Пример #1
0
 private void _export_Click(object sender, RoutedEventArgs e)
 {
     //打开对话框
     System.Windows.Forms.SaveFileDialog saveFile = new System.Windows.Forms.SaveFileDialog();
     saveFile.Filter = "JPG(*.jpg)|*.jpg";
     saveFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
     if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
     {
         return;
     }
     var saveFilePath = saveFile.FileName;
     if (saveFilePath != "")
     {
         if (web != null)
         {
             if (web.ReadyState == System.Windows.Forms.WebBrowserReadyState.Complete)
             {
                 System.Drawing.Rectangle r = web.Document.Body.ScrollRectangle;
                 web.Height = r.Height;
                 web.Width = r.Width;
                 Bitmap bitMapPic = new Bitmap(r.Width, r.Height);
                 web.DrawToBitmap(bitMapPic, r);
                 bitMapPic.Save(saveFilePath);
                 Toolkit.MessageBox.Show("文件导出成功!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
             }
         }
     }
 }
Пример #2
0
        private void DoAction(Mine2D game, int buttonNumber)
        {
            switch (buttonNumber)
            {
                case 0:
                    game.gameState = GameState.Playing;
                    break;

                case 1:
                    System.Windows.Forms.SaveFileDialog saveWorld = new System.Windows.Forms.SaveFileDialog();
                    saveWorld.Filter = "Сжатые миры Mine2D|*.m2d";
                    if (saveWorld.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        game.gameState = GameState.SavingWorld;
                        new System.Threading.Thread(delegate()
                        {
                            LevelManager.SaveLevel(game, saveWorld.FileName);
                        }).Start();
                    }
                    break;

                case 2:
                    LevelManager.RecreateLevel(game);
                    game.gameState = GameState.MainMenu;
                    break;
            }
        }
Пример #3
0
		void menuitem_Click(object sender, EventArgs e)
		{
			if (_host.Chats.Length != 0) {
				System.Windows.Forms.SaveFileDialog sf = new System.Windows.Forms.SaveFileDialog();
				sf.DefaultExt = ".xml";
				sf.Filter = "XMLファイル(*.xml)|*.xml";
				sf.FileName = "export_" + _host.Id + ".xml";
				if (sf.ShowDialog((System.Windows.Forms.IWin32Window)_host.Win32WindowOwner) == System.Windows.Forms.DialogResult.OK) {
					string xml = buildNicoXML();
					if (xml != null) {
						try {
							using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sf.FileName)) {
								sw.WriteLine(xml);
								sw.Close();
							}

							_host.ShowStatusMessage("エクスポートに成功しました。");

						} catch (Exception ex) {
							NicoApiSharp.Logger.Default.LogException(ex);
							_host.ShowFaitalMessage("エクスポートに失敗しました。詳しい情報はログファイルを参照してください");
						}
					}
				}
			}
		}
Пример #4
0
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txbAPIKey.Text) || string.IsNullOrEmpty(txbEventId.Text))
            {
                MessageBox.Show("Please enter all the information on the form.", "Export", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            //load data from meetup should be async
            IMeetupService service = new MeetupService(new MeetupRepository(txbAPIKey.Text));
            IList<RsvpItem> rsvpItems = service.GetRsvpsForEvent(long.Parse(txbEventId.Text));

            //export it
            var saveFileDialog = new SaveFileDialog
                         {
                             InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                             DefaultExt = "csv",
                             AddExtension = true,
                             Filter = @"CSV Files (*.csv)|*.csv"
                         };

            if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    File.WriteAllText(saveFileDialog.FileName, new RsvpManager().GetAttendees(rsvpItems).ToCsv(true));
                    MessageBox.Show("Export done.", "Export", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch
                {
                    MessageBox.Show("Export Failed.", "Export", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Пример #5
0
        public override void OnClick()
        {
            System.Data.IDbConnection resultConnection = CheckApplication.CurrentTask.ResultConnection as System.Data.OleDb.OleDbConnection;
            if (resultConnection == null)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("��ǰ����״̬�����Ϊ�Ѵ����������������ѱ��Ƴ���");
                return;
            }

            System.Windows.Forms.SaveFileDialog dlgShpFile = new System.Windows.Forms.SaveFileDialog();
            dlgShpFile.FileName = Environment.CurrentDirectory + "\\" + CheckApplication.CurrentTask.Name + ".xls";
            dlgShpFile.Filter = "SHP �ļ�|*.Shp";
            if (dlgShpFile.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;

            string strFile = dlgShpFile.FileName;
            string strPath = System.IO.Path.GetDirectoryName(strFile);
            string strName = System.IO.Path.GetFileNameWithoutExtension(strFile);

            Hy.Check.Task.Task curTask = CheckApplication.CurrentTask;
               ErrorExporter exporter = new ErrorExporter();
            exporter.BaseWorkspace = curTask.BaseWorkspace;
            exporter.ResultConnection = curTask.ResultConnection;
            exporter.SchemaID = curTask.SchemaID;
            exporter.Topology = curTask.Topology;
            exporter.ExportToShp(strPath, strName);
        }
Пример #6
0
        protected override void OnClick()
        {
            if (IsExportMode)
            {
                var saveFile = new System.Windows.Forms.SaveFileDialog();
                saveFile.AddExtension = true;
                saveFile.AutoUpgradeEnabled = true;
                saveFile.CheckPathExists = true;
                saveFile.DefaultExt = ExportModeDefaultExtension;
                saveFile.Filter = ExportModeExtensionFilter;
                saveFile.FilterIndex = 0;
                var result = saveFile.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    var fileName = saveFile.FileName;
                    this.CommandParameter = fileName;
                    base.OnClick();
                }
            }
            else
            {
                base.OnClick();
            }
        }
        private void btnAddData_Click(object sender, EventArgs e)
        {
            /////////////////////////////////
            //Replace with something that uses the default data provider
            System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
            sfd.OverwritePrompt = true;
            sfd.Filter = "Shape Files|*.shp";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                IFeatureSet _addedFeatureSet = new MapWindow.Data.Shapefile();
                _addedFeatureSet.Filename = sfd.FileName;

                //If the features set is null do nothing the user probably hit cancel
                if (_addedFeatureSet == null)
                    return;

                //If the feature type is good save it
                else
                {
                    //This inserts the new featureset into the list
                    textBox1.Text = System.IO.Path.GetFileNameWithoutExtension(_addedFeatureSet.Filename);
                    base.Param.Value = _addedFeatureSet;
                    base.Status = ToolStatus.Ok;
                    base.LightTipText = MapWindow.MessageStrings.FeaturesetValid;
                }
            }
        }
Пример #8
0
        private void saveBtn_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog save = new System.Windows.Forms.SaveFileDialog();
            save.DefaultExt = "txt";
            save.Filter = Strings.GetLabelString("TxtFileDescriptionPlural") + "|*.txt|" + Strings.GetLabelString("AllFileDescriptionPlural") + "|*";
            save.Title = Strings.GetLabelString("SaveReportQuestion");

            if (AAnalyzer.LastSavePath == null)
                save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            else
                save.InitialDirectory = AAnalyzer.LastSavePath;

            save.FileName = analyzer.game.Name + ".txt";
            if (save.ShowDialog(this.GetIWin32Window()) != System.Windows.Forms.DialogResult.Cancel) {
                AAnalyzer.LastSavePath = Path.GetDirectoryName(save.FileName);
                try {
                    StreamWriter writer = File.CreateText(save.FileName);
                    writer.Write(reportTxt.Text);
                    writer.Close();
                    saved = true;
                } catch (Exception ex) {
                    TranslatingMessageHandler.SendError("WriteError", ex, save.FileName);
                }
            }
        }
Пример #9
0
 public static void SaveTheme(this MsDev2013_Theme theme)
 {
     using (var sfd = new System.Windows.Forms.SaveFileDialog() { Filter = "YAML File|*.yml" })
       {
     if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
     theme.SaveTheme(sfd.FileName);
       }
 }
Пример #10
0
 /// <summary>                                                                                                                                                        
 /// 导出用户选择的XML文件                                                                                                                                                
 /// </summary>                                                                                                                                                           
 /// <param name="ds">DataSet</param>                                                                                                                                     
 public void ExportToXML(DataSet ds)
 {
     System.Windows.Forms.SaveFileDialog saveFileDlg = new System.Windows.Forms.SaveFileDialog();
     saveFileDlg.DefaultExt = "xml";
     saveFileDlg.Filter = "xml文件 (*.xml)|*.xml";
     if (saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         doExportXML(ds, saveFileDlg.FileName);
 }
Пример #11
0
        private void btnSaveImg_Click(object sender, RoutedEventArgs e)
        {
            var sfd = new System.Windows.Forms.SaveFileDialog
	                      {
		                      Title = "Select where do you want to save the Screenshot", 
							  Filter = "PNG Image (*.png)|*.png"
	                      };
	        if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                SaveImage(sfd.FileName);
        }
Пример #12
0
 private void SaveAsMenuItem_Click(object sender, RoutedEventArgs e)
 {
     System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
     dialog.DefaultExt = ".bvh";
     dialog.Filter = "BVHファイル(*.bvh)|*.bvh";
     if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         bvhTo.BVH.Save(dialog.FileName);
     }
 }
Пример #13
0
 private void ButtonScreenshot_OnClick(object sender, RoutedEventArgs e)
 {
     System.Windows.Forms.SaveFileDialog Dialog = new System.Windows.Forms.SaveFileDialog
     {
         Filter = "PNG|*.png|MRC|*.mrc"
     };
     System.Windows.Forms.DialogResult Result = Dialog.ShowDialog();
     if (Result == System.Windows.Forms.DialogResult.OK)
     {
         Viewport.GrabScreenshot(Dialog.FileName);
     }
 }
Пример #14
0
 private void btnExport_Click(object sender, RoutedEventArgs e) {
     using(SaveFileDialog sf = new SaveFileDialog()) {
         // todo: localize?
         sf.Filter = "Registry file (*.reg)|*.reg";
         sf.RestoreDirectory = true;
         DateTime dt = DateTime.Now;
         sf.FileName = "QTTabBarSettings-" + dt.Year + "-" + dt.Month + "-" + dt.Day + ".reg";
         if(DialogResult.OK == sf.ShowDialog()) {
             RegFileWriter.Export(RegConst.Root, sf.FileName);
         }
     }
 }
        public static void SaveProject(TestProject testProject, bool showDialogAlways = false)
        {
            System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog.Title = "Save test project";
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.InitialDirectory = Directory.GetCurrentDirectory();
            saveFileDialog.Filter = "Controller Tester Projects (*.fmpx) | *.fmpx";
            saveFileDialog.FileName = testProject.Name;

            if (showDialogAlways == true || testProject.Path == null)
            {
                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (!saveFileDialog.FileName.Contains(".fmpx"))
                    {
                        testProject.Name = Path.GetFileNameWithoutExtension(saveFileDialog.FileName);
                        testProject.Path = saveFileDialog.FileName + ".fmpx";
                    }
                    else
                    {
                        testProject.Name = Path.GetFileNameWithoutExtension(saveFileDialog.FileName);
                        testProject.Path = saveFileDialog.FileName;
                    }
                }
                else
                {
                    return;
                }
            }

            if (testProject.Path != null)
            {
                FileStream f = File.Create(testProject.Path);

                var listOfFaultModelAssemblies = (from lAssembly in AppDomain.CurrentDomain.GetAssemblies()
                                                  where lAssembly.FullName.Contains("FaultModel")
                                                  select lAssembly).ToArray();
                var extraTypes = (from lAssembly in listOfFaultModelAssemblies
                                  from lType in lAssembly.GetTypes()
                                  where lType.IsSubclassOf(typeof(FM4CC.Environment.FaultModelConfiguration))
                                  select lType).ToArray();
                var extraTypes2 = (from lAssembly in listOfFaultModelAssemblies
                                   from lType in lAssembly.GetTypes()
                                   where lType.IsSubclassOf(typeof(FM4CC.TestCase.FaultModelTesterTestCase))
                                   select lType).ToArray();
                XmlSerializer xsSubmit = new XmlSerializer(typeof(TestProject), extraTypes.Concat(extraTypes2).ToArray());

                XmlWriter writer = XmlWriter.Create(f);
                xsSubmit.Serialize(writer, testProject);

                f.Close();
            }
        }
Пример #16
0
 public void ExportMapBehavior(object sender, TomShane.Neoforce.Controls.EventArgs e)
 {
     Button btn = (Button)sender;
     btn.Focused = false;
     System.Windows.Forms.SaveFileDialog exportMapDialog = new System.Windows.Forms.SaveFileDialog();
     exportMapDialog.InitialDirectory = Convert.ToString(Environment.SpecialFolder.CommonProgramFilesX86);
     exportMapDialog.Filter = "Map files (*.datmap)|*.datmap";
     exportMapDialog.FilterIndex = 1;
     exportMapDialog.Title = "Export your map";
     exportMapDialog.FileOk += new System.ComponentModel.CancelEventHandler(SuccessfullyExportedMap);
     exportMapDialog.ShowDialog();
 }
 public void Save(TestDepthFrame frame)
 {
     using (var dialog = new System.Windows.Forms.SaveFileDialog())
     {
         dialog.Filter = this.fileDialogFilter;
         dialog.FileName = frame.Id + ".xfrm";
         if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         {
             new TestFrameRepository().Save(frame.ToTestDepthFrame(), dialog.FileName);
         }
     }
 }
Пример #18
0
        private void SelectFileButton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog fileDialog = new System.Windows.Forms.SaveFileDialog();
            fileDialog.FileName = DateTime.Now.ToString("yyyy-MM") + ".csv";
            fileDialog.AddExtension = true;
            fileDialog.OverwritePrompt = true;
            fileDialog.RestoreDirectory = false;
            fileDialog.Filter = "CSV (*.csv)|*.csv|All files (*.*)|*.*";

            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                FilenameTextBox.Text = fileDialog.FileName;
        }
 private void btnXuat_Click(object sender, RoutedEventArgs e)
 {
     System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
     dlg.InitialDirectory = mTranSit.DuongDanHinh;
     dlg.Filter = "Excel Files | *.xlsx";
     if (dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK)
     {
         //ExportImport.ImportExportProcess.Export(dlg.FileName);
         //mImportExportProcess.Export(dlg.FileName);                
         mImportExportProcess.ExportItem(dlg.FileName);
     }
 }
            /// <summary>
            /// Writes a Pac1 file. [Useable by scripts and interface components alike.]
            /// </summary>
            /// <param name="Direct_Data">Array of Completed Direct Sound Simulations Required</param>
            /// <param name="IS_Data">Array of Completed Image Source Simulations. Enter null if opted out.</param>
            /// <param name="Receiver">Array of Completed Ray-Tracing Simulation Receivers. Enter null if opted out.</param>
            public static void Write_Pac1(Direct_Sound[] Direct_Data, ImageSourceData[] IS_Data = null, Environment.Receiver_Bank[] Receiver = null)
            {
                System.Windows.Forms.SaveFileDialog sf = new System.Windows.Forms.SaveFileDialog();
                sf.DefaultExt = ".pac1";
                sf.AddExtension = true;
                sf.Filter = "Pachyderm Ray Data file (*.pac1)|*.pac1|" + "All Files|";

                if (sf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    Write_Pac1(sf.FileName, Direct_Data, IS_Data, Receiver);
                }
            }
Пример #21
0
 private void ExportButton_Click(object sender, RoutedEventArgs e)
 {
     System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
     dialog.Filter = "Sql files(*.sql)|*.sql|All Files (*.*)|*.*";
     dialog.Title = "Enter name of file to back up data";
     if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         string file_name = dialog.FileName;
         if (Onion.MySQLHandler.MySQLHelper.BackUp(file_name))
             MessageBox.Show("Database exported successfully");
     }
 }
 /// <summary>
 /// 选择保存路径
 /// </summary>
 /// <param name="title"></param>
 /// <param name="filter"></param>
 /// <returns></returns>
 public static string SelectAndSavePath(string title, string filter)
 {
     var sp = new System.Windows.Forms.SaveFileDialog
         {
             Title = title,
             RestoreDirectory = true,
             Filter = filter
         };
     if (sp.ShowDialog() != System.Windows.Forms.DialogResult.OK) return null;
     var oppath = sp.FileName;
     return oppath;
 }
Пример #23
0
        public DocumentsPlugin()
        {
            state = new DocumentsState();

            EventBroker.Subscribe(AppEvents.View, delegate(Document document)
                {
                    string sourceFilename = ClientState.Current.Storage.ResolvePhysicalFilename(".", document.StreamName);
                    string targetFileName = document.Filename;

                    int i = 0;

                    while (true)
                    {
                        if (i > 0)
                        {
                            targetFileName = String.Format("{0} ({1}){2}",
                                Path.GetFileNameWithoutExtension(document.Filename), i,
                                Path.GetExtension(document.Filename));
                        }

                        if (File.Exists(Path.Combine(Path.GetTempPath(), targetFileName)))
                        {
                            i++;
                            continue;
                        }

                        break;
                    }

                    var targetFilename = Path.Combine(Path.GetTempPath(), targetFileName);

                    File.Copy(sourceFilename, targetFilename);

                    new Process { StartInfo = new ProcessStartInfo(targetFilename) }.Start();
                });

            EventBroker.Subscribe(AppEvents.Save, delegate(Document document)
            {
                var dialog = new System.Windows.Forms.SaveFileDialog();
                dialog.FileName = document.Filename;
                dialog.Filter = String.Format("{0} files (*.{0})|*.{0}|All files (*.*)|*.*",
                    Path.GetExtension(document.Filename));

                var result = dialog.ShowDialog();

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    string filename = ClientState.Current.Storage.ResolvePhysicalFilename(".", document.StreamName);
                    File.Copy(filename, dialog.FileName);
                }
            });
        }
Пример #24
0
        private void btnExcel_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog fileDialog = new System.Windows.Forms.SaveFileDialog();
            fileDialog.Title = "导出Excel";
            fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";
            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //DevExpress.XtraPrinting.XlsxExportOptions options = new DevExpress.XtraPrinting.XlsxExportOptions;
                ((TableView)gridMain.View).ExportToXlsx(fileDialog.FileName);

                MessageBox.Show("导出成功!", "提示");
            }
        }
Пример #25
0
 private void Browse_Click(object sender, System.Windows.RoutedEventArgs e)
 {
     System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
     sfd.Filter = _filterString;
     if (this.Value != null)
     {
         sfd.FileName = (string)this.Value;
     }
     if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         this.Value = sfd.FileName;
     }
 }
Пример #26
0
 private void saveButton_Click(object sender, RoutedEventArgs e)
 {
     System.Windows.Forms.SaveFileDialog saveLog = new System.Windows.Forms.SaveFileDialog();
     saveLog.Filter = "Logging-Files (*.log)|*.log|All files (*.*)|*.*";
     saveLog.FilterIndex = 1;
     saveLog.RestoreDirectory = true;
     if (saveLog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
         StreamWriter sw = new StreamWriter(saveLog.FileName, false, Encoding.Default);
         sw.Write(textBlock.Text);
         sw.Flush();
         sw.Close();
     }
 }
        public static void SaveStringAs(string stringToSave, System.Windows.Forms.IWin32Window owner)
        {
            System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog.AddExtension = true;
            saveFileDialog.DefaultExt = "txt";
            saveFileDialog.Filter = "Text Files (*.txt)|*.txt";
            saveFileDialog.OverwritePrompt = false;

            System.Windows.Forms.DialogResult result;
            if (owner != null)
                result = saveFileDialog.ShowDialog(owner);
            else
                result = saveFileDialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK || result == System.Windows.Forms.DialogResult.Yes)
            {
                StreamWriter writer = new StreamWriter(saveFileDialog.FileName, false);
                writer.Write(stringToSave);
                writer.Close();
                //				MessageDialog.ShowMessage("Files Saved in " + saveFileDialog.FileName);
                System.Diagnostics.Process.Start("Notepad.exe", saveFileDialog.FileName);
            }
        }
Пример #28
0
        /// <summary>
        /// 初始化View
        /// </summary>
        private void InitView()
        {
            //Excel文件路径
            this.btnChooseExcelFile.Click += delegate(object sender, RoutedEventArgs args)
            {
                System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog();
                fileDialog.Filter = "Excel文件|*.xlsx";
                if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    //初始化文件转换器
                    excelToXmlConverter = new ExcelToXmlConverter(fileDialog.FileName);
                    this.tboxExcelFilePath.Text = fileDialog.FileName;
                    //检测Excel数据是否可用
                    if (!excelToXmlConverter.IsDataValid())
                    {
                        MessageBox.Show("Excel输入文件数据格式有误!", "提示");
                        this.tboxExcelFilePath.Text = "";
                    }
                }
            };

            //Xml输出路径
            this.btnChooseOutputPath.Click += delegate(object sender, RoutedEventArgs args)
            {
                System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
                saveFileDialog.Filter = "Xml|*.xml";
                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    //初始化输出路径
                    outputPath = saveFileDialog.FileName;
                    this.tboxOutputPath.Text = saveFileDialog.FileName;
                }
            };

            //生成Xml文件
            this.btnGenerateXmlFile.Click += delegate(object sender, RoutedEventArgs args)
            {
                //文件转换器已初始化 excel路径已有 输出路径已有
                if (excelToXmlConverter != null && outputPath != null)
                {
                    excelToXmlConverter.ExportXmlFile(outputPath);
                    MessageBox.Show("文件生成完毕", "提示");
                }
                else
                {
                    MessageBox.Show("请先选择输入输出路径", "提示");
                }
            };
        }
Пример #29
0
        private void pdfButton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog fileDialog = new System.Windows.Forms.SaveFileDialog();
            fileDialog.Title = "Specify output pdf file";
            fileDialog.Filter = "pdf file|*.pdf";
            fileDialog.RestoreDirectory = true;
            fileDialog.FileName = outputPdfPath;

            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                outputPdfPath = fileDialog.FileName;
                checkPlayButton();

            }
        }
Пример #30
0
        public static void Save(Document document)
        {
            var dialog = new System.Windows.Forms.SaveFileDialog();
            dialog.FileName = document.Filename;
            dialog.Filter = String.Format("{0} files (*.{0})|*.{0}|All files (*.*)|*.*",
                Path.GetExtension(document.Filename));

            var result = dialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                string filename = ClientState.Current.Storage.ResolvePhysicalFilename(".", document.StreamName);
                File.Copy(filename, dialog.FileName);
            }
        }
        private async void ButtonWrite_OnClick(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog SaveDialog = new System.Windows.Forms.SaveFileDialog
            {
                Filter = "STAR Files|*.star"
            };
            System.Windows.Forms.DialogResult ResultSave = SaveDialog.ShowDialog();

            if (ResultSave.ToString() == "OK")
            {
                ExportPath = SaveDialog.FileName;
            }
            else
            {
                return;
            }

            decimal _OutputAngPix = OutputAngPix;
            int     _BoxSize      = BoxSize;
            int     _Diameter     = Diameter;

            bool _ReconstructVolume = ReconstructVolume;
            bool _ReconstructSeries = ReconstructSeries;

            bool    _ApplyShift = ApplyShift;
            decimal _ShiftX     = ShiftX;
            decimal _ShiftY     = ShiftY;
            decimal _ShiftZ     = ShiftZ;

            bool _ReconstructPrerotated  = ReconstructPrerotated;
            bool _ReconstructDoLimitDose = ReconstructDoLimitDose;
            int  _ReconstructNTilts      = ReconstructNTilts;

            bool _InputInvert           = InputInvert;
            bool _InputNormalize        = InputNormalize;
            bool _OutputNormalize       = OutputNormalize;
            bool _ReconstructMakeSparse = ReconstructMakeSparse;

            if (!_ReconstructVolume)
            {
                _ReconstructPrerotated = true;
            }

            float3 AdditionalShiftAngstrom = new float3((float)_ShiftX,
                                                        (float)_ShiftY,
                                                        (float)_ShiftZ);

            ProgressWrite.Visibility      = Visibility.Visible;
            ProgressWrite.IsIndeterminate = true;
            PanelButtons.Visibility       = Visibility.Collapsed;
            PanelRemaining.Visibility     = Visibility.Visible;

            foreach (var element in DisableWhileProcessing)
            {
                element.IsEnabled = false;
            }

            MainWindow MainWindow = (MainWindow)Application.Current.MainWindow;

            await Task.Run(() =>
            {
                List <Star> AllSourceTables = new List <Star>();
                string[] AllSourceHashes    = Helper.GetUniqueElements(Species.Particles.Select(p => p.SourceHash)).ToArray();
                AllSourceHashes             = AllSourceHashes.Where(h => Sources.Any(s => s.Files.ContainsKey(h))).ToArray();

                foreach (var source in Sources)
                {
                    if (!source.IsTiltSeries)
                    {
                        continue;
                    }

                    #region Get all movies that can potentially be used

                    List <string> ValidSourceHashes = AllSourceHashes.Where(h => source.Files.ContainsKey(h)).ToList();
                    List <string> ValidSourcePaths  = ValidSourceHashes.Select(k => System.IO.Path.Combine(source.FolderPath, source.Files[k])).ToList();
                    List <string> ValidMovieNames   = ValidSourcePaths.Select(p => Helper.PathToName(p)).ToList();
                    List <TiltSeries> ValidSeries   = ValidSourcePaths.Select(p => new TiltSeries(p)).ToList();

                    List <Particle> Particles = Species.Particles.Where(p => ValidSourceHashes.Contains(p.SourceHash)).ToList();
                    Particles.Sort((a, b) => a.SourceHash.CompareTo(b.SourceHash));

                    #endregion

                    if (IsCanceled)
                    {
                        return;
                    }

                    #region Create worker processes

                    int NDevices                   = GPU.GetDeviceCount();
                    List <int> UsedDevices         = MainWindow.GetDeviceList();
                    List <int> UsedDeviceProcesses = Helper.Combine(Helper.ArrayOfFunction(i => UsedDevices.Select(d => d + i *NDevices).ToArray(), 1)).ToList();

                    WorkerWrapper[] Workers = new WorkerWrapper[GPU.GetDeviceCount() * 1];
                    foreach (var gpuID in UsedDeviceProcesses)
                    {
                        Workers[gpuID] = new WorkerWrapper(gpuID);
                        Workers[gpuID].SetHeaderlessParams(new int2(1, 1),
                                                           0,
                                                           "float32");

                        Workers[gpuID].LoadGainRef(source.GainPath,
                                                   source.GainFlipX,
                                                   source.GainFlipY,
                                                   source.GainTranspose,
                                                   source.DefectsPath);
                    }

                    #endregion

                    List <Star> SourceTables = new List <Star>();

                    {
                        Dispatcher.Invoke(() => ProgressWrite.MaxValue = AllSourceHashes.Length);

                        Helper.ForEachGPU(ValidSeries, (series, gpuID) =>
                        {
                            if (IsCanceled)
                            {
                                return;
                            }

                            Stopwatch ItemTime = new Stopwatch();
                            ItemTime.Start();

                            string SeriesHash = series.GetDataHash();

                            Star TableOut = new Star(new string[] { "rlnMagnification",
                                                                    "rlnDetectorPixelSize",
                                                                    "rlnCoordinateX",
                                                                    "rlnCoordinateY",
                                                                    "rlnCoordinateZ",
                                                                    "rlnAngleRot",
                                                                    "rlnAngleTilt",
                                                                    "rlnAnglePsi",
                                                                    "rlnImageName",
                                                                    "rlnCtfImage",
                                                                    "rlnRandomSubset" });

                            ProcessingOptionsTomoSubReconstruction ExportOptions = new ProcessingOptionsTomoSubReconstruction()
                            {
                                PixelSizeX     = source.PixelSizeX,
                                PixelSizeY     = source.PixelSizeY,
                                PixelSizeAngle = source.PixelSizeAngle,

                                BinTimes      = (decimal)Math.Log((double)(_OutputAngPix / source.PixelSizeMean), 2.0),
                                GainPath      = source.GainPath,
                                DefectsPath   = source.DefectsPath,
                                GainFlipX     = source.GainFlipX,
                                GainFlipY     = source.GainFlipY,
                                GainTranspose = source.GainTranspose,

                                Dimensions = new float3((float)source.DimensionsX,
                                                        (float)source.DimensionsY,
                                                        (float)source.DimensionsZ),

                                Suffix = "_" + Species.NameSafe,

                                BoxSize          = _BoxSize,
                                ParticleDiameter = _Diameter,

                                Invert          = _InputInvert,
                                NormalizeInput  = _InputNormalize,
                                NormalizeOutput = _OutputNormalize,

                                PrerotateParticles = _ReconstructPrerotated,
                                DoLimitDose        = _ReconstructDoLimitDose,
                                NTilts             = Math.Min(series.NTilts, Math.Min(source.FrameLimit, _ReconstructNTilts)),

                                MakeSparse = _ReconstructMakeSparse
                            };

                            Particle[] SeriesParticles = Particles.Where(p => p.SourceHash == SeriesHash).ToArray();
                            int NParticles             = SeriesParticles.Length;

                            #region Process particle positions and angles

                            float3[] Positions         = new float3[NParticles *series.NTilts];
                            float3[] Angles            = new float3[NParticles *series.NTilts];
                            int[] Subsets              = SeriesParticles.Select(p => p.RandomSubset + 1).ToArray();
                            float MinDose              = MathHelper.Min(series.Dose);
                            float MaxDose              = MathHelper.Max(series.Dose);
                            float[] InterpolationSteps = Helper.ArrayOfFunction(i => (series.Dose[i] - MinDose) / (MaxDose - MinDose), series.NTilts);

                            for (int p = 0; p < NParticles; p++)
                            {
                                float3[] ParticlePositions = SeriesParticles[p].GetCoordinateSeries(InterpolationSteps);
                                float3[] ParticleAngles    = SeriesParticles[p].GetAngleSeries(InterpolationSteps);

                                if (_ApplyShift)
                                {
                                    Matrix3 R0          = Matrix3.Euler(ParticleAngles[0] * Helper.ToRad);
                                    float3 RotatedShift = R0 *AdditionalShiftAngstrom;

                                    for (int t = 0; t < ParticlePositions.Length; t++)
                                    {
                                        ParticlePositions[t] += RotatedShift;
                                    }
                                }

                                if (!_ReconstructPrerotated)
                                {
                                    Matrix3 R0I = Matrix3.Euler(ParticleAngles[0] * Helper.ToRad).Transposed();

                                    for (int t = 0; t < ParticleAngles.Length; t++)
                                    {
                                        ParticleAngles[t] = Matrix3.EulerFromMatrix(R0I *Matrix3.Euler(ParticleAngles[t] * Helper.ToRad)) * Helper.ToDeg;
                                    }
                                }

                                for (int t = 0; t < series.NTilts; t++)
                                {
                                    Positions[p *series.NTilts + t] = ParticlePositions[t];
                                    Angles[p *series.NTilts + t]    = ParticleAngles[t];
                                }

                                string PathSubtomo = series.SubtomoDir + $"{series.RootName}{ExportOptions.Suffix}_{p:D7}_{ExportOptions.BinnedPixelSizeMean:F2}A.mrc";
                                string PathCTF     = (series.SubtomoDir + $"{series.RootName}{ExportOptions.Suffix}_{p:D7}_ctf_{ExportOptions.BinnedPixelSizeMean:F2}A.mrc");

                                Uri UriStar = new Uri(ExportPath);
                                PathSubtomo = UriStar.MakeRelativeUri(new Uri(PathSubtomo)).ToString();
                                PathCTF     = UriStar.MakeRelativeUri(new Uri(PathCTF)).ToString();

                                TableOut.AddRow(new List <string>()
                                {
                                    "10000.0",
                                    ExportOptions.BinnedPixelSizeMean.ToString("F5", CultureInfo.InvariantCulture),
                                    (ParticlePositions[0].X / (float)ExportOptions.BinnedPixelSizeMean).ToString("F5", CultureInfo.InvariantCulture),
                                    (ParticlePositions[0].Y / (float)ExportOptions.BinnedPixelSizeMean).ToString("F5", CultureInfo.InvariantCulture),
                                    (ParticlePositions[0].Z / (float)ExportOptions.BinnedPixelSizeMean).ToString("F5", CultureInfo.InvariantCulture),
                                    (_ReconstructPrerotated ? 0 : SeriesParticles[p].Angles[0].X).ToString("F5", CultureInfo.InvariantCulture),
                                    (_ReconstructPrerotated ? 0 : SeriesParticles[p].Angles[0].Y).ToString("F5", CultureInfo.InvariantCulture),
                                    (_ReconstructPrerotated ? 0 : SeriesParticles[p].Angles[0].Z).ToString("F5", CultureInfo.InvariantCulture),
                                    PathSubtomo,
                                    PathCTF,
                                    Subsets[p].ToString()
                                });
                            }

                            #endregion

                            #region Finally, reconstruct the actual sub-tomos

                            if (_ReconstructVolume)
                            {
                                Workers[gpuID].TomoExportParticles(series.Path, ExportOptions, Positions, Angles);
                            }
                            else
                            {
                                series.ReconstructParticleSeries(ExportOptions, Positions, Angles, Subsets, ExportPath, out TableOut);
                            }

                            lock (AllSourceTables)
                                AllSourceTables.Add(TableOut);

                            #endregion

                            #region Add this micrograph's table to global collection, update remaining time estimate

                            lock (AllSourceTables)
                            {
                                Timings.Add(ItemTime.ElapsedMilliseconds / (float)UsedDeviceProcesses.Count);

                                int MsRemaining        = (int)(MathHelper.Mean(Timings) * (AllSourceHashes.Length - AllSourceTables.Count));
                                TimeSpan SpanRemaining = new TimeSpan(0, 0, 0, 0, MsRemaining);

                                Dispatcher.Invoke(() => TextRemaining.Text = SpanRemaining.ToString((int)SpanRemaining.TotalHours > 0 ? @"hh\:mm\:ss" : @"mm\:ss"));

                                Dispatcher.Invoke(() =>
                                {
                                    ProgressWrite.IsIndeterminate = false;
                                    ProgressWrite.Value           = AllSourceTables.Count;
                                });
                            }

                            #endregion
                        }, 1, UsedDeviceProcesses);
                    }

                    Thread.Sleep(10000);    // Writing out particles is async, so if workers are killed immediately they may not write out everything

                    foreach (var worker in Workers)
                    {
                        worker?.Dispose();
                    }

                    if (IsCanceled)
                    {
                        return;
                    }
                }

                if (AllSourceTables.Count > 0)
                {
                    (new Star(AllSourceTables.ToArray())).Save(ExportPath);
                }
            });

            Close?.Invoke();
        }
Пример #32
0
        public void ExportToCSVFile()
        {
            var acDoc = AcAp.DocumentManager.MdiActiveDocument;
            var acDb  = acDoc.Database;
            var ed    = acDoc.Editor;


            var filter = new SelectionFilter(new[]
            {
                new TypedValue(-4, "OR"),
                new TypedValue(0, "ARC,CIRCLE,ELLIPSE,LINE,LWPOLYLINE,SPLINE"),
                new TypedValue(-4, "AND"),
                new TypedValue(0, "POLYLINE"),
                new TypedValue(-4, "NOT"),
                new TypedValue(-4, "&"),
                new TypedValue(70, 112),
                new TypedValue(-4, "NOT>"),
                new TypedValue(-4, "AND>"),
                new TypedValue(-4, "OR>"),
            });

            PromptSelectionResult selection = ed.GetSelection(filter);

            if (selection.Status == PromptStatus.OK)
            {
                return;
            }

            sw.Forms.SaveFileDialog sfd = new sw.Forms.SaveFileDialog();
            sfd.Filter = "*.csv Files|*.csv";

            try
            {
                using (Transaction acTrans = acDb.TransactionManager.StartTransaction())
                {
                    sfd.ShowDialog();
                    string filename = sfd.FileName;

                    if (filename != "")
                    {
                        StreamWriter sWriter;
                        sWriter = GetWriterForFile(filename);

                        var lengths = selection.Value
                                      .Cast <SelectedObject>()
                                      .Select(selObj => (Curve)acTrans.GetObject(selObj.ObjectId, OpenMode.ForRead))
                                      .ToLookup(curve => curve.GetType().Name,                         // <- key selector
                                                curve => curve.GetDistanceAtParameter(curve.EndParam)) // <- element selector
                                      .ToDictionary(group => group.Key,                                // <- key selector
                                                    group => group.Sum());                             // <- element selector

                        // print results
                        foreach (var entry in lengths)
                        {
                            sWriter.WriteLine($"\n{entry.Key,-12} , {entry.Value,9:0.00}");
                        }
                    }
                    else
                    {
                        ed.WriteMessage("\nHa, you're joking, right?");
                    }
                }
            }
            catch
            {
                ed.WriteMessage("\nI don't know how to write....");
            }
        }
Пример #33
0
        /// <summary>
        /// 엑셀다운로드
        /// </summary>
        /// <param name="obj"></param>
        private void ExcelDownAction(object obj)
        {
            try
            {
                /// 데이터조회
                Hashtable conditions = new Hashtable();
                conditions.Add("CNT_CDE", cbCNT_CDE.EditValue);
                conditions.Add("CNT_NUM", txtCNT_NUM.Text.Trim());
                conditions.Add("CNT_NAM", txtCNT_NAM.Text.Trim());
                //conditions.Add("FTR_IDN", FmsUtil.Trim(txtFTR_IDN.EditValue));
                conditions.Add("TCT_AMT_FROM", txtTCT_AMT_FROM.EditValue);
                conditions.Add("TCT_AMT_TO", txtTCT_AMT_TO.EditValue);

                try
                {
                    conditions.Add("BEG_YMD_FROM", dtBEG_YMD_FROM.EditValue == null ? null : Convert.ToDateTime(dtBEG_YMD_FROM.EditValue).ToString("yyyyMMdd"));
                    conditions.Add("BEG_YMD_TO", dtBEG_YMD_TO.EditValue == null ? null : Convert.ToDateTime(dtBEG_YMD_TO.EditValue).ToString("yyyyMMdd"));
                }
                catch (Exception) { }
                try
                {
                    conditions.Add("FNS_YMD_FROM", dtFNS_YMD_FROM.EditValue == null ? null : Convert.ToDateTime(dtFNS_YMD_FROM.EditValue).ToString("yyyyMMdd"));
                    conditions.Add("FNS_YMD_TO", dtFNS_YMD_TO.EditValue == null ? null : Convert.ToDateTime(dtFNS_YMD_TO.EditValue).ToString("yyyyMMdd"));
                }
                catch (Exception) { }
                if (!BizUtil.ValidDateBtw(conditions["TCT_AMT_FROM"], conditions["TCT_AMT_TO"]))
                {
                    Messages.ShowInfoMsgBox("계약금액 범위를 확인하세요");
                    return;
                }
                if (!BizUtil.ValidDateBtw(conditions["BEG_YMD_FROM"], conditions["BEG_YMD_TO"]))
                {
                    Messages.ShowInfoMsgBox("착공일자 범위를 확인하세요");
                    return;
                }
                if (!BizUtil.ValidDateBtw(conditions["FNS_YMD_FROM"], conditions["FNS_YMD_TO"]))
                {
                    Messages.ShowInfoMsgBox("준공일자 범위를 확인하세요");
                    return;
                }
                conditions.Add("CTT_CDE", cbCTT_CDE.EditValue);
                conditions.Add("CNT_LOC", txtCNT_LOC.Text.Trim());

                conditions.Add("page", 0);
                conditions.Add("rows", 1000000);

                conditions.Add("sqlId", "SelectWttConsMaList");


                exceldt = BizUtil.SelectList(conditions);


                //그리드헤더정보 추출
                columnList = new GridColumn[grid.Columns.Count];
                grid.Columns.CopyTo(columnList, 0);
                listCols = new List <string>(); //컬럼헤더정보 가져오기
                foreach (GridColumn gcol in columnList)
                {
                    try
                    {
                        if ("PrintN".Equals(gcol.Tag.ToString()))
                        {
                            continue;                                       //엑셀출력제외컬럼
                        }
                    }
                    catch (Exception) { }

                    listCols.Add(gcol.FieldName.ToString());
                }


                saveFileDialog       = null;
                saveFileDialog       = new System.Windows.Forms.SaveFileDialog();
                saveFileDialog.Title = "저장경로를 지정하세요.";

                //초기 파일명 지정
                saveFileDialog.FileName = DateTime.Now.ToString("yyyyMMdd") + "_" + "상수공사대장.xlsx";

                saveFileDialog.OverwritePrompt = true;
                saveFileDialog.Filter          = "Excel|*.xlsx";

                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    strFileName = saveFileDialog.FileName;
                    thread      = new Thread(new ThreadStart(ExcelExportFX));
                    thread.Start();
                }
            }
            catch (Exception ex)
            {
                Messages.ShowErrMsgBoxLog(ex);
            }
        }
Пример #34
0
        private void _export_Click(object sender, RoutedEventArgs e)
        {
            if (dtpStartDate.SelectedDate.Value.Date != dtpEndDate.SelectedDate.Value.Date)
            {
                Toolkit.MessageBox.Show("只能导出同一天的数据(开始日期必须等于结束日期),请重新选择!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            if (user_flag_tier != "4")
            {
                if (_detect_station.SelectedIndex < 1)
                {
                    Toolkit.MessageBox.Show("只能导出一个检疫分站的数据,请选择!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
            }

            string shipper_name;

            if (_shipper_name.SelectedIndex == 0)
            {
                shipper_name = "";
            }
            else
            {
                shipper_name = _shipper_name.Text;
            }

            System.Data.DataTable exporttable = dbOperation.GetDbHelper().GetDataSet(string.Format("call p_quarantine_query('{0}','{1}','{2}','{3}','{4}','{5}')",
                                                                                                   deptId,
                                                                                                   ((DateTime)dtpStartDate.SelectedDate).ToShortDateString(),
                                                                                                   ((DateTime)dtpEndDate.SelectedDate).ToShortDateString(),
                                                                                                   _detect_station.SelectedIndex < 1 ? "" : (_detect_station.SelectedItem as System.Windows.Controls.Label).Tag,
                                                                                                   _detect_person1.SelectedIndex < 1 ? "" : (_detect_person1.SelectedItem as System.Windows.Controls.Label).Tag,
                                                                                                   shipper_name)).Tables[0];

            if (exporttable.Rows.Count - 1 == 0)
            {
                Toolkit.MessageBox.Show("导出内容为空,请确认!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            //打开对话框
            System.Windows.Forms.SaveFileDialog saveFile = new System.Windows.Forms.SaveFileDialog();
            saveFile.Filter           = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
            saveFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            var excelFilePath = saveFile.FileName;

            if (excelFilePath != "")
            {
                if (System.IO.File.Exists(excelFilePath))
                {
                    try
                    {
                        System.IO.File.Delete(excelFilePath);
                    }
                    catch (Exception ex)
                    {
                        Toolkit.MessageBox.Show("导出文件时出错,文件可能正被打开!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }

                try
                {
                    //创建Excel
                    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

                    if (excelApp == null)
                    {
                        Toolkit.MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel程序!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }

                    load = new Exporting_window();
                    load.Show();

                    Workbook  excelWB = excelApp.Workbooks.Add(System.Type.Missing); //创建工作簿(WorkBook:即Excel文件主体本身)
                    Worksheet excelWS = (Worksheet)excelWB.Worksheets[1];            //创建工作表(即Excel里的子表sheet) 1表示在子表sheet1里进行数据导出
                    excelWS.Name = "屠宰检疫工作情况日记录表";

                    //excelWS.Cells.NumberFormat = "@";     //  如果数据中存在数字类型 可以让它变文本格式显示
                    //导出表头
                    excelWS.Cells[1, 1] = "屠宰检疫工作情况日记录表";
                    //合并单元格
                    Range excelRange = excelWS.get_Range("A1", "N1");
                    excelRange.Merge(excelRange.MergeCells);
                    excelRange.RowHeight = 50;
                    //设置字体大小
                    excelRange.Font.Size = 18;
                    excelRange.Font.Bold = 10;
                    // 文本水平居中方式
                    excelRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                    //导出标题
                    excelWS.Cells[2, 1]  = "动物卫生监督所(分所)名称:" + exporttable.Rows[0][0].ToString();
                    excelWS.Cells[2, 6]  = "屠宰场名称:" + exporttable.Rows[0][1].ToString();
                    excelWS.Cells[2, 12] = "屠宰动物种类:" + exporttable.Rows[0][2].ToString();
                    //设置行高
                    Range excelRange2 = excelWS.get_Range("A2");
                    excelRange2.RowHeight = 25;
                    //合并单元格
                    excelWS.get_Range("A2", "E2").Merge(excelWS.get_Range("A2", "E2").MergeCells);
                    excelWS.get_Range("F2", "K2").Merge(excelWS.get_Range("F2", "K2").MergeCells);
                    excelWS.get_Range("L2", "N2").Merge(excelWS.get_Range("L2", "N2").MergeCells);


                    //导出列名
                    excelWS.Cells[3, 4]  = "入场监督查验";
                    excelWS.Cells[3, 7]  = "宰前检查";
                    excelWS.Cells[3, 9]  = "同步检疫";
                    excelWS.Cells[3, 12] = "检疫人员";
                    //合并单元格
                    excelWS.get_Range("D3", "F3").Merge(excelWS.get_Range("D3", "F3").MergeCells);
                    excelWS.get_Range("D3", "F3").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelWS.get_Range("G3", "H3").Merge(excelWS.get_Range("G3", "H3").MergeCells);
                    excelWS.get_Range("G3", "H3").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelWS.get_Range("I3", "K3").Merge(excelWS.get_Range("I3", "K3").MergeCells);
                    excelWS.get_Range("I3", "K3").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelWS.get_Range("L3", "M3").Merge(excelWS.get_Range("L3", "M3").MergeCells);
                    excelWS.get_Range("L3", "M3").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;


                    excelWS.Cells[4, 1]  = "申报人";
                    excelWS.Cells[4, 2]  = "产地";
                    excelWS.Cells[4, 3]  = "入场数量(头、只、羽、匹)";
                    excelWS.Cells[4, 4]  = "临床情况";
                    excelWS.Cells[4, 5]  = "是都佩戴规定的畜禽标识";
                    excelWS.Cells[4, 6]  = "回收《动物检疫合格证明》编号";
                    excelWS.Cells[4, 7]  = "合格数(头、只、羽、匹)";
                    excelWS.Cells[4, 8]  = "不合格数(头、只、羽、匹)";
                    excelWS.Cells[4, 9]  = "合格数(头、只、羽、匹)";
                    excelWS.Cells[4, 10] = "出具《动物检疫合格证明》编号";
                    excelWS.Cells[4, 11] = "不合格数(头、只、羽、匹)";
                    excelWS.Cells[4, 12] = "官方兽医姓名";
                    excelWS.Cells[4, 13] = "协检员";
                    excelWS.Cells[4, 14] = "备注";
                    //合并单元格
                    excelWS.get_Range("A3", "A4").Merge(excelWS.get_Range("A3", "A4").MergeCells);
                    excelWS.get_Range("A3", "A4").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelWS.get_Range("B3", "B4").Merge(excelWS.get_Range("B3", "B4").MergeCells);
                    excelWS.get_Range("B3", "B4").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelWS.get_Range("C3", "C4").Merge(excelWS.get_Range("C3", "C4").MergeCells);
                    excelWS.get_Range("C3", "C4").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excelWS.get_Range("N3", "N4").Merge(excelWS.get_Range("N3", "N4").MergeCells);
                    excelWS.get_Range("N3", "N4").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                    Range range = null;
                    range                   = excelWS.get_Range(excelWS.Cells[3, 1], excelWS.Cells[exporttable.Rows.Count + 4, 14]); //设置表格左上角开始显示的位置
                    range.ColumnWidth       = 10;                                                                                    //设置单元格的宽度
                    range.Borders.LineStyle = 1;                                                                                     //设置单元格边框的粗细
                    //文本自动换行
                    range.WrapText = true;

                    //特殊设置-产地
                    excelWS.get_Range("B3").ColumnWidth = 20; //设置单元格的宽度

                    //将数据导入到工作表的单元格
                    for (int i = 0; i < exporttable.Rows.Count; i++)
                    {
                        for (int j = 4; j < exporttable.Columns.Count - 1; j++)
                        {
                            excelWS.Cells[i + 5, j - 3] = exporttable.Rows[i][j].ToString();
                        }
                    }

                    //赋值合计
                    excelWS.Cells[exporttable.Rows.Count + 4, 1] = "合计";

                    //赋值检疫日期
                    excelWS.Cells[exporttable.Rows.Count + 5, 12] = "检疫日期:  " + dtpStartDate.SelectedDate.Value.Year + "年" +
                                                                    dtpStartDate.SelectedDate.Value.Month + "月" + dtpStartDate.SelectedDate.Value.Day +
                                                                    "日";
                    //设置内容单元格的高度
                    excelWS.get_Range(excelWS.Cells[5, 1], excelWS.Cells[exporttable.Rows.Count + 5, 1]).RowHeight           = 25;
                    excelWS.get_Range(excelWS.Cells[5, 1], excelWS.Cells[exporttable.Rows.Count + 5, 1]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                    excelWB.SaveAs(excelFilePath);  //将其进行保存到指定的路径
                    excelWB.Close();
                    excelApp.Quit();
                    KillAllExcel(excelApp); //释放可能还没释放的进程
                    load.Close();
                    Toolkit.MessageBox.Show("文件导出成功!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch
                {
                    load.Close();
                    Toolkit.MessageBox.Show("无法创建Excel对象,可能您的机子Office版本有问题!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
            }
        }
Пример #35
0
        private void exportCsvBtn_Click(object sender, RoutedEventArgs e)
        {
            if ((!logFile.FieldDict.ContainsKey("vehicle_global_position.lon")) ||
                (!logFile.FieldDict.ContainsKey("vehicle_global_position.lat")) ||
                (!logFile.FieldDict.ContainsKey("vehicle_global_position.alt")) ||
                (!logFile.FieldDict.ContainsKey("vehicle_attitude.roll")) ||
                (!logFile.FieldDict.ContainsKey("vehicle_attitude.pitch")) ||
                (!logFile.FieldDict.ContainsKey("vehicle_attitude.yaw")))
            {
                MessageBox.Show("数据不全");
                return;
            }
            DataField[] posData = new DataField[3];
            DataField[] attData = new DataField[3];
            posData[0] = logFile.FieldDict["vehicle_global_position.lon"];
            posData[1] = logFile.FieldDict["vehicle_global_position.lat"];
            posData[2] = logFile.FieldDict["vehicle_global_position.alt"];
            attData[0] = logFile.FieldDict["vehicle_attitude.roll"];
            attData[1] = logFile.FieldDict["vehicle_attitude.pitch"];
            attData[2] = logFile.FieldDict["vehicle_attitude.yaw"];
            double[] attFilter = new double[3];

            System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
            sfd.AddExtension = true;
            sfd.Filter       = "csv files(*.csv)|*.csv";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                StreamWriter sw = new StreamWriter(sfd.FileName, false);
                sw.WriteLine("Time,Lat,Lon,Alt");
                double currtime = -1;
                double time;
                double hdg;
                int    pospos = 0, attpos = 0;
                var    posTimes = posData[0].Timestamps;
                var    attTimes = attData[0].Timestamps;
                while (pospos < posTimes.Count || attpos < attTimes.Count)
                {
                    int flag = 0;
                    if (pospos < posTimes.Count && attpos < attTimes.Count)
                    {
                        if (posTimes[pospos] < attTimes[attpos])
                        {
                            flag = 1;
                        }
                        else
                        {
                            flag = 2;
                        }
                    }
                    else if (pospos < posTimes.Count)
                    {
                        flag = 1;
                    }
                    else
                    {
                        flag = 2;
                    }
                    if (flag == 1)
                    {
                        //Update pos
                        sw.WriteLine("{0},{1},{2},{3}", posTimes[pospos], posData[1].Values[pospos], posData[0].Values[pospos], posData[2].Values[pospos]);
                        //sw.WriteLine("#" + posTimes[pospos].ToString());

                        //sw.WriteLine("101,T={0}|{1}|{2}|{3}|{4}|{5}", posData[0].Values[pospos], posData[1].Values[pospos], posData[2].Values[pospos], attFilter[0] * 57.29577951, attFilter[1] * 57.29577951, hdg);
                        pospos++;
                    }
                    else
                    {
                        for (int i = 0; i < 2; i++)
                        {
                            if (attpos == 0)
                            {
                                attFilter[i] = attData[i].Values[attpos];
                            }
                            else
                            {
                                attFilter[i] = 0.95 * attFilter[i] + 0.05 * attData[i].Values[attpos];
                            }
                        }
                        hdg = attData[2].Values[attpos] * 57.29577951;
                        if (hdg < 0)
                        {
                            hdg += 360;
                        }
                        //if (attTimes[attpos] - currtime >= 0.1)
                        //{
                        //	sw.WriteLine("#" + attTimes[attpos].ToString());

                        //	sw.WriteLine("101,T=|||{0}|{1}|{2}", attFilter[0] * 57.29577951, attFilter[1] * 57.29577951, hdg);
                        //	currtime = attTimes[attpos];
                        //}

                        attpos++;
                    }
                }
                sw.Close();
            }
        }
Пример #36
0
        /// <summary>
        /// Creates a session based on the specified source data an analysis scripts
        /// </summary>
        /// <param name="sources">The source data files</param>
        /// <param name="sinkScripts">The data analysis scripts</param>
        /// <returns>The session instance</returns>
        public static StockSession LoadData(List <string> sources, List <string> sinkScripts)
        {
            StockSession session = new StockSession();

            session.DataScriptPaths.Clear();
            Directory.CreateDirectory("tmp");

            // Convert any legacy files before further processing
            var legacyFiles = sources.Where((s) => { return(s.EndsWith(".csv")); }).ToList();

            if (legacyFiles.Count() > 0)
            {
                System.Windows.Forms.SaveFileDialog saveDiag = new System.Windows.Forms.SaveFileDialog();
                saveDiag.Title           = "Save converted data file as...";
                saveDiag.CheckFileExists = false;
                if (saveDiag.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    List <string> convertedFileNames;
                    var           convertedFiles = StockDataFile.ConvertByMonth(legacyFiles, Path.GetDirectoryName(saveDiag.FileName), out convertedFileNames);
                    foreach (var cf in convertedFileNames)
                    {
                        sources.Add(cf);
                    }
                }
                else
                {
                    // Cancel running the script
                    return(null);
                }
                foreach (var l in legacyFiles)
                {
                    sources.Remove(l);
                }
            }

            session.SourceFile = StockDataFile.Open(sources.ConvertAll <Stream>((s) => { return(new FileStream(s, FileMode.Open)); }));
            session.DataScriptPaths.Add("tmp/" + SOURCE_CLASS + ".cs");
            using (var file = new StreamWriter(new FileStream(session.DataScriptPaths.Last(), FileMode.Create))) file.Write(session.SourceFile.GetSourceCode(SOURCE_CLASS));

            // Put the data set reference script first
            List <string> totalSinkScripts = sinkScripts.ToList();

            totalSinkScripts.Insert(0, "Script\\Data\\DataSetReference.cs");
            session.SinkFile          = new StockDataFile(totalSinkScripts.ConvertAll <string>((f) => { return(Path.GetFileNameWithoutExtension(f)); }), totalSinkScripts.ConvertAll <string>((f) => { return(File.ReadAllText(f)); }));
            session.SinkFile.Interval = session.SourceFile.Interval;
            session.DataScriptPaths.Add("tmp/" + SINK_CLASS + ".cs");
            using (var file = new StreamWriter(new FileStream(session.DataScriptPaths.Last(), FileMode.Create))) file.Write(session.SinkFile.GenStockDataSink());
            session.DataScriptPaths.AddRange(totalSinkScripts);

            // Create the evaluator file (needs to be compiled in the script since it references StockDataSource)
            string[] embeddedFiles = new string[]
            {
                "RobinhoodDesktop.Script.StockEvaluator.cs",
                "RobinhoodDesktop.Script.StockProcessor.cs"
            };
            foreach (var f in embeddedFiles)
            {
                session.DataScriptPaths.Add(string.Format("tmp/{0}.cs", f.Substring(24, f.Length - 27)));
                StringBuilder analyzerCode = new StringBuilder();
                analyzerCode.Append(new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(f)).ReadToEnd());
                using (var file = new StreamWriter(new FileStream(session.DataScriptPaths.Last(), FileMode.Create))) file.Write(StockDataFile.FormatSource(analyzerCode.ToString()));
            }

            // Add the user defined analyzers
            foreach (string path in Directory.GetFiles(@"Script/Decision", "*.cs", SearchOption.AllDirectories))
            {
                session.DataScriptPaths.Add(path);
            }
            foreach (string path in Directory.GetFiles(@"Script/Action", "*.cs", SearchOption.AllDirectories))
            {
                session.DataScriptPaths.Add(path);
            }

            // Build the data
            session.Reload();
            if (session.Data != null)
            {
                StockSession.Instance = session;
            }
            else
            {
                session.SourceFile.Close();
            }
            return(StockSession.Instance);
        }
Пример #37
0
        public override void UpdateBegin()
        {
            TileScreenMousePos   = Input.ScreenMousePos / GameConsole.CharSize;
            TileScreenMousePos.X = (float)Math.Floor(TileScreenMousePos.X);
            TileScreenMousePos.Y = (float)Math.Floor(TileScreenMousePos.Y);

            if (!Input.MouseCheck(Input.MB.Left))
            {
                ClickBlock = false;
            }
            if (ClickBlock)
            {
                Input.MouseClear();
            }

            #region Mode selection

            if (Input.KeyboardCheck(Keys.LeftControl))
            {
                if (Input.KeyboardCheckPress(TileModeHotkey))
                {
                    CurrentMode = Mode.Tiles;
                }
                if (Input.KeyboardCheckPress(ObjectModeHotkey))
                {
                    CurrentMode = Mode.Objects;
                    Input.KeyboardClear();
                }
                if (Input.KeyboardCheckPress(CollisionModeHotkey))
                {
                    CurrentMode           = Mode.Collision;
                    Terrain.DisplaySolids = true;
                }
            }

            #endregion Mode selection


            #region Saving/Loading

            if (Input.KeyboardCheck(Keys.LeftControl))
            {
                if (Input.KeyboardCheckPress(SaveHotkey))
                {
                    string filename = MapFileName;
                    if (Input.KeyboardCheck(Keys.LeftShift) || filename == "")
                    {
                        System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
                        dialog.Title  = "Save map file";
                        dialog.Filter = "Map File|*.map";
                        dialog.ShowDialog();
                        filename = dialog.FileName;
                    }

                    if (filename != "")
                    {
                        SaveMap(Terrain, filename);
                        MapFileName = filename;
                    }
                }

                if (Input.KeyboardCheckPress(LoadHotkey))
                {
                    System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
                    dialog.Title  = "Save map file";
                    dialog.Filter = "Map File|*.map";
                    dialog.ShowDialog();
                    if (dialog.FileName != "")
                    {
                        Terrain = LoadMap(dialog.FileName, true);
                        DrawCntrl.Cameras[0].X = -GameConsole.CharSize.X;
                        DrawCntrl.Cameras[0].Y = -GameConsole.CharSize.Y;
                        MapFileName            = dialog.FileName;
                    }
                }
            }

            #endregion Saving/Loading


            #region Exiting
            ExitAlarm.Update();
            if (Input.KeyboardCheckPress(ExitHotkey))
            {
                ExitAlarm.Set(2);
            }
            if (!Input.KeyboardCheck(ExitHotkey))
            {
                ExitAlarm.Reset();
            }
            if (ExitAlarm.Triggered)
            {
                Objects.Destroy(this);
            }
            #endregion Exiting

            MoveCamera();

            // Menus and stuff.
            #region Selection menu
            if (SelectionMenuActive)
            {
                if (Input.MouseCheckPress(Input.MB.Left))
                {
                    var chars = GameConsole.Font.GetGlyphs().ToArray();

                    var index = 0;
                    for (var y = 0; y < SelectionMenuSize.Y; y += 1)
                    {
                        for (var x = 0; x < SelectionMenuSize.X; x += 1)
                        {
                            if (SelectionMenuMode == 0)
                            {
                                // Palette select.
                                if (index >= Palettes.Length)
                                {
                                    y = (int)SelectionMenuSize.Y;
                                    break;
                                }

                                if (TileScreenMousePos - SelectionMenuPos == new Vector2(x, y))
                                {
                                    CurrentPalette = index;
                                    y = (int)SelectionMenuSize.Y;
                                    break;
                                }
                                // Palette select.
                            }
                            else
                            {
                                // Chars select.
                                if (index >= chars.Length)
                                {
                                    y = (int)SelectionMenuSize.Y;
                                    break;
                                }

                                if (TileScreenMousePos - SelectionMenuPos == new Vector2(x, y))
                                {
                                    CurrentChar = chars[index].Key;
                                    y           = (int)SelectionMenuSize.Y;
                                    break;
                                }
                                // Chars select.
                            }

                            index += 1;
                        }
                    }

                    SelectionMenuActive = false;
                    ClickBlock          = true;
                    Input.MouseClear();
                }

                if ((SelectionMenuMode == 0 && Input.KeyboardCheckPress(PalettesHotkey)) ||
                    (SelectionMenuMode == 1 && Input.KeyboardCheckPress(CharsHotkey)) ||
                    Input.KeyboardCheckPress(Keys.Escape))
                {
                    SelectionMenuActive = false;
                    Input.KeyboardClear();
                }
            }
            #endregion Selection menu

            #region Argument menu

            if (ObjArgumentMenuActive)
            {
                foreach (char ch in Input.KeyboardString)
                {
                    if (ch == (char)Keys.Back)
                    {
                        if (CurrentObject.Argument.Length > 0)
                        {
                            CurrentObject.Argument = CurrentObject.Argument.Remove(CurrentObject.Argument.Length - 1, 1);
                        }
                    }
                    else
                    {
                        if (!Char.IsControl(ch))
                        {
                            CurrentObject.Argument += ch;
                        }
                    }
                }

                if (Input.KeyboardCheck(Keys.Enter) || Input.KeyboardCheck(Keys.Escape) || Input.MouseCheck(Input.MB.Left))
                {
                    ClickBlock            = true;
                    ObjArgumentMenuActive = false;
                }

                Input.IOClear();
            }

            #endregion Argument menu

            #region Object menu

            if (ObjSelectMenuActive)
            {
                if (Input.MouseCheckPress(Input.MB.Left))
                {
                    if (TileScreenMousePos.X >= ObjSelectMenuPos.X &&
                        TileScreenMousePos.X < ObjSelectMenuPos.X + ObjSelectMenuSize.X &&
                        TileScreenMousePos.Y >= ObjSelectMenuPos.Y &&
                        TileScreenMousePos.Y < ObjSelectMenuPos.Y + ObjSelectMenuSize.Y)
                    {
                        CurrentObjectType = (int)(TileScreenMousePos.Y - ObjSelectMenuPos.Y);
                    }
                    ClickBlock          = true;
                    ObjSelectMenuActive = false;
                    Input.MouseClear();
                }
            }

            #endregion Object menu
            // Menus and stuff.
        }
Пример #38
0
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem item = sender as MenuItem;

            ///edit
            if (item.Header.ToString().ToLower().Contains("graph setting"))
            {
                if (UINodeParameters.Instance != null && graphs.Count > 0)
                {
                    if (GraphDocuments.SelectedContentIndex > -1)
                    {
                        var graph = graphs[GraphDocuments.SelectedContentIndex];
                        if (graph.Graph != null)
                        {
                            UINodeParameters.Instance.SetActive(graph.Graph);
                        }
                    }
                }
            }
            else if (item.Header.ToString().ToLower().Contains("redo"))
            {
                if (GraphDocuments.SelectedContentIndex > -1)
                {
                    var graph = graphs[GraphDocuments.SelectedContentIndex];
                    graph.TryAndRedo();
                }
            }
            else if (item.Header.ToString().ToLower().Contains("undo"))
            {
                if (GraphDocuments.SelectedContentIndex > -1)
                {
                    var graph = graphs[GraphDocuments.SelectedContentIndex];
                    graph.TryAndUndo();
                }
            }
            ///windows
            else if (item.Header.ToString().ToLower().Contains("3d"))
            {
                if (Preview3DPane.IsVisible)
                {
                    Preview3DPane.Hide();
                }
                else
                {
                    Preview3DPane.Show();
                }
            }
            else if (item.Header.ToString().ToLower().Contains("2d"))
            {
                if (Preview2DPane.IsVisible)
                {
                    Preview2DPane.Hide();
                }
                else
                {
                    Preview2DPane.Show();
                }
            }
            else if (item.Header.ToString().ToLower().Contains("parameters"))
            {
                if (ParametersPane.IsVisible)
                {
                    ParametersPane.Hide();
                }
                else
                {
                    ParametersPane.Show();
                }
            }
            else if (item.Header.ToString().ToLower().Contains("shelf"))
            {
                if (ShelfPane.IsVisible)
                {
                    ShelfPane.Hide();
                }
                else
                {
                    ShelfPane.Show();
                }
            }
            else if (item.Header.ToString().ToLower().Contains("log"))
            {
                if (LogPane.IsVisible)
                {
                    LogPane.Hide();
                }
                else
                {
                    LogPane.Show();
                }
            }
            else if (item.Header.ToString().ToLower().Contains("close all graph"))
            {
                for (int i = 0; i < documents.Count; i++)
                {
                    var doc = documents[i];
                    doc.Close();
                }
            }
            //file menu
            else if (item.Header.ToString().ToLower().Contains("save as"))
            {
                if (graphs.Count > 0)
                {
                    System.Windows.Forms.SaveFileDialog svf = new System.Windows.Forms.SaveFileDialog();
                    svf.CheckPathExists = true;
                    svf.DefaultExt      = ".mtg";
                    svf.Filter          = "Materia Graph (*.mtg)|*.mtg|Materia Graph Archive (*.mtga)|*.mtga";

                    if (svf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        UIGraph g = graphs[GraphDocuments.SelectedContentIndex];
                        if (g != null)
                        {
                            g.Save(svf.FileName, true);

                            var doc = documents[GraphDocuments.SelectedContentIndex];
                            doc.Title = g.GraphName;

                            recent.Add(svf.FileName);
                            BuildRecentSubMenu();
                        }
                    }
                }
            }
            else if (item.Header.ToString().ToLower().Contains("save"))
            {
                if (graphs.Count > 0)
                {
                    UIGraph g = graphs[GraphDocuments.SelectedContentIndex];
                    HandleSave(g);
                    var doc = documents[GraphDocuments.SelectedContentIndex];
                    doc.Title = g.GraphName;
                }
            }
            else if (item.Header.ToString().ToLower().Contains("open"))
            {
                System.Windows.Forms.OpenFileDialog ovf = new System.Windows.Forms.OpenFileDialog();
                ovf.CheckFileExists = true;
                ovf.CheckPathExists = true;
                ovf.DefaultExt      = ".mtg";
                ovf.Filter          = "Materia Graph (*.mtg;*.mtga)|*.mtg;*.mtga";

                if (ovf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    HandleOpen(ovf.FileName);
                }
            }
            else if (item.Header.ToString().ToLower().Contains("new"))
            {
                HandleCreate();
            }
            else if (item.Header.ToString().ToLower().Contains("export output"))
            {
                if (graphs.Count > 0 && GraphDocuments.SelectedContentIndex > -1 &&
                    GraphDocuments.SelectedContentIndex < graphs.Count)
                {
                    UIExportOutputs exportdialog = new UIExportOutputs(graphs[GraphDocuments.SelectedContentIndex]);
                    exportdialog.ShowDialog();
                }
            }
        }
Пример #39
0
            public void Plot_Results()
            {
                if (Direct_Data == null && IS_Data == null && Receiver == null && Parameter_Choice.Text != "Sabine RT" && Parameter_Choice.Text != "Eyring RT")
                {
                    return;
                }

                System.Windows.Forms.SaveFileDialog sf = new System.Windows.Forms.SaveFileDialog();
                sf.DefaultExt   = ".txt";
                sf.AddExtension = true;
                sf.Filter       = "Text File (*.txt)|*.txt|" + "All Files|";

                if (sf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    System.IO.StreamWriter SW;

fileread:
                    try
                    {
                        SW = new System.IO.StreamWriter(System.IO.File.Open(sf.FileName, System.IO.FileMode.Create));
                    }
                    catch
                    {
                        System.Windows.Forms.DialogResult dr = System.Windows.Forms.MessageBox.Show("File is in use. Close any programs using the file, and try again.", "File In Use", System.Windows.Forms.MessageBoxButtons.RetryCancel);
                        if (dr == System.Windows.Forms.DialogResult.Cancel)
                        {
                            return;
                        }
                        goto fileread;
                    }

                    double[] Schroeder;
                    double[, ,] EDT = new double[this.SourceList.Items.Count, Recs.Length, 8];
                    double[, ,] T10 = new double[this.SourceList.Items.Count, Recs.Length, 8];
                    double[, ,] T15 = new double[this.SourceList.Items.Count, Recs.Length, 8];
                    double[, ,] T20 = new double[this.SourceList.Items.Count, Recs.Length, 8];
                    double[, ,] T30 = new double[this.SourceList.Items.Count, Recs.Length, 8];
                    double[, ,] G   = new double[this.SourceList.Items.Count, Recs.Length, 8];
                    double[, ,] C80 = new double[this.SourceList.Items.Count, Recs.Length, 8];
                    double[, ,] C50 = new double[this.SourceList.Items.Count, Recs.Length, 8];
                    double[, ,] D50 = new double[this.SourceList.Items.Count, Recs.Length, 8];
                    double[, ,] TS  = new double[this.SourceList.Items.Count, Recs.Length, 8];
                    double[, ,] LF  = new double[this.SourceList.Items.Count, Recs.Length, 8];
                    double[, ,] LE  = new double[this.SourceList.Items.Count, Recs.Length, 8];

                    for (int s = 0; s < SourceList.Items.Count; s++)
                    {
                        for (int r = 0; r < Recs.Length; r++)
                        {
                            for (int oct = 0; oct < 8; oct++)
                            {
                                double[] ETC = IR_Construction.ETCurve(Direct_Data, IS_Data, Receiver, (int)(CO_TIME.Value / 1000), SampleRate, oct, r, s, false);
                                Schroeder      = AcousticalMath.Schroeder_Integral(ETC);
                                EDT[s, r, oct] = AcousticalMath.EarlyDecayTime(Schroeder, SampleRate);
                                T10[s, r, oct] = AcousticalMath.T_X(Schroeder, 10, SampleRate);
                                T15[s, r, oct] = AcousticalMath.T_X(Schroeder, 15, SampleRate);
                                T20[s, r, oct] = AcousticalMath.T_X(Schroeder, 20, SampleRate);
                                T30[s, r, oct] = AcousticalMath.T_X(Schroeder, 30, SampleRate);
                                G[s, r, oct]   = AcousticalMath.Strength(ETC, Direct_Data[s].SWL[oct], false);
                                C50[s, r, oct] = AcousticalMath.Clarity(ETC, SampleRate, 0.05, Direct_Data[s].Min_Time(r), false);
                                C80[s, r, oct] = AcousticalMath.Clarity(ETC, SampleRate, 0.08, Direct_Data[s].Min_Time(r), false);
                                D50[s, r, oct] = AcousticalMath.Definition(ETC, SampleRate, 0.05, Direct_Data[s].Min_Time(r), false);
                                TS[s, r, oct]  = AcousticalMath.Center_Time(ETC, SampleRate, Direct_Data[s].Min_Time(r)) * 1000;
                                double[] L_ETC = IR_Construction.ETCurve_1d(Direct_Data, IS_Data, Receiver, (int)(CO_TIME.Value), SampleRate, oct, r, new System.Collections.Generic.List <int>()
                                {
                                    s
                                }, false, (double)this.Alt_Choice.Value, (double)this.Azi_Choice.Value, true)[1];
                                LF[s, r, oct] = AcousticalMath.Lateral_Fraction(ETC, L_ETC, SampleRate, Direct_Data[s].Min_Time(r), false) * 1000;
                                LE[s, r, oct] = AcousticalMath.Lateral_Efficiency(ETC, L_ETC, SampleRate, Direct_Data[s].Min_Time(r), false) * 1000;
                            }
                        }
                    }

                    SW.WriteLine("Pachyderm Acoustic Simulation Results");
                    SW.WriteLine("Saved {0}", System.DateTime.Now.ToString());
                    SW.WriteLine("Filename:{0}", Rhino.RhinoDoc.ActiveDoc.Name);
                    for (int s = 0; s < SourceList.Items.Count; s++)
                    {
                        SW.WriteLine("Source {0};", s);
                        for (int r = 0; r < Recs.Length; r++)
                        {
                            SW.WriteLine("Receiver {0};63 Hz.;125 Hz.;250 Hz.;500 Hz.;1000 Hz.; 2000 Hz.;4000 Hz.; 8000 Hz.", r);
                            SW.WriteLine("Early Decay Time (EDT);{0};{1};{2};{3};{4};{5};{6};{7}", EDT[s, r, 0], EDT[s, r, 1], EDT[s, r, 2], EDT[s, r, 3], EDT[s, r, 4], EDT[s, r, 5], EDT[s, r, 6], EDT[s, r, 7]);
                            SW.WriteLine("Reverberation Time (T-10);{0};{1};{2};{3};{4};{5};{6};{7}", T10[s, r, 0], T10[s, r, 1], T10[s, r, 2], T10[s, r, 3], T10[s, r, 4], T10[s, r, 5], T10[s, r, 6], T10[s, r, 7]);
                            SW.WriteLine("Reverberation Time (T-15);{0};{1};{2};{3};{4};{5};{6};{7}", T15[s, r, 0], T15[s, r, 1], T15[s, r, 2], T15[s, r, 3], T15[s, r, 4], T15[s, r, 5], T15[s, r, 6], T15[s, r, 7]);
                            SW.WriteLine("Reverberation Time (T-20);{0};{1};{2};{3};{4};{5};{6};{7}", T20[s, r, 0], T20[s, r, 1], T20[s, r, 2], T20[s, r, 3], T20[s, r, 4], T20[s, r, 5], T20[s, r, 6], T20[s, r, 7]);
                            SW.WriteLine("Reverberation Time (T-30);{0};{1};{2};{3};{4};{5};{6};{7}", T30[s, r, 0], T30[s, r, 1], T30[s, r, 2], T30[s, r, 3], T30[s, r, 4], T30[s, r, 5], T30[s, r, 6], T30[s, r, 7]);
                            SW.WriteLine("Clarity - 50 ms (C-50);{0};{1};{2};{3};{4};{5};{6};{7}", C50[s, r, 0], C50[s, r, 1], C50[s, r, 2], C50[s, r, 3], C50[s, r, 4], C50[s, r, 5], C50[s, r, 6], C50[s, r, 7]);
                            SW.WriteLine("Definition/Deutlichkeit (D);{0};{1};{2};{3};{4};{5};{6};{7}", D50[s, r, 0], D50[s, r, 1], D50[s, r, 2], D50[s, r, 3], D50[s, r, 4], D50[s, r, 5], D50[s, r, 6], D50[s, r, 7]);
                            SW.WriteLine("Clarity - 80 ms (C-80);{0};{1};{2};{3};{4};{5};{6};{7}", C80[s, r, 0], C80[s, r, 1], C80[s, r, 2], C80[s, r, 3], C80[s, r, 4], C80[s, r, 5], C80[s, r, 6], C80[s, r, 7]);
                            SW.WriteLine("Center Time (TS);{0};{1};{2};{3};{4};{5};{6};{7}", TS[s, r, 0], TS[s, r, 1], TS[s, r, 2], TS[s, r, 3], TS[s, r, 4], TS[s, r, 5], TS[s, r, 6], TS[s, r, 7]);
                            SW.WriteLine("Strength(G);{0};{1};{2};{3};{4};{5};{6};{7}", G[s, r, 0], G[s, r, 1], G[s, r, 2], G[s, r, 3], G[s, r, 4], G[s, r, 5], G[s, r, 6], G[s, r, 7]);
                            SW.WriteLine("Lateral Fraction(LF);{0};{1};{2};{3};{4};{5};{6};{7}", LF[s, r, 0], LF[s, r, 1], LF[s, r, 2], LF[s, r, 3], LF[s, r, 4], LF[s, r, 5], LF[s, r, 6], LF[s, r, 7]);
                            SW.WriteLine("Lateral Efficiency(LE);{0};{1};{2};{3};{4};{5};{6};{7}", LE[s, r, 0], LE[s, r, 1], LE[s, r, 2], LE[s, r, 3], LE[s, r, 4], LE[s, r, 5], LE[s, r, 6], LE[s, r, 7]);
                        }
                    }
                    SW.Close();
                }
            }
        private void BtnExportClick(object sender, RoutedEventArgs e)
        {
            if (_FixedDoc == null)
            {
                this.BtnExport.IsEnabled = false;
                return;
            }
            System.Windows.Forms.SaveFileDialog fileDialog = new System.Windows.Forms.SaveFileDialog();
            fileDialog.Filter   = "Docx|*.Docx";
            fileDialog.FileName = _FixedDocVM.CurMember.Name;
            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            try
            {
                this.BtnExport.IsEnabled = false;
                string MemberTemplet = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OWPMemberInfo.dat");
                if (!File.Exists(MemberTemplet))
                {
                    this.BtnExport.IsEnabled = true;
                    AppFuns.ShowMessage("未找到欲导出的模板文件!", Caption: "失败");
                    return;
                }
                FileStream FStream = File.OpenRead(MemberTemplet);
                if (FStream == null)
                {
                    this.BtnExport.IsEnabled = true;
                    AppFuns.ShowMessage("读取模板文件时出现错误,是否文件正在使用?", Caption: "失败");
                    return;
                }
                InputStream WordStream = new FileInputStream(FStream);
                if (WordStream == null)
                {
                    this.BtnExport.IsEnabled = true;
                    AppFuns.ShowMessage("转换模板文件成Word对象流时出现错误?", Caption: "失败");
                    return;
                }
                XWPFDocument WDoc = new XWPFDocument(WordStream);
                if (WDoc == null)
                {
                    this.BtnExport.IsEnabled = true;
                    AppFuns.ShowMessage("转换模板文件成Word对象时出现错误?", Caption: "失败");
                    return;
                }
                //释放不必须的资源
                FStream.Dispose();
                WordStream.Dispose();

                //开始导出
                ExportWord(WDoc, _FixedDocVM);

                //写入输出文件
                if (WDoc != null)
                {
                    FileStream NewWordDoc = File.Create(fileDialog.FileName);
                    WDoc.Write(NewWordDoc);
                    NewWordDoc.Close();
                    WDoc.Close();
                    AppFuns.ShowMessage("数据导出成功!", Caption: "完成");
                    FileOperation.UseDefaultAppOpenFile(fileDialog.FileName);
                }
                else
                {
                    AppFuns.ShowMessage("数据导出失败!", Caption: "失败");
                }
                this.BtnExport.IsEnabled = true;
            }
            catch (Exception Ex)
            {
                this.BtnExport.IsEnabled = true;
                AppFuns.ShowMessage(Ex.Message, Caption: "失败");
            }
        }
Пример #41
0
        /// <summary>
        /// reads price request from text file, sends to server, saves response to text file
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            // NOTES: Anything can be done in this method, such as create a message box,
            // a task dialog or fetch some information from revit and so on.
            // We mainly use the task dialog for example.

            // Get the application and document from external command data.
            Application app    = commandData.Application.Application;
            Document    curDoc = commandData.Application.ActiveUIDocument.Document;

            //loads from settings.txt
            settings.LoadSettings();
            List <string> cats = new List <string>();

            PricingHttpRest.InitializeClient(settings.APILocation, "");// "https://ce7649b3.ngrok.io", "");

            // Displays an OpenFileDialog so the user can select a Cursor.
            System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            openFileDialog1.Filter = "Text files|*.txt";
            openFileDialog1.Title  = "Select a text file with sample price query";


            if (openFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return(Autodesk.Revit.UI.Result.Succeeded);
            }

            //send element data
            string serialS    = File.ReadAllText(openFileDialog1.FileName);
            string pricesJSON = "";

            try
            {
                PricingHttpRest.APICommand  = "pricing/model1";
                PricingHttpRest.sendContent = serialS;

                string result = PricingHttpRest.Post();

                pricesJSON = PricingHttpRest.receivedContent;
                if (result != "OK")
                {
                    System.Windows.Forms.MessageBox.Show("Error accessing API while submitting sample data for pricing: " + result + " " + pricesJSON);
                    return(Autodesk.Revit.UI.Result.Failed);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Error accessing API while submitting sample data for pricing: " + ex.ToString());
                return(Autodesk.Revit.UI.Result.Failed);
            }


            System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog1.Filter = "Text file|*.txt";
            saveFileDialog1.Title  = "Save Sample Price / Instance Data";
            saveFileDialog1.ShowDialog();

            // If the file name is not an empty string open it for saving.
            if (saveFileDialog1.FileName != "")
            {
                System.IO.File.WriteAllText(saveFileDialog1.FileName, pricesJSON);
            }

            return(Autodesk.Revit.UI.Result.Succeeded);
        }
Пример #42
0
        private async void ButtonWrite_OnClick(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog SaveDialog = new System.Windows.Forms.SaveFileDialog
            {
                Filter = "STAR Files|*.star"
            };
            System.Windows.Forms.DialogResult ResultSave = SaveDialog.ShowDialog();

            if (ResultSave.ToString() == "OK")
            {
                ExportPath = SaveDialog.FileName;
            }
            else
            {
                return;
            }

            bool Invert    = (bool)CheckInvert.IsChecked;
            bool Normalize = (bool)CheckNormalize.IsChecked;
            bool Preflip   = (bool)CheckPreflip.IsChecked;

            bool Relative = (bool)CheckRelative.IsChecked;

            bool Filter = (bool)CheckFilter.IsChecked;
            bool Manual = (bool)CheckManual.IsChecked;

            int BoxSize      = (int)Options.Tasks.Export2DBoxSize;
            int NormDiameter = (int)Options.Tasks.Export2DParticleDiameter;

            bool DoVolumes = (bool)RadioVolume.IsChecked;

            if (!DoVolumes)
            {
                Options.Tasks.TomoSubReconstructPrerotated = true;
            }

            bool MakeSparse = (bool)CheckSparse.IsChecked;

            float3 AdditionalShiftAngstrom = (bool)CheckShiftParticles.IsChecked ?
                                             new float3((float)SliderShiftParticlesX.Value,
                                                        (float)SliderShiftParticlesY.Value,
                                                        (float)SliderShiftParticlesZ.Value) :
                                             new float3(0);

            ProgressWrite.Visibility      = Visibility.Visible;
            ProgressWrite.IsIndeterminate = true;
            PanelButtons.Visibility       = Visibility.Collapsed;
            PanelRemaining.Visibility     = Visibility.Visible;

            foreach (var element in DisableWhileProcessing)
            {
                element.IsEnabled = false;
            }

            await Task.Run(() =>
            {
                #region Get all movies that can potentially be used

                List <TiltSeries> ValidSeries = Series.Where(v =>
                {
                    if (!Filter && v.UnselectFilter && v.UnselectManual == null)
                    {
                        return(false);
                    }
                    if (!Manual && v.UnselectManual != null && (bool)v.UnselectManual)
                    {
                        return(false);
                    }
                    if (v.OptionsCTF == null)
                    {
                        return(false);
                    }
                    return(true);
                }).ToList();
                List <string> ValidMovieNames = ValidSeries.Select(m => m.RootName).ToList();

                #endregion

                #region Read table and intersect its micrograph set with valid movies

                Star TableIn;

                if (Options.Tasks.InputOnePerItem)
                {
                    List <Star> Tables = new List <Star>();
                    foreach (var item in Series)
                    {
                        string StarPath = InputFolder + item.RootName + InputSuffix;
                        if (File.Exists(StarPath))
                        {
                            Star TableItem = new Star(StarPath);
                            if (!TableItem.HasColumn("rlnMicrographName"))
                            {
                                TableItem.AddColumn("rlnMicrographName", item.Name);
                            }
                            else
                            {
                                TableItem.SetColumn("rlnMicrographName", Helper.ArrayOfConstant(item.Name, TableItem.RowCount));
                            }

                            Tables.Add(TableItem);
                        }
                    }

                    TableIn = new Star(Tables.ToArray());
                }
                else
                {
                    TableIn = new Star(ImportPath);
                }

                if (!TableIn.HasColumn("rlnMicrographName"))
                {
                    throw new Exception("Couldn't find rlnMicrographName column.");
                }
                if (!TableIn.HasColumn("rlnCoordinateX"))
                {
                    throw new Exception("Couldn't find rlnCoordinateX column.");
                }
                if (!TableIn.HasColumn("rlnCoordinateY"))
                {
                    throw new Exception("Couldn't find rlnCoordinateY column.");
                }
                if (!TableIn.HasColumn("rlnCoordinateZ"))
                {
                    throw new Exception("Couldn't find rlnCoordinateZ column.");
                }

                Dictionary <string, List <int> > Groups = new Dictionary <string, List <int> >();
                {
                    string[] ColumnMicNames = TableIn.GetColumn("rlnMicrographName");
                    for (int r = 0; r < ColumnMicNames.Length; r++)
                    {
                        if (!Groups.ContainsKey(ColumnMicNames[r]))
                        {
                            Groups.Add(ColumnMicNames[r], new List <int>());
                        }
                        Groups[ColumnMicNames[r]].Add(r);
                    }
                    Groups = Groups.ToDictionary(group => Helper.PathToName(group.Key), group => group.Value);

                    Groups = Groups.Where(group => ValidMovieNames.Any(n => group.Key.Contains(n))).ToDictionary(group => group.Key, group => group.Value);
                }

                bool[] RowsIncluded = new bool[TableIn.RowCount];
                foreach (var group in Groups)
                {
                    foreach (var r in group.Value)
                    {
                        RowsIncluded[r] = true;
                    }
                }
                List <int> RowsNotIncluded = new List <int>();
                for (int r = 0; r < RowsIncluded.Length; r++)
                {
                    if (!RowsIncluded[r])
                    {
                        RowsNotIncluded.Add(r);
                    }
                }

                ValidSeries = ValidSeries.Where(v => Groups.Any(n => n.Key.Contains(v.RootName))).ToList();

                if (ValidSeries.Count == 0)     // Exit if there is nothing to export, otherwise errors will be thrown below
                {
                    return;
                }

                #endregion

                #region Make sure all columns are there

                if (!TableIn.HasColumn("rlnMagnification"))
                {
                    TableIn.AddColumn("rlnMagnification", "10000.0");
                }
                else
                {
                    TableIn.SetColumn("rlnMagnification", Helper.ArrayOfConstant("10000.0", TableIn.RowCount));
                }

                if (!TableIn.HasColumn("rlnDetectorPixelSize"))
                {
                    TableIn.AddColumn("rlnDetectorPixelSize", Options.Tasks.TomoSubReconstructPixel.ToString("F5", CultureInfo.InvariantCulture));
                }
                else
                {
                    TableIn.SetColumn("rlnDetectorPixelSize", Helper.ArrayOfConstant(Options.Tasks.TomoSubReconstructPixel.ToString("F5", CultureInfo.InvariantCulture), TableIn.RowCount));
                }

                if (!TableIn.HasColumn("rlnCtfMaxResolution"))
                {
                    TableIn.AddColumn("rlnCtfMaxResolution", "999.0");
                }

                if (!TableIn.HasColumn("rlnImageName"))
                {
                    TableIn.AddColumn("rlnImageName", "None");
                }

                if (!TableIn.HasColumn("rlnCtfImage"))
                {
                    TableIn.AddColumn("rlnCtfImage", "None");
                }

                List <Star> SeriesTablesOut = new List <Star>();

                #endregion

                if (IsCanceled)
                {
                    return;
                }

                #region Create worker processes

                int NDevices                   = GPU.GetDeviceCount();
                List <int> UsedDevices         = Options.MainWindow.GetDeviceList();
                List <int> UsedDeviceProcesses = Helper.Combine(Helper.ArrayOfFunction(i => UsedDevices.Select(d => d + i *NDevices).ToArray(), MainWindow.GlobalOptions.ProcessesPerDevice)).ToList();

                WorkerWrapper[] Workers = new WorkerWrapper[GPU.GetDeviceCount() * MainWindow.GlobalOptions.ProcessesPerDevice];
                foreach (var gpuID in UsedDeviceProcesses)
                {
                    Workers[gpuID] = new WorkerWrapper(gpuID);
                    Workers[gpuID].SetHeaderlessParams(new int2(Options.Import.HeaderlessWidth, Options.Import.HeaderlessHeight),
                                                       Options.Import.HeaderlessOffset,
                                                       Options.Import.HeaderlessType);

                    Workers[gpuID].LoadGainRef(Options.Import.CorrectGain ? Options.Import.GainPath : "",
                                               Options.Import.GainFlipX,
                                               Options.Import.GainFlipY,
                                               Options.Import.GainTranspose,
                                               Options.Import.CorrectDefects ? Options.Import.DefectsPath : "");
                }

                #endregion

                Star TableOut = null;
                {
                    Dictionary <string, Star> MicrographTables = new Dictionary <string, Star>();

                    #region Get coordinates and angles

                    float[] PosX   = TableIn.GetColumn("rlnCoordinateX").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                    float[] PosY   = TableIn.GetColumn("rlnCoordinateY").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                    float[] PosZ   = TableIn.GetColumn("rlnCoordinateZ").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                    float[] ShiftX = TableIn.HasColumn("rlnOriginX") ? TableIn.GetColumn("rlnOriginX").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    float[] ShiftY = TableIn.HasColumn("rlnOriginY") ? TableIn.GetColumn("rlnOriginY").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    float[] ShiftZ = TableIn.HasColumn("rlnOriginZ") ? TableIn.GetColumn("rlnOriginZ").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];


                    if (Options.Tasks.TomoSubReconstructNormalizedCoords)
                    {
                        for (int r = 0; r < TableIn.RowCount; r++)
                        {
                            PosX[r] *= (float)Options.Tomo.DimensionsX * (float)Options.PixelSizeMean;
                            PosY[r] *= (float)Options.Tomo.DimensionsY * (float)Options.PixelSizeMean;
                            PosZ[r] *= (float)Options.Tomo.DimensionsZ * (float)Options.PixelSizeMean;
                        }
                    }
                    else
                    {
                        for (int r = 0; r < TableIn.RowCount; r++)
                        {
                            PosX[r] = (PosX[r] - ShiftX[r]) * (float)Options.Tasks.InputPixelSize;
                            PosY[r] = (PosY[r] - ShiftY[r]) * (float)Options.Tasks.InputPixelSize;
                            PosZ[r] = (PosZ[r] - ShiftZ[r]) * (float)Options.Tasks.InputPixelSize;
                        }
                    }

                    float[] AngleRot  = TableIn.HasColumn("rlnAngleRot") && Options.Tasks.TomoSubReconstructPrerotated ? TableIn.GetColumn("rlnAngleRot").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    float[] AngleTilt = TableIn.HasColumn("rlnAngleTilt") && Options.Tasks.TomoSubReconstructPrerotated ? TableIn.GetColumn("rlnAngleTilt").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    float[] AnglePsi  = TableIn.HasColumn("rlnAnglePsi") && Options.Tasks.TomoSubReconstructPrerotated ? TableIn.GetColumn("rlnAnglePsi").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];

                    if (TableIn.HasColumn("rlnOriginX"))
                    {
                        TableIn.RemoveColumn("rlnOriginX");
                    }
                    if (TableIn.HasColumn("rlnOriginY"))
                    {
                        TableIn.RemoveColumn("rlnOriginY");
                    }
                    if (TableIn.HasColumn("rlnOriginZ"))
                    {
                        TableIn.RemoveColumn("rlnOriginZ");
                    }

                    if (AdditionalShiftAngstrom.Length() > 0)
                    {
                        for (int r = 0; r < TableIn.RowCount; r++)
                        {
                            Matrix3 R = Matrix3.Euler(AngleRot[r] * Helper.ToRad,
                                                      AngleTilt[r] * Helper.ToRad,
                                                      AnglePsi[r] * Helper.ToRad);
                            float3 RotatedShift = R *AdditionalShiftAngstrom;

                            PosX[r] += RotatedShift.X;
                            PosY[r] += RotatedShift.Y;
                            PosZ[r] += RotatedShift.Z;
                        }
                    }

                    if (Options.Tasks.TomoSubReconstructPrerotated)
                    {
                        if (TableIn.HasColumn("rlnAngleRot"))
                        {
                            TableIn.RemoveColumn("rlnAngleRot");
                            TableIn.AddColumn("rlnAngleRot", "0");
                        }
                        if (TableIn.HasColumn("rlnAngleTilt"))
                        {
                            TableIn.RemoveColumn("rlnAngleTilt");
                            TableIn.AddColumn("rlnAngleTilt", "0");
                        }
                        if (TableIn.HasColumn("rlnAnglePsi"))
                        {
                            TableIn.RemoveColumn("rlnAnglePsi");
                            TableIn.AddColumn("rlnAnglePsi", "0");
                        }
                    }

                    #endregion

                    Dispatcher.Invoke(() => ProgressWrite.MaxValue = ValidSeries.Count);


                    //Dispatcher.Invoke(() =>
                    //{
                    //    ProgressWrite.IsIndeterminate = true;
                    //    TextRemaining.Text = "?:??";
                    //});

                    Helper.ForEachGPU(ValidSeries, (series, gpuID) =>
                    {
                        if (IsCanceled)
                        {
                            return;
                        }

                        Stopwatch ItemTime = new Stopwatch();
                        ItemTime.Start();

                        ProcessingOptionsTomoSubReconstruction ExportOptions = Options.GetProcessingTomoSubReconstruction();

                        #region Update row values

                        List <int> GroupRows = Groups.First(n => n.Key.Contains(series.RootName)).Value;

                        int pi = 0;
                        foreach (var r in GroupRows)
                        {
                            TableIn.SetRowValue(r, "rlnCtfMaxResolution", series.CTFResolutionEstimate.ToString("F1", CultureInfo.InvariantCulture));

                            TableIn.SetRowValue(r, "rlnCoordinateX", (PosX[r] / (float)ExportOptions.BinnedPixelSizeMean).ToString("F3", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnCoordinateY", (PosY[r] / (float)ExportOptions.BinnedPixelSizeMean).ToString("F3", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnCoordinateZ", (PosZ[r] / (float)ExportOptions.BinnedPixelSizeMean).ToString("F3", CultureInfo.InvariantCulture));

                            #region Figure out relative or absolute path to sub-tomo and its CTF

                            string PathSubtomo = series.SubtomoDir + $"{series.RootName}{ExportOptions.Suffix}_{pi:D7}_{ExportOptions.BinnedPixelSizeMean:F2}A.mrc";
                            string PathCTF     = //MakeSparse ?
                                                 //(series.SubtomoDir + $"{series.RootName}_{pi:D7}_ctf_{ExportOptions.BinnedPixelSizeMean:F2}A.tif") :
                                                 (series.SubtomoDir + $"{series.RootName}{ExportOptions.Suffix}_{pi:D7}_ctf_{ExportOptions.BinnedPixelSizeMean:F2}A.mrc");
                            if (Relative)
                            {
                                Uri UriStar = new Uri(ExportPath);
                                PathSubtomo = UriStar.MakeRelativeUri(new Uri(PathSubtomo)).ToString();
                                PathCTF     = UriStar.MakeRelativeUri(new Uri(PathCTF)).ToString();
                            }

                            #endregion

                            TableIn.SetRowValue(r, "rlnImageName", PathSubtomo);
                            TableIn.SetRowValue(r, "rlnCtfImage", PathCTF);

                            pi++;
                        }

                        #endregion

                        #region Populate micrograph table with rows for all exported particles

                        Star MicrographTable = new Star(TableIn.GetColumnNames());

                        foreach (var r in GroupRows)
                        {
                            MicrographTable.AddRow(TableIn.GetRow(r).ToList());
                        }

                        #endregion

                        #region Finally, reconstruct the actual sub-tomos

                        float3[] TomoPositions = Helper.Combine(GroupRows.Select(r => Helper.ArrayOfConstant(new float3(PosX[r], PosY[r], PosZ[r]), series.NTilts)).ToArray());
                        float3[] TomoAngles    = Helper.Combine(GroupRows.Select(r => Helper.ArrayOfConstant(new float3(AngleRot[r], AngleTilt[r], AnglePsi[r]), series.NTilts)).ToArray());

                        if (DoVolumes)
                        {
                            Workers[gpuID].TomoExportParticles(series.Path, ExportOptions, TomoPositions, TomoAngles);
                            //series.ReconstructSubtomos(ExportOptions, TomoPositions, TomoAngles);

                            lock (MicrographTables)
                                MicrographTables.Add(series.RootName, MicrographTable);
                        }
                        else
                        {
                            Star SeriesTable;
                            Random Rand   = new Random(123);
                            int[] Subsets = Helper.ArrayOfFunction(i => Rand.Next(1, 3), GroupRows.Count);
                            series.ReconstructParticleSeries(ExportOptions, TomoPositions, TomoAngles, Subsets, ExportPath, out SeriesTable);

                            lock (MicrographTables)
                                MicrographTables.Add(series.RootName, SeriesTable);
                        }

                        #endregion

                        #region Add this micrograph's table to global collection, update remaining time estimate

                        lock (MicrographTables)
                        {
                            Timings.Add(ItemTime.ElapsedMilliseconds / (float)UsedDeviceProcesses.Count);

                            int MsRemaining        = (int)(MathHelper.Mean(Timings) * (ValidSeries.Count - MicrographTables.Count));
                            TimeSpan SpanRemaining = new TimeSpan(0, 0, 0, 0, MsRemaining);

                            Dispatcher.Invoke(() => TextRemaining.Text = SpanRemaining.ToString((int)SpanRemaining.TotalHours > 0 ? @"hh\:mm\:ss" : @"mm\:ss"));

                            Dispatcher.Invoke(() =>
                            {
                                ProgressWrite.IsIndeterminate = false;
                                ProgressWrite.Value           = MicrographTables.Count;
                            });
                        }

                        #endregion
                    }, 1, UsedDeviceProcesses);

                    if (MicrographTables.Count > 0)
                    {
                        TableOut = new Star(MicrographTables.Values.ToArray());
                    }
                }

                Thread.Sleep(10000);    // Writing out particles is async, so if workers are killed immediately they may not write out everything

                foreach (var worker in Workers)
                {
                    worker?.Dispose();
                }

                if (IsCanceled)
                {
                    return;
                }

                TableOut.Save(ExportPath);
            });

            Close?.Invoke();
        }
        /// <summary>
        /// Метод создания и сохранения документов
        /// в форматах Microsoft Word (doc, PDF),
        /// Excel (exls)
        /// </summary>
        /// <param name="type">Тип создаваемого документа
        /// отчёт или статистика</param>
        /// <param name="format">Формат сохранения
        /// документ или таблица</param>
        /// <param name="name">Название документа</param>
        /// <param name="table">Входная таблица с данными</param>
        public void Document_Create(Document_Type type,
                                    Document_Format format, string name,
                                    DataTable table)
        {
            string filename = "";

            if (format == Document_Format.Word)
            {
                System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
                saveFileDialog.Filter = "Word документ (*.doc)|*.doc|Все файлы (*.*)|*.*";
                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                {
                    return;
                }
                filename = saveFileDialog.FileName;
            }


            //Получение данных о конфигурации документа
            Configuration_class configuration_Class
                = new Configuration_class();

            configuration_Class.Document_Configuration_Get();
            //Проверка на пустоту названия
            switch (name != "" || name != null)
            {
            case true:
                //Выбор формата либо Word либо PDF

                //Запуск процесса в дистпечере задач
                word.Application application
                    = new word.Application();
                //создание документа в процессе
                word.Document document
                //Присвоение документа процессу, Visible: true
                //возможность редактирования документа
                    = application.Documents.Add(Visible: true);
                try
                {
                    //Объявление дипапазона для формирования текста
                    word.Range range = document.Range(0, 0);
                    //Настройка отступов в документе
                    document.Sections.PageSetup.LeftMargin
                        = application.CentimetersToPoints(
                              (float)Configuration_class.
                              doc_Left_Merge);
                    document.Sections.PageSetup.TopMargin
                        = application.CentimetersToPoints(
                              (float)Configuration_class.
                              doc_Top_Merge);
                    document.Sections.PageSetup.RightMargin
                        = application.
                          CentimetersToPoints((float)
                                              Configuration_class.doc_Right_Merg);
                    document.Sections.PageSetup.BottomMargin
                        = application.CentimetersToPoints(
                              (float)Configuration_class.
                              doc_Bottom_Merge);
                    //Присвоение текстового знеачения в дипазон
                    range.Text =
                        Configuration_class.Organization_Name;
                    //Настройка выравнивания текста
                    range.ParagraphFormat.Alignment =
                        word.WdParagraphAlignment.
                        wdAlignParagraphCenter;
                    //Настройка интервала после абзаца
                    range.ParagraphFormat.SpaceAfter = 1;
                    //Настройка интервала перед абзаца
                    range.ParagraphFormat.SpaceBefore = 1;
                    //Настройка межстрочного интервала
                    range.ParagraphFormat.LineSpacingRule
                        = word.WdLineSpacing.wdLineSpaceSingle;
                    //Настройка названия шрифта
                    range.Font.Name = "Times New Roman";
                    //Настройка размера шрифта
                    range.Font.Size = 12;
                    //Добавление параграфов
                    document.Paragraphs.Add();            //В конце текста
                    document.Paragraphs.Add();            //Свободный
                    document.Paragraphs.Add();            //Для будущего текста
                    //Параграф для названия документа
                    word.Paragraph Document_Name
                        = document.Paragraphs.Add();
                    //Настройка параграфа через свойство диапазона
                    Document_Name.Format.Alignment
                        = word.WdParagraphAlignment.wdAlignParagraphCenter;
                    Document_Name.Range.Font.Name = "Times New Roman";
                    Document_Name.Range.Font.Size = 16;
                    //Проверка на тип документа, отчёт или статистика
                    switch (type)
                    {
                    case Document_Type.Report:
                        Document_Name.Range.Text = "ОТЧЁТ";

                        break;

                    case Document_Type.Statistic:
                        Document_Name.Range.Text = "СТАТИСТИЧЕСКИЙ ОТЧЁТ";
                        break;

                    case Document_Type.List:
                        Document_Name.Range.Text = "СПИСОК СОТРУДНИКОВ";
                        break;

                    case Document_Type.Check:
                        Document_Name.Range.Text = "ЧЕК";
                        break;
                    }
                    document.Paragraphs.Add();
                    document.Paragraphs.Add();
                    document.Paragraphs.Add();
                    word.Paragraph statparg = document.Paragraphs.Add();
                    //Создание области таблицы в документе


                    if (type == Document_Type.Check)
                    {
                        word.Table stat_table2
                            = document.Tables.Add(statparg.Range,
                                                  2, 5);
                        stat_table2.Borders.InsideLineStyle
                            = word.WdLineStyle.wdLineStyleSingle;
                        //Настройка границ таблицы внешние
                        stat_table2.Borders.OutsideLineStyle
                            = word.WdLineStyle.wdLineStyleSingle;
                        //Выравнивание текста внутри ячеек по ширине
                        stat_table2.Rows.Alignment
                            = word.WdRowAlignment.wdAlignRowCenter;
                        //Выравнивание текста внутри ячеек по высоте
                        stat_table2.Range.Cells.VerticalAlignment =
                            word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        stat_table2.Range.Font.Size       = 11;
                        stat_table2.Range.Font.Name       = "Times New Roman";
                        stat_table2.Cell(1, 1).Range.Text = "Цена";
                        stat_table2.Cell(1, 2).Range.Text = "Дата";
                        stat_table2.Cell(1, 3).Range.Text = "Фамилия";
                        stat_table2.Cell(1, 4).Range.Text = "Имя";
                        stat_table2.Cell(1, 5).Range.Text = "Отчество";
                        stat_table2.Cell(2, 1).Range.Text = table.Rows[0][0].ToString();
                        stat_table2.Cell(2, 2).Range.Text = table.Rows[0][1].ToString();
                        stat_table2.Cell(2, 3).Range.Text = table.Rows[0][2].ToString();
                        stat_table2.Cell(2, 4).Range.Text = table.Rows[0][3].ToString();
                        stat_table2.Cell(2, 5).Range.Text = table.Rows[0][4].ToString();
                    }



                    if (type != Document_Type.Check)
                    {
                        word.Table stat_table
                        //Добавление таблицы в область документа
                        //Указывается параграф в котором документ создан
                        //Количество строк и столбцов
                            = document.Tables.Add(statparg.Range,
                                                  table.Rows.Count, table.Columns.Count);

                        //Настройка границ таблицы внутренние
                        stat_table.Borders.InsideLineStyle
                            = word.WdLineStyle.wdLineStyleSingle;
                        //Настройка границ таблицы внешние
                        stat_table.Borders.OutsideLineStyle
                            = word.WdLineStyle.wdLineStyleSingle;
                        //Выравнивание текста внутри ячеек по ширине
                        stat_table.Rows.Alignment
                            = word.WdRowAlignment.wdAlignRowCenter;
                        //Выравнивание текста внутри ячеек по высоте
                        stat_table.Range.Cells.VerticalAlignment =
                            word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        stat_table.Range.Font.Size = 11;
                        stat_table.Range.Font.Name = "Times New Roman";
                        //Индексация столбцов и строк в Word начинается с 1,1
                        for (int row = 1; row <= table.Rows.Count; row++)
                        {
                            for (int col = 1; col <= table.Columns.Count; col++)
                            {
                                stat_table.Cell(row, col).Range.Text
                                    = table.Rows[row - 1][col - 1].ToString();
                            }
                        }
                    }



                    document.Paragraphs.Add();
                    document.Paragraphs.Add();
                    //Парадграф с фиксациейц даты создания документа
                    word.Paragraph Footparg = document.Paragraphs.Add();
                    Footparg.Range.Text =
                        string.Format("Дата создания \t\t\t{0}",
                                      DateTime.Now.ToString("dd.MM.yyyy"));
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                }
                finally
                {
                    switch (format)
                    {
                    case Document_Format.Word:
                        //Сохранение документа с названием из метода,
                        //и в формате doc
                        document.SaveAs2(filename,
                                         word.WdSaveFormat.wdFormatDocument);
                        //document.SaveAs2(string.Format("{0}\\{1}",Environment.CurrentDirectory, name) ,
                        //    word.WdSaveFormat.wdFormatDocument); filename
                        document.Close();
                        break;

                    case Document_Format.PDF:
                        //Сохранение документа в формате PDF
                        document.SaveAs2(string.Format("{0}\\{1}", Environment.CurrentDirectory, name),
                                         word.WdSaveFormat.wdFormatPDF);
                        break;
                    }
                    //Закрываем документ

                    //Выходим из процесса с его закрытием
                    application.Quit();
                }
                break;
            }
        }
Пример #44
0
        /// <summary>
        /// 엑셀다운로드
        /// </summary>
        /// <param name="obj"></param>
        private void ExcelDownAction(object obj)
        {
            try
            {
                /// 데이터조회
                Hashtable conditions = new Hashtable();
                conditions.Add("RCV_NUM", cnstCmplListView.txtRCV_NUM.Text.Trim());
                conditions.Add("APL_HJD", cbHJD_CDE.EditValue);
                conditions.Add("APL_CDE", cbAPL_CDE.EditValue);
                conditions.Add("PRO_CDE", cbPRO_CDE.EditValue);
                conditions.Add("RCV_YMD_FROM", cnstCmplListView.dtRCV_YMD_FROM.EditValue == null ? "" : Convert.ToDateTime(cnstCmplListView.dtRCV_YMD_FROM.EditValue).ToString("yyyyMMdd"));
                conditions.Add("RCV_YMD_TO", cnstCmplListView.dtRCV_YMD_TO.EditValue == null ? "" : Convert.ToDateTime(cnstCmplListView.dtRCV_YMD_TO.EditValue).ToString("yyyyMMdd"));
                conditions.Add("PRO_YMD_FROM", cnstCmplListView.dtPRO_YMD_FROM.EditValue == null ? "" : Convert.ToDateTime(cnstCmplListView.dtPRO_YMD_FROM.EditValue).ToString("yyyyMMdd"));
                conditions.Add("PRO_YMD_TO", cnstCmplListView.dtPRO_YMD_TO.EditValue == null ? "" : Convert.ToDateTime(cnstCmplListView.dtPRO_YMD_TO.EditValue).ToString("yyyyMMdd"));


                conditions.Add("page", 0);
                conditions.Add("rows", 1000000);

                conditions.Add("sqlId", "SelectCnstCmplList");


                exceldt = BizUtil.SelectList(conditions);


                //그리드헤더정보 추출
                columnList = new GridColumn[grid.Columns.Count];
                grid.Columns.CopyTo(columnList, 0);
                listCols = new List <string>(); //컬럼헤더정보 가져오기
                foreach (GridColumn gcol in columnList)
                {
                    try
                    {
                        if ("PrintN".Equals(gcol.Tag.ToString()))
                        {
                            continue;                                       //엑셀출력제외컬럼
                        }
                    }
                    catch (Exception) { }

                    listCols.Add(gcol.FieldName.ToString());
                }


                saveFileDialog       = null;
                saveFileDialog       = new System.Windows.Forms.SaveFileDialog();
                saveFileDialog.Title = "저장경로를 지정하세요.";

                //초기 파일명 지정
                saveFileDialog.FileName = DateTime.Now.ToString("yyyyMMdd") + "_" + "상수공사 민원목록.xlsx";

                saveFileDialog.OverwritePrompt = true;
                saveFileDialog.Filter          = "Excel|*.xlsx";

                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    strFileName = saveFileDialog.FileName;
                    thread      = new Thread(new ThreadStart(ExcelExportFX));
                    thread.Start();
                }
            }
            catch (Exception ex)
            {
                Messages.ShowErrMsgBoxLog(ex);
            }
        }
Пример #45
0
        /// <summary>
        /// Convert report as excel document
        /// </summary>
        /// <returns></returns>
        /// 2019/07/13, Vinoth N,  Initial Version
        private void DeliveryListGeneration()
        {
            string sheetName      = "";
            string resonForChange = "";
            string msg            = string.Empty;
            string location       = string.Empty;

            Excel.Application excelapp = new Excel.Application();
            Excel.Workbook    workbook = null;
            this.Dispatcher.Invoke(() =>
            {
                sheetName      = t_POTag.Text ?? "non";
                resonForChange = t_Reason.Text ?? "";
                location       = t_Location.Text;
            });
            if (sheetName.Length < 30)
            {
                if (sheetName.Contains("[") || sheetName.Contains("]"))
                {
                    char[] chars = new char[] { '[', ']', '/', '?', '*' };
                    sheetName = chars.Aggregate(sheetName, (c1, c2) => c1.Replace(c2, ' '));
                    sheetName = sheetName.Replace(" ", "");
                }
                try
                {
                    LogModel.Log("Report Generation Started");
                    string excelPath = System.Environment.CurrentDirectory.ToString();
                    if (excelPath.Contains(@"\bin\Debug"))
                    {
                        excelPath = excelPath.Remove((excelPath.Length - (@"\bin\Debug").Length));
                    }

                    excelapp.Visible = false;
                    workbook         = excelapp.Workbooks.Open(excelPath + @"\\App_Data\\KLOC_Template.xls");
                    PrepareKLOCReport(workbook, sheetName, resonForChange);
                    this.Dispatcher.Invoke(() =>
                    {
                        using (System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog()
                        {
                            Filter = "XLS|*.xls|XLSX|*.xlsx", ValidateNames = true, FileName = "PRS Report", InitialDirectory = location
                        })
                        {
                            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                if (Path.GetExtension(sfd.FileName) == ".xlsx")
                                {
                                    workbook.SaveAs(sfd.FileName, Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, Excel.XlSaveAsAccessMode.xlShared, Excel.XlSaveConflictResolution.xlUserResolution, Type.Missing, Type.Missing);
                                }
                                else
                                {
                                    workbook.SaveAs(sfd.FileName);
                                }
                                msg = "Download Completed";
                                counterStatus.Content = msg;
                                LogModel.Log(msg);
                            }
                            else
                            {
                                msg = "Download Cancelled";
                                StopGeneration(msg);
                            }
                        }
                    });
                }
                catch (Exception ex)
                {
                    StopGeneration(ex.Message);
                    LogModel.Log(ex.Message);
                    LogModel.Log(ex.StackTrace);
                    MessageBox.Show("Excel Template Not Found !");
                }
                finally
                {
                    CloseWorkSheet(excelapp, workbook);
                    LogModel.Log("Report Generation Ended");
                }
            }
            else
            {
                msg = "Excel sheet name length is exceeded: " + sheetName + ". Please change the project name then try...";
                StopGeneration(msg);
                MessageBox.Show(msg);
            }
        }
Пример #46
0
            public void Plot_PTB_Results()
            {
                if (Direct_Data == null && IS_Data == null && Receiver == null && Parameter_Choice.Text != "Sabine RT" && Parameter_Choice.Text != "Eyring RT")
                {
                    return;
                }
                double[] Schroeder;
                string[] paramtype    = new string [] { "T30/s", "EDT/s", "D/%", "C/dB", "TS/ms", "G/dB", "LF%", "LFC%", "IACC" };//LF/% LFC/% IACC
                string   ReceiverLine = "Receiver{0};";

                double[, , ,] ParamValues = new double[SourceList.Items.Count, Recs.Length, 8, paramtype.Length];

                for (int s = 0; s < Direct_Data.Length; s++)
                {
                    for (int r = 0; r < Recs.Length; r++)
                    {
                        ReceiverLine += r.ToString() + ";";
                        for (int oct = 0; oct < 8; oct++)
                        {
                            double[] ETC = IR_Construction.ETCurve(Direct_Data, IS_Data, Receiver, (int)(CO_TIME.Value / 1000), SampleRate, oct, r, s, false);
                            Schroeder = AcousticalMath.Schroeder_Integral(ETC);
                            ParamValues[s, r, oct, 0] = AcousticalMath.T_X(Schroeder, 30, SampleRate);
                            ParamValues[s, r, oct, 1] = AcousticalMath.EarlyDecayTime(Schroeder, SampleRate);
                            ParamValues[s, r, oct, 2] = AcousticalMath.Definition(ETC, SampleRate, 0.05, Direct_Data[s].Min_Time(r), false);
                            ParamValues[s, r, oct, 3] = AcousticalMath.Clarity(ETC, SampleRate, 0.08, Direct_Data[s].Min_Time(r), false);
                            ParamValues[s, r, oct, 4] = AcousticalMath.Center_Time(ETC, SampleRate, Direct_Data[s].Min_Time(r)) * 1000;
                            ParamValues[s, r, oct, 5] = AcousticalMath.Strength(ETC, Direct_Data[s].SWL[oct], false);
                            double azi, alt;
                            PachTools.World_Angles(Direct_Data[s].Src.Origin(), Recs[r], true, out alt, out azi);
                            double[][] Lateral_ETC = IR_Construction.ETCurve_1d(Direct_Data, IS_Data, Receiver, CutoffTime, SampleRate, oct, r, new System.Collections.Generic.List <int> {
                                s
                            }, false, alt, azi, true);
                            ParamValues[s, r, oct, 6] = AcousticalMath.Lateral_Fraction(ETC, Lateral_ETC, SampleRate, Direct_Data[s].Min_Time(r), false);
                        }
                    }
                }

                System.Windows.Forms.SaveFileDialog sf = new System.Windows.Forms.SaveFileDialog();
                sf.DefaultExt   = ".txt";
                sf.AddExtension = true;
                sf.Filter       = "Text File (*.txt)|*.txt|" + "All Files|";

                if (sf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        System.IO.StreamWriter SW = new System.IO.StreamWriter(System.IO.File.Open(sf.FileName, System.IO.FileMode.Create));
                        SW.WriteLine("Pachyderm Acoustic Simulation Results");
                        SW.WriteLine("Saved {0}", System.DateTime.Now.ToString());
                        SW.WriteLine("Filename:{0}", Rhino.RhinoDoc.ActiveDoc.Name);

                        for (int oct = 0; oct < 8; oct++)
                        {
                            SW.WriteLine(string.Format(ReceiverLine, oct));
                            for (int param = 0; param < paramtype.Length; param++)
                            {
                                SW.Write(paramtype[param] + ";");
                                for (int i = 0; i < Direct_Data.Length; i++)
                                {
                                    for (int q = 0; q < Recs.Length; q++)
                                    {
                                        SW.Write(ParamValues[i, q, oct, param].ToString() + ";");
                                    }
                                }
                                SW.WriteLine("");
                            }
                        }
                        SW.Close();
                    }
                    catch (System.Exception)
                    {
                        Rhino.RhinoApp.WriteLine("File is open, and cannot be written over.");
                        return;
                    }
                }
            }
Пример #47
0
        /// <summary>
        /// 생성자
        /// </summary>
        public FilePopViewModel()
        {
            // 초기로딩처리
            LoadedCommand = new DelegateCommand <object>(OnLoaded);


            // 파일인포리스트
            ItemsFile   = new ObservableCollection <FileInfo>();
            ItemsSelect = new ObservableCollection <FileDtl>();
            ItemsAdd    = new ObservableCollection <FileDtl>();



            //파일저장버튼 이벤트
            SaveCmd = new RelayCommand <object>(delegate(object obj)
            {
                upload_thread = new Thread(new ThreadStart(UploadFileListFX));
                upload_thread.Start();
            });

            //파일삭제버튼 이벤트
            DelCmd = new DelegateCommand <object>(delegate(object obj)
            {
                string seq = "";
                try
                {
                    seq = obj.ToString();
                }
                catch (Exception) {}

                if (FmsUtil.IsNull(seq) || "0".Equals(seq))
                {
                    Messages.ShowErrMsgBox("삭제할 대상이 없습니다.");
                    return;
                }


                string file_name     = "";
                string del_file_path = "";



                //0.첨부파일정보가져오기
                Hashtable param = new Hashtable();
                try
                {
                    param.Add("FIL_SEQ", this.FIL_SEQ);
                    param.Add("SEQ", seq);
                    param.Add("sqlId", "SelectFileDtl");
                    DataTable dt = BizUtil.SelectList(param);
                    //물리파일명 가져오기
                    file_name = dt.Rows[0]["UPF_NAM"].ToString();
                }
                catch (Exception ex)
                {
                    Messages.ShowInfoMsgBox(ex.ToString());
                    InitModel();
                    return;
                }


                //1.첨부파일상세테이블 삭제
                param["sqlId"] = "DeleteFileSeq";
                BizUtil.Update(param);


                //2.물리적파일 삭제
                del_file_path = System.IO.Path.Combine(dir_name, file_name);
                try
                {
                    FileInfo fi = new FileInfo(del_file_path);
                    fi.Delete();
                }
                catch (Exception) {}

                //삭제성공
                Messages.ShowOkMsgBox();
                InitModel();
            });



            //기존파일 다운로드버튼 이벤트
            DownloadCmd = new RelayCommand <object>(delegate(object obj)
            {
                FileDtl dtl       = obj as FileDtl;
                string file_name  = dtl.DWN_NAM;
                string file_name2 = dtl.UPF_NAM;

                try
                {
                    source_file_path = System.IO.Path.Combine(dir_name, file_name2);
                }
                catch (Exception)
                {
                    Messages.ShowErrMsgBox("다운로드할 수 없습니다.");
                    return;
                }


                //파일다운로드
                saveFileDialog       = new System.Windows.Forms.SaveFileDialog();
                saveFileDialog.Title = "저장경로를 지정하세요.";
                //초기 파일명 지정
                saveFileDialog.FileName        = file_name;
                saveFileDialog.OverwritePrompt = true;
                //saveFileDialog.Filter = "Excel|*.xlsx";
                //saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
                saveFileDialog.Filter = "All files (*.*)|*.*";

                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    target_file_path = saveFileDialog.FileName;
                    download_thread  = new Thread(new ThreadStart(DownloadFX));
                    download_thread.Start();
                }
            });


            //파일찾기버튼 이벤트
            FindFileCmd = new RelayCommand <object>(delegate(object obj)
            {
                OpenFileDialog openFileDialog   = new OpenFileDialog();
                openFileDialog.Multiselect      = true;
                openFileDialog.Filter           = "Image Files |*.jpg;*.jpeg;*.png;*.gif;*.bmp;*.tif;*.tiff;";
                openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                if (openFileDialog.ShowDialog() == true)
                {
                    FileInfo[] files = openFileDialog.FileNames.Select(f => new FileInfo(f)).ToArray();  //파일인포

                    foreach (FileInfo fi in files)
                    {
                        //파일객체
                        ItemsFile.Add(fi);

                        //파일db객체
                        FileDtl dtl = new FileDtl();
                        dtl.DWN_NAM = fi.Name;
                        dtl.FIL_TYP = fi.Extension.Replace(".", "");
                        dtl.FIL_SIZ = fi.Length.ToString();
                        ItemsSelect.Add(dtl);
                    }
                }
            });



            //윈도우 마우스드래그
            WindowMoveCommand = new DelegateCommand <object>(delegate(object obj)
            {
                try
                {
                    if (Mouse.LeftButton == MouseButtonState.Pressed)
                    {
                        if (filePopView.WindowState == WindowState.Maximized)
                        {
                            filePopView.Top  = Mouse.GetPosition(filePopView).Y - System.Windows.Forms.Cursor.Position.Y - 6;
                            filePopView.Left = System.Windows.Forms.Cursor.Position.X - Mouse.GetPosition(filePopView).X + 20;

                            filePopView.WindowState = WindowState.Normal;
                        }
                        filePopView.DragMove();
                    }
                }
                catch (Exception ex)
                {
                    Messages.ShowErrMsgBoxLog(ex);
                }
            });
        }
Пример #48
0
        /// <summary>
        /// retrieves categories from server, generates price requests, sends, receives prices and saves to text file
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            // NOTES: Anything can be done in this method, such as create a message box,
            // a task dialog or fetch some information from revit and so on.
            // We mainly use the task dialog for example.

            // Get the application and document from external command data.
            Application app    = commandData.Application.Application;
            Document    curDoc = commandData.Application.ActiveUIDocument.Document;

            //loads from settings.txt
            settings.LoadSettings();
            List <string> cats = new List <string>();

            PricingHttpRest.InitializeClient(settings.APILocation, "");
            string configJSON = "";

            try
            {
                PricingHttpRest.APICommand = "pricing/config";
                string result = PricingHttpRest.Get();

                configJSON = PricingHttpRest.receivedContent;
                if (result != "OK")
                {
                    System.Windows.Forms.MessageBox.Show("Error accessing API while getting config");
                    return(Autodesk.Revit.UI.Result.Failed);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Error accessing API while getting config");
                return(Autodesk.Revit.UI.Result.Failed);
            }


            try
            {
                Newtonsoft.Json.Linq.JToken jt   = Newtonsoft.Json.Linq.JObject.Parse(configJSON);
                Newtonsoft.Json.Linq.JToken jfil = jt.SelectToken("filters");
                Newtonsoft.Json.Linq.JToken jcat = jfil.SelectToken("categories");
                cats = jcat.ToObject <List <string> >();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Deserialization failure: " + ex.ToString());
                return(Autodesk.Revit.UI.Result.Failed);
            }
            if (cats.Count == 0)
            {
                System.Windows.Forms.MessageBox.Show("No categories found, taking all");
            }
            //if (myConf.filters.Count==0)
            //{
            //    System.Windows.Forms.MessageBox.Show("No config data");
            //    return Autodesk.Revit.UI.Result.Failed;
            //}

            revit_pricing_request price1 = utilities.get_pricing_request(curDoc, cats);


            //send element data
            string serialS    = JsonConvert.SerializeObject(price1);
            string pricesJSON = "";

            try
            {
                PricingHttpRest.APICommand  = "pricing/model1";
                PricingHttpRest.sendContent = serialS;

                string result = PricingHttpRest.Post();

                pricesJSON = PricingHttpRest.receivedContent;
                if (result != "OK")
                {
                    System.Windows.Forms.MessageBox.Show("Error accessing API while submitting  data for pricing: " + result + " " + pricesJSON);
                    return(Autodesk.Revit.UI.Result.Failed);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Error accessing API while submitting  data for pricing: " + ex.ToString());
                return(Autodesk.Revit.UI.Result.Failed);
            }


            System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog1.Filter = "Text file|*.txt";
            saveFileDialog1.Title  = "Save Price / Instance Data";
            saveFileDialog1.ShowDialog();

            // If the file name is not an empty string open it for saving.
            if (saveFileDialog1.FileName != "")
            {
                System.IO.File.WriteAllText(saveFileDialog1.FileName, pricesJSON);
            }

            return(Autodesk.Revit.UI.Result.Succeeded);
        }
Пример #49
0
        private async void ButtonExport_OnClick(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog SaveDialog = new System.Windows.Forms.SaveFileDialog
            {
                Filter = "STAR Files|*.star"
            };
            System.Windows.Forms.DialogResult ResultSave = SaveDialog.ShowDialog();

            if (ResultSave.ToString() == "OK")
            {
                ExportPath = SaveDialog.FileName;
            }
            else
            {
                return;
            }

            bool DoAverage        = (bool)RadioAverage.IsChecked;
            bool DoStack          = (bool)RadioStack.IsChecked;
            bool DoDenoisingPairs = (bool)RadioDenoising.IsChecked;
            bool DoOnlyStar       = (bool)RadioStar.IsChecked;

            bool Invert    = (bool)CheckInvert.IsChecked;
            bool Normalize = (bool)CheckNormalize.IsChecked;
            bool Preflip   = (bool)CheckPreflip.IsChecked;

            float AngPix = (float)Options.Tasks.InputPixelSize;

            bool Relative = (bool)CheckRelative.IsChecked;

            bool Filter = (bool)CheckFilter.IsChecked;
            bool Manual = (bool)CheckManual.IsChecked;

            int BoxSize      = (int)Options.Tasks.Export2DBoxSize;
            int NormDiameter = (int)Options.Tasks.Export2DParticleDiameter;

            ProgressWrite.Visibility      = Visibility.Visible;
            ProgressWrite.IsIndeterminate = true;
            PanelButtons.Visibility       = Visibility.Collapsed;
            PanelRemaining.Visibility     = Visibility.Visible;

            foreach (var element in DisableWhileProcessing)
            {
                element.IsEnabled = false;
            }

            await Task.Run(async() =>
            {
                #region Get all movies that can potentially be used

                List <Movie> ValidMovies = Movies.Where(v =>
                {
                    if (!Filter && v.UnselectFilter && v.UnselectManual == null)
                    {
                        return(false);
                    }
                    if (!Manual && v.UnselectManual != null && (bool)v.UnselectManual)
                    {
                        return(false);
                    }
                    if (v.OptionsCTF == null)
                    {
                        return(false);
                    }
                    return(true);
                }).ToList();
                List <string> ValidMovieNames = ValidMovies.Select(m => m.RootName).ToList();

                if (ValidMovies.Count == 0)
                {
                    await Dispatcher.Invoke(async() =>
                    {
                        await((MainWindow)Application.Current.MainWindow).ShowMessageAsync("Oopsie",
                                                                                           "No items were found to extract particles from.\n" +
                                                                                           "Please make sure the names match, estimate the CTF for all items, and review your filtering thresholds.");
                    });
                }

                #endregion

                #region Read table and intersect its micrograph set with valid movies

                Star TableIn;

                if (Options.Tasks.InputOnePerItem)
                {
                    List <Star> Tables = new List <Star>();
                    foreach (var item in Movies)
                    {
                        string StarPath = InputFolder + item.RootName + InputSuffix + ".star";
                        if (File.Exists(StarPath))
                        {
                            Star TableItem = new Star(StarPath);
                            if (!TableItem.HasColumn("rlnMicrographName"))
                            {
                                TableItem.AddColumn("rlnMicrographName", item.Name);
                            }

                            if (item.PickingThresholds.ContainsKey(InputSuffix) && TableItem.HasColumn("rlnAutopickFigureOfMerit"))
                            {
                                float Threshold   = (float)item.PickingThresholds[InputSuffix];
                                float[] Scores    = TableItem.GetColumn("rlnAutopickFigureOfMerit").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                                int[] InvalidRows = Helper.ArrayOfSequence(0, TableItem.RowCount, 1).Where(i => Scores[i] < Threshold).ToArray();
                                TableItem.RemoveRows(InvalidRows);
                            }

                            Tables.Add(TableItem);
                        }
                    }

                    TableIn = new Star(Tables.ToArray());
                }
                else
                {
                    TableIn = new Star(ImportPath);
                }

                if (!TableIn.HasColumn("rlnMicrographName"))
                {
                    throw new Exception("Couldn't find rlnMicrographName column.");
                }
                if (!TableIn.HasColumn("rlnCoordinateX"))
                {
                    throw new Exception("Couldn't find rlnCoordinateX column.");
                }
                if (!TableIn.HasColumn("rlnCoordinateY"))
                {
                    throw new Exception("Couldn't find rlnCoordinateY column.");
                }

                Dictionary <string, List <int> > Groups = new Dictionary <string, List <int> >();
                {
                    string[] ColumnMicNames = TableIn.GetColumn("rlnMicrographName");
                    for (int r = 0; r < ColumnMicNames.Length; r++)
                    {
                        if (!Groups.ContainsKey(ColumnMicNames[r]))
                        {
                            Groups.Add(ColumnMicNames[r], new List <int>());
                        }
                        Groups[ColumnMicNames[r]].Add(r);
                    }
                    Groups = Groups.ToDictionary(group => Helper.PathToName(group.Key), group => group.Value);

                    Groups = Groups.Where(group => ValidMovieNames.Contains(group.Key)).ToDictionary(group => group.Key, group => group.Value);
                }

                bool[] RowsIncluded = new bool[TableIn.RowCount];
                foreach (var group in Groups)
                {
                    foreach (var r in group.Value)
                    {
                        RowsIncluded[r] = true;
                    }
                }
                List <int> RowsNotIncluded = new List <int>();
                for (int r = 0; r < RowsIncluded.Length; r++)
                {
                    if (!RowsIncluded[r])
                    {
                        RowsNotIncluded.Add(r);
                    }
                }

                ValidMovies = ValidMovies.Where(v => Groups.ContainsKey(v.RootName)).ToList();

                if (ValidMovies.Count == 0)     // Exit if there is nothing to export, otherwise errors will be thrown below
                {
                    return;
                }

                #endregion

                #region Make sure all columns are there

                if (!TableIn.HasColumn("rlnMagnification"))
                {
                    TableIn.AddColumn("rlnMagnification", "10000.0");
                }
                else
                {
                    TableIn.SetColumn("rlnMagnification", Helper.ArrayOfConstant("10000.0", TableIn.RowCount));
                }

                if (!TableIn.HasColumn("rlnDetectorPixelSize"))
                {
                    TableIn.AddColumn("rlnDetectorPixelSize", Options.GetProcessingParticleExport().BinnedPixelSizeMean.ToString("F5", CultureInfo.InvariantCulture));
                }
                else
                {
                    TableIn.SetColumn("rlnDetectorPixelSize", Helper.ArrayOfConstant(Options.GetProcessingParticleExport().BinnedPixelSizeMean.ToString("F5", CultureInfo.InvariantCulture), TableIn.RowCount));
                }

                if (!TableIn.HasColumn("rlnVoltage"))
                {
                    TableIn.AddColumn("rlnVoltage", "300.0");
                }

                if (!TableIn.HasColumn("rlnSphericalAberration"))
                {
                    TableIn.AddColumn("rlnSphericalAberration", "2.7");
                }

                if (!TableIn.HasColumn("rlnAmplitudeContrast"))
                {
                    TableIn.AddColumn("rlnAmplitudeContrast", "0.07");
                }

                if (!TableIn.HasColumn("rlnPhaseShift"))
                {
                    TableIn.AddColumn("rlnPhaseShift", "0.0");
                }

                if (!TableIn.HasColumn("rlnDefocusU"))
                {
                    TableIn.AddColumn("rlnDefocusU", "0.0");
                }

                if (!TableIn.HasColumn("rlnDefocusV"))
                {
                    TableIn.AddColumn("rlnDefocusV", "0.0");
                }

                if (!TableIn.HasColumn("rlnDefocusAngle"))
                {
                    TableIn.AddColumn("rlnDefocusAngle", "0.0");
                }

                if (!TableIn.HasColumn("rlnCtfMaxResolution"))
                {
                    TableIn.AddColumn("rlnCtfMaxResolution", "999.0");
                }

                if (!TableIn.HasColumn("rlnImageName"))
                {
                    TableIn.AddColumn("rlnImageName", "None");
                }

                if (!TableIn.HasColumn("rlnMicrographName"))
                {
                    TableIn.AddColumn("rlnMicrographName", "None");
                }

                #endregion

                int NDevices                   = GPU.GetDeviceCount();
                List <int> UsedDevices         = Options.MainWindow.GetDeviceList();
                List <int> UsedDeviceProcesses = Helper.Combine(Helper.ArrayOfFunction(i => UsedDevices.Select(d => d + i *NDevices).ToArray(), MainWindow.GlobalOptions.ProcessesPerDevice)).ToList();

                if (IsCanceled)
                {
                    return;
                }

                #region Create worker processes

                WorkerWrapper[] Workers = new WorkerWrapper[GPU.GetDeviceCount() * MainWindow.GlobalOptions.ProcessesPerDevice];
                foreach (var gpuID in UsedDeviceProcesses)
                {
                    Workers[gpuID] = new WorkerWrapper(gpuID);
                    Workers[gpuID].SetHeaderlessParams(new int2(Options.Import.HeaderlessWidth, Options.Import.HeaderlessHeight),
                                                       Options.Import.HeaderlessOffset,
                                                       Options.Import.HeaderlessType);

                    if (!string.IsNullOrEmpty(Options.Import.GainPath) && Options.Import.CorrectGain)
                    {
                        Workers[gpuID].LoadGainRef(Options.Import.CorrectGain ? Options.Import.GainPath : "",
                                                   Options.Import.GainFlipX,
                                                   Options.Import.GainFlipY,
                                                   Options.Import.GainTranspose,
                                                   Options.Import.CorrectDefects ? Options.Import.DefectsPath : "");
                    }
                }

                #endregion

                #region Load gain reference if needed

                //Image[] ImageGain = new Image[NDevices];
                //if (!string.IsNullOrEmpty(Options.Import.GainPath) && Options.Import.CorrectGain && File.Exists(Options.Import.GainPath))
                //    for (int d = 0; d < NDevices; d++)
                //    {
                //        GPU.SetDevice(d);
                //        ImageGain[d] = MainWindow.LoadAndPrepareGainReference();
                //    }

                #endregion

                bool Overwrite = true;
                if (DoAverage || DoStack)
                {
                    foreach (var movie in ValidMovies)
                    {
                        bool FileExists = File.Exists((DoAverage ? movie.ParticlesDir : movie.ParticleMoviesDir) + movie.RootName + Options.Tasks.OutputSuffix + ".mrcs");
                        if (FileExists)
                        {
                            await Dispatcher.Invoke(async() =>
                            {
                                var DialogResult = await((MainWindow)Application.Current.MainWindow).ShowMessageAsync("Some particle files already exist. Overwrite them?",
                                                                                                                      "",
                                                                                                                      MessageDialogStyle.AffirmativeAndNegative,
                                                                                                                      new MetroDialogSettings()
                                {
                                    AffirmativeButtonText = "Yes",
                                    NegativeButtonText    = "No"
                                });
                                if (DialogResult == MessageDialogResult.Negative)
                                {
                                    Overwrite = false;
                                }
                            });
                            break;
                        }
                    }
                }

                Star TableOut = null;
                {
                    Dictionary <string, Star> MicrographTables = new Dictionary <string, Star>();

                    #region Get coordinates

                    float[] PosX   = TableIn.GetColumn("rlnCoordinateX").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                    float[] PosY   = TableIn.GetColumn("rlnCoordinateY").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                    float[] ShiftX = TableIn.HasColumn("rlnOriginX") ? TableIn.GetColumn("rlnOriginX").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    float[] ShiftY = TableIn.HasColumn("rlnOriginY") ? TableIn.GetColumn("rlnOriginY").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    for (int r = 0; r < TableIn.RowCount; r++)
                    {
                        PosX[r] -= ShiftX[r];
                        PosY[r] -= ShiftY[r];
                    }

                    if (TableIn.HasColumn("rlnOriginX"))
                    {
                        TableIn.RemoveColumn("rlnOriginX");
                    }
                    if (TableIn.HasColumn("rlnOriginY"))
                    {
                        TableIn.RemoveColumn("rlnOriginY");
                    }

                    #endregion

                    Dispatcher.Invoke(() => ProgressWrite.MaxValue = ValidMovies.Count);

                    Helper.ForEachGPU(ValidMovies, (movie, gpuID) =>
                    {
                        if (IsCanceled)
                        {
                            return;
                        }

                        Stopwatch ItemTime = new Stopwatch();
                        ItemTime.Start();

                        MapHeader OriginalHeader = MapHeader.ReadFromFile(movie.Path);

                        #region Set up export options

                        ProcessingOptionsParticlesExport ExportOptions = Options.GetProcessingParticleExport();
                        ExportOptions.DoAverage        = DoAverage;
                        ExportOptions.DoDenoisingPairs = DoDenoisingPairs;
                        ExportOptions.DoStack          = DoStack;
                        ExportOptions.Invert           = Invert;
                        ExportOptions.Normalize        = Normalize;
                        ExportOptions.PreflipPhases    = Preflip;
                        ExportOptions.Dimensions       = OriginalHeader.Dimensions.MultXY((float)Options.PixelSizeMean);
                        ExportOptions.BoxSize          = BoxSize;
                        ExportOptions.Diameter         = NormDiameter;

                        #endregion

                        bool FileExists = File.Exists((DoAverage ? movie.ParticlesDir : movie.ParticleMoviesDir) + movie.RootName + ExportOptions.Suffix + ".mrcs");

                        #region Load and prepare original movie

                        //Image OriginalStack = null;
                        decimal ScaleFactor = 1M / (decimal)Math.Pow(2, (double)ExportOptions.BinTimes);

                        if (!DoOnlyStar && (!FileExists || Overwrite))
                        {
                            Workers[gpuID].LoadStack(movie.Path, ScaleFactor, ExportOptions.EERGroupFrames);
                        }
                        //MainWindow.LoadAndPrepareHeaderAndMap(movie.Path, ImageGain[gpuID], ScaleFactor, out OriginalHeader, out OriginalStack);

                        if (IsCanceled)
                        {
                            //foreach (Image gain in ImageGain)
                            //    gain?.Dispose();
                            //OriginalStack?.Dispose();

                            return;
                        }

                        #endregion

                        #region Figure out relative or absolute path to particle stack

                        string PathStack      = (ExportOptions.DoStack ? movie.ParticleMoviesDir : movie.ParticlesDir) + movie.RootName + ExportOptions.Suffix + ".mrcs";
                        string PathMicrograph = movie.Path;
                        if (Relative)
                        {
                            Uri UriStar    = new Uri(ExportPath);
                            PathStack      = UriStar.MakeRelativeUri(new Uri(PathStack)).ToString();
                            PathMicrograph = UriStar.MakeRelativeUri(new Uri(PathMicrograph)).ToString();
                        }

                        #endregion

                        #region Update row values

                        List <int> GroupRows    = Groups[movie.RootName];
                        List <float2> Positions = new List <float2>();

                        float Astigmatism  = (float)movie.CTF.DefocusDelta / 2;
                        float PhaseShift   = movie.OptionsCTF.DoPhase ? movie.GridCTFPhase.GetInterpolated(new float3(0.5f)) * 180 : 0;
                        int ImageNameIndex = TableIn.GetColumnID("rlnImageName");

                        foreach (var r in GroupRows)
                        {
                            float3 Position = new float3(PosX[r] * AngPix / ExportOptions.Dimensions.X,
                                                         PosY[r] * AngPix / ExportOptions.Dimensions.Y,
                                                         0.5f);
                            float LocalDefocus = movie.GridCTFDefocus.GetInterpolated(Position);

                            TableIn.SetRowValue(r, "rlnDefocusU", ((LocalDefocus + Astigmatism) * 1e4f).ToString("F1", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnDefocusV", ((LocalDefocus - Astigmatism) * 1e4f).ToString("F1", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnDefocusAngle", movie.CTF.DefocusAngle.ToString("F1", CultureInfo.InvariantCulture));

                            TableIn.SetRowValue(r, "rlnVoltage", movie.CTF.Voltage.ToString("F1", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnSphericalAberration", movie.CTF.Cs.ToString("F4", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnAmplitudeContrast", movie.CTF.Amplitude.ToString("F3", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnPhaseShift", PhaseShift.ToString("F1", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnCtfMaxResolution", movie.CTFResolutionEstimate.ToString("F1", CultureInfo.InvariantCulture));

                            TableIn.SetRowValue(r, "rlnCoordinateX", (PosX[r] * AngPix / (float)ExportOptions.BinnedPixelSizeMean).ToString("F2", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnCoordinateY", (PosY[r] * AngPix / (float)ExportOptions.BinnedPixelSizeMean).ToString("F2", CultureInfo.InvariantCulture));

                            TableIn.SetRowValue(r, "rlnImageName", PathStack);

                            TableIn.SetRowValue(r, "rlnMicrographName", PathMicrograph);

                            Positions.Add(new float2(PosX[r] * AngPix,
                                                     PosY[r] * AngPix));
                        }

                        #endregion

                        #region Populate micrograph table with rows for all exported particles

                        Star MicrographTable = new Star(TableIn.GetColumnNames());

                        int StackDepth = (ExportOptions.DoAverage || ExportOptions.DoDenoisingPairs || DoOnlyStar)
                                             ? 1
                                             : (OriginalHeader.Dimensions.Z - ExportOptions.SkipFirstN - ExportOptions.SkipLastN) /
                                         ExportOptions.StackGroupSize;

                        int pi = 0;
                        for (int i = 0; i < StackDepth; i++)
                        {
                            foreach (var r in GroupRows)
                            {
                                List <string> Row   = TableIn.GetRow(r).ToList();
                                Row[ImageNameIndex] = (++pi).ToString("D7") + "@" + Row[ImageNameIndex];
                                MicrographTable.AddRow(Row);
                            }
                        }

                        #endregion

                        #region Finally, process and export the actual particles

                        if (!DoOnlyStar && (!FileExists || Overwrite))
                        {
                            Workers[gpuID].MovieExportParticles(movie.Path, ExportOptions, Positions.ToArray());
                            //movie.ExportParticles(OriginalStack, Positions.ToArray(), ExportOptions);
                            //OriginalStack.Dispose();
                        }

                        #endregion

                        #region Add this micrograph's table to global collection, update remaining time estimate

                        lock (MicrographTables)
                        {
                            MicrographTables.Add(movie.RootName, MicrographTable);

                            Timings.Add(ItemTime.ElapsedMilliseconds / (float)NDevices);

                            int MsRemaining        = (int)(MathHelper.Mean(Timings) * (ValidMovies.Count - MicrographTables.Count));
                            TimeSpan SpanRemaining = new TimeSpan(0, 0, 0, 0, MsRemaining);

                            Dispatcher.Invoke(() => TextRemaining.Text = SpanRemaining.ToString((int)SpanRemaining.TotalHours > 0 ? @"hh\:mm\:ss" : @"mm\:ss"));

                            Dispatcher.Invoke(() =>
                            {
                                ProgressWrite.IsIndeterminate = false;
                                ProgressWrite.Value           = MicrographTables.Count;
                            });
                        }

                        #endregion
                    }, 1, UsedDeviceProcesses);

                    if (MicrographTables.Count > 0)
                    {
                        TableOut = new Star(MicrographTables.Values.ToArray());
                    }
                }

                Thread.Sleep(10000);    // Writing out particle stacks is async, so if workers are killed immediately they may not write out everything

                foreach (var worker in Workers)
                {
                    worker?.Dispose();
                }

                //foreach (Image gain in ImageGain)
                //    gain?.Dispose();

                if (IsCanceled)
                {
                    return;
                }

                TableOut.Save(ExportPath);
            });

            DataContext = null;
            Close?.Invoke();
        }
Пример #50
0
        public static string BrowseForFileSave(
            IntPtr owner,
            string filter,
            string initialPath = null,
            string title       = null
            )
        {
            if (string.IsNullOrEmpty(initialPath))
            {
                initialPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar;
            }

            IVsUIShell uiShell = 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);
                    if (!string.IsNullOrEmpty(title))
                    {
                        sfd.Title = title;
                    }
                    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].pwzDlgTitle  = title;
            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);
                }
            }
        }
Пример #51
0
        public override void exp(Model objekt, DatabaseAdapter db, bool savetofile)
        {
            if (objekt == null || ((Projekt)objekt).getProjektID() <= 0)
            {
                throw new Exception("ID darf bei delete nicht  <= 0 sein");
            }
            if (objekt.GetType().Name == "Projekt")
            {
                Projekt temp_objekt = (Projekt)objekt;
                if (get(temp_objekt).Count == 0)
                {
                    ExecuteSQL("INSERT INTO Projekt (ProjektID, Bezeichnung) VALUES ( " + temp_objekt.getProjektID() + ", '" + temp_objekt.getBezeichnung() + "');");
                }
                Nutzwert        tempnutz_obj  = new Nutzwert(ProjektID: temp_objekt.getProjektID(), KriteriumID: -1, ProduktID: -1);
                List <Nutzwert> tempnutz_list = db.get(tempnutz_obj);
                foreach (Nutzwert nutz_obj in tempnutz_list)
                {
                    if (get(nutz_obj).Count == 0)
                    {
                        ExecuteSQL("INSERT INTO NWA (KriteriumID, ProjektID, ProduktID, Erfuellung, Gewichtung, Kommentar, beitrag_absolut, beitrag_absolut_check, abstufung) VALUES ( " + nutz_obj.getKriteriumID() + ", " + nutz_obj.getProjektID() + " , " + nutz_obj.getProduktID() + ", " + nutz_obj.getErfuellung() + ", " + nutz_obj.getGewichtung() + ", '" + nutz_obj.getKommentar() + "', " + nutz_obj.getBeitragAbsolut().ToString().Replace(",", ".") + ", " + nutz_obj.getBeitragAbsolutCheck() + ", " + nutz_obj.getAbstufung().ToString().Replace(",", ".") + ");");
                    }
                    Produkt        tempprod_obj  = new Produkt(nutz_obj.getProduktID());
                    List <Produkt> tempprod_list = db.get(tempprod_obj);
                    foreach (Produkt prod_obj in tempprod_list)
                    {
                        if (get(prod_obj).Count == 0)
                        {
                            ExecuteSQL("INSERT INTO Produkt (ProduktID, Bezeichnung) VALUES ( " + prod_obj.getProduktID() + ", '" + prod_obj.getBezeichnung() + "');");
                        }
                    }

                    Kriterium        tempkrit_obj  = new Kriterium(nutz_obj.getKriteriumID());
                    List <Kriterium> tempkrit_list = db.get(tempkrit_obj);
                    foreach (Kriterium krit_obj in tempkrit_list)
                    {
                        if (get(krit_obj).Count == 0)
                        {
                            ExecuteSQL("INSERT INTO Kriterium (KriteriumID, Bezeichnung) VALUES ( " + krit_obj.getKriteriumID() + ", '" + krit_obj.getBezeichnung() + "');");
                        }
                        Kriteriumstruktur        tempkritstrk_obj  = new Kriteriumstruktur(krit_obj.getKriteriumID());
                        List <Kriteriumstruktur> tempkritstrk_list = db.get(tempkritstrk_obj);
                        foreach (Kriteriumstruktur kritstrk_obj in tempkritstrk_list)
                        {
                            if (get(kritstrk_obj).Count == 0)
                            {
                                ExecuteSQL("INSERT INTO Kriteriumstruktur (OberKriteriumID, UnterKriteriumID) VALUES ( " + kritstrk_obj.getOberKriteriumID() + ", '" + kritstrk_obj.getUnterKriteriumID() + "');");
                            }
                        }
                    }
                }


                if (savetofile)
                {
                    System.Windows.Forms.SaveFileDialog openFileDialog1 = new System.Windows.Forms.SaveFileDialog();

                    // OK button was pressed.
                    string file = "";
                    openFileDialog1.Filter = "SQL file|*.sql";
                    openFileDialog1.Title  = "Save an sql File";
                    while (file == "")
                    {
                        openFileDialog1.ShowDialog();
                        file = openFileDialog1.FileName;
                    }

                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        using (MySqlBackup mb = new MySqlBackup(cmd))
                        {
                            cmd.Connection = conn;
                            conn.Open();
                            mb.ExportToFile(file);
                            conn.Close();
                        }
                    }
                }
            }
            else
            {
                throw new NotImplementedException();
            }
        }
        private void _export_Click(object sender, RoutedEventArgs e)
        {
            if (exporttable != null)
            {
                if (exporttable.Rows.Count == 0)
                {
                    Toolkit.MessageBox.Show("导出内容为空,请确认!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                //打开对话框
                System.Windows.Forms.SaveFileDialog saveFile = new System.Windows.Forms.SaveFileDialog();
                saveFile.Filter           = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
                saveFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                {
                    return;
                }
                var excelFilePath = saveFile.FileName;
                if (excelFilePath != "")
                {
                    if (System.IO.File.Exists(excelFilePath))
                    {
                        try
                        {
                            System.IO.File.Delete(excelFilePath);
                        }
                        catch (Exception ex)
                        {
                            Toolkit.MessageBox.Show("导出文件时出错,文件可能正被打开!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                            return;
                        }
                    }

                    try
                    {
                        //创建Excel
                        Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();

                        if (excelApp == null)
                        {
                            Toolkit.MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel程序!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                            return;
                        }
                        Workbook  excelWB = excelApp.Workbooks.Add(System.Type.Missing); //创建工作簿(WorkBook:即Excel文件主体本身)
                        Worksheet excelWS = (Worksheet)excelWB.Worksheets[1];            //创建工作表(即Excel里的子表sheet) 1表示在子表sheet1里进行数据导出
                        excelWS.Name = "货主信息";

                        //excelWS.Cells.NumberFormat = "@";     //  如果数据中存在数字类型 可以让它变文本格式显示
                        //导出列名
                        excelWS.Cells[1, 1] = "货主代码";
                        excelWS.Cells[1, 2] = "货主";
                        excelWS.Cells[1, 3] = "电话";
                        excelWS.Cells[1, 4] = "地址";

                        //将数据导入到工作表的单元格
                        for (int i = 0; i < exporttable.Rows.Count; i++)
                        {
                            for (int j = 0; j < exporttable.Columns.Count; j++)
                            {
                                excelWS.Cells[i + 2, j + 1] = exporttable.Rows[i][j].ToString();
                            }
                        }

                        Range range = null;
                        range                     = excelWS.get_Range(excelWS.Cells[1, 1], excelWS.Cells[exporttable.Rows.Count + 1, 4]); //设置表格左上角开始显示的位置
                        range.ColumnWidth         = 15;                                                                                   //设置单元格的宽度
                        range.RowHeight           = 22;                                                                                   //设置单元格的高度
                        range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                        excelWB.SaveAs(excelFilePath);  //将其进行保存到指定的路径
                        excelWB.Close();
                        excelApp.Quit();
                        KillAllExcel(excelApp); //释放可能还没释放的进程
                        Toolkit.MessageBox.Show("文件导出成功!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    catch
                    {
                        Toolkit.MessageBox.Show("无法创建Excel对象,可能您的机子Office版本有问题!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }
            }
        }
Пример #53
0
        public void ExportModel()
        {
            string defaultex;

            switch (COL.Model.GetModelFormat())
            {
            case ModelFormat.Chunk:
                defaultex = ".sa2mdl";
                break;

            case ModelFormat.GC:
                defaultex = ".sa2bmdl";
                break;

            case ModelFormat.Basic:
            case ModelFormat.BasicDX:
            default:
                defaultex = ".sa1mdl";
                break;
            }

            using (System.Windows.Forms.SaveFileDialog a = new System.Windows.Forms.SaveFileDialog
            {
                DefaultExt = "dae",
                FileName = Name + defaultex,
                Filter = "SAModel Files|*.sa?mdl|Collada|*.dae|Wavefront|*.obj"
            })
            {
                if (a.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string ftype = "collada";
                    switch (System.IO.Path.GetExtension(a.FileName).ToLowerInvariant())
                    {
                    case ".sa1mdl":
                    case ".sa2mdl":
                    case ".sa2bmdl":
                        ModelFile.CreateFile(a.FileName, COL.Model, null, null, null, null, COL.Model.GetModelFormat());
                        return;

                    case ".fbx":
                        ftype = "fbx";
                        break;

                    case ".obj":
                        ftype = "obj";
                        break;
                    }
                    Assimp.AssimpContext context = new Assimp.AssimpContext();
                    Assimp.Scene         scene   = new Assimp.Scene();
                    scene.Materials.Add(new Assimp.Material());
                    Assimp.Node n = new Assimp.Node();
                    n.Name         = "RootNode";
                    scene.RootNode = n;
                    string        rootPath     = System.IO.Path.GetDirectoryName(a.FileName);
                    List <string> texturePaths = new List <string>();
                    int           numSteps     = 0;
                    if (LevelData.TextureBitmaps != null && LevelData.TextureBitmaps.Count > 0)
                    {
                        numSteps = LevelData.TextureBitmaps[LevelData.leveltexs].Length;
                    }
                    for (int i = 0; i < numSteps; i++)
                    {
                        BMPInfo bmp = LevelData.TextureBitmaps[LevelData.leveltexs][i];
                        texturePaths.Add(System.IO.Path.Combine(rootPath, bmp.Name + ".png"));
                        bmp.Image.Save(System.IO.Path.Combine(rootPath, bmp.Name + ".png"));
                    }
                    SAEditorCommon.Import.AssimpStuff.AssimpExport(COL.Model, scene, Matrix.Identity, texturePaths.Count > 0 ? texturePaths.ToArray() : null, scene.RootNode);
                    context.ExportFile(scene, a.FileName, ftype, Assimp.PostProcessSteps.ValidateDataStructure | Assimp.PostProcessSteps.Triangulate | Assimp.PostProcessSteps.FlipUVs);                    //
                }
            }
        }
Пример #54
0
        /// 생성자
        public ShpPsViewModel()
        {
            ItemsSelect = new ObservableCollection <FileDtl>();
            ItemsFile   = new ObservableCollection <FileInfo>();



            // 초기로딩처리
            LoadedCommand = new RelayCommand <object>(delegate(object obj) {
                if (obj == null)
                {
                    return;
                }
                //그리드뷰인스턴스
                shpPsView = obj as ShpPsView;


                // 초기조회
                InitModel();
            });


            //shp파일 임포트
            ImportCmd = new RelayCommand <object>(delegate(object obj) {
                //필수체크
                if (!BizUtil.ValidReq(shpPsView))
                {
                    return;
                }

                OpenFileDialog openFileDialog   = new OpenFileDialog();
                openFileDialog.Multiselect      = true;
                openFileDialog.Filter           = "Shape files |*.shp;*.dbf";
                openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                if (openFileDialog.ShowDialog() == true)
                {
                    FileInfo[] files = openFileDialog.FileNames.Select(f => new FileInfo(f)).ToArray();  //파일인포

                    foreach (FileInfo fi in files)
                    {
                        try
                        {
                            //파일객체
                            ItemsFile.Add(fi);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }

                    //파일업로드시작
                    upload_thread = new Thread(new ThreadStart(UploadFileListFX));
                    upload_thread.Start();
                }
            });



            //기존파일 다운로드버튼 이벤트
            DownloadCmd = new RelayCommand <object>(delegate(object obj)
            {
                FileDtl dtl      = obj as FileDtl;
                string file_name = dtl.DWN_NAM;

                try
                {
                    source_file_path = BizUtil.GetDataFolder("shape", file_name);
                }
                catch (Exception)
                {
                    Messages.ShowErrMsgBox("다운로드할 수 없습니다.");
                    return;
                }


                //파일다운로드
                saveFileDialog       = new System.Windows.Forms.SaveFileDialog();
                saveFileDialog.Title = "저장경로를 지정하세요.";
                //초기 파일명 지정
                saveFileDialog.FileName        = file_name;
                saveFileDialog.OverwritePrompt = true;
                saveFileDialog.Filter          = "All files (*.*)|*.*";

                if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    target_file_path = saveFileDialog.FileName;
                    download_thread  = new Thread(new ThreadStart(DownloadFX));
                    download_thread.Start();
                }
            });
        }
Пример #55
0
        /// <summary>
        /// Saves Revit model parameters to text file
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            // NOTES: Anything can be done in this method, such as create a message box,
            // a task dialog or fetch some information from revit and so on.
            // We mainly use the task dialog for example.

            // Get the application and document from external command data.
            Application app    = commandData.Application.Application;
            Document    curDoc = commandData.Application.ActiveUIDocument.Document;

            //for text file
            List <string> lines = new List <string>();

            //loads from settings.txt
            settings.LoadSettings();

            //get document handle

            lines.Add("Document Title: " + curDoc.Title);
            lines.Add("Project Information UniqueID: " + curDoc.ProjectInformation.UniqueId.ToString());
            lines.Add(" ");
            lines.Add("Family Instances:");


            //filter for family instances
            FilteredElementCollector famCol = new FilteredElementCollector(curDoc);

            famCol.OfClass(typeof(FamilyInstance));
            IList <Element> famElems = famCol.ToElements();

            //iterate
            foreach (Element myE in famElems)
            {
                lines.Add("Element ID:	"+ myE.Id.ToString() + "	.	"+ "Element Name:	"+ myE.Name);

                FamilyInstance myFamInst = myE as FamilyInstance;
                lines.Add("Family Symbol: " + myFamInst.Symbol.Name);
                foreach (Parameter myParam in myE.Parameters)
                {
                    if (myParam.StorageType == StorageType.String)
                    {
                        lines.Add("	Param ID:	"+ myParam.Id.IntegerValue.ToString() + "	,	Param name:	"+ myParam.Definition.Name + "	:	Param value:	"+ myParam.AsString());
                    }
                    else
                    {
                        lines.Add("	Param ID:	"+ myParam.Id.IntegerValue.ToString() + "	,	Param name:	"+ myParam.Definition.Name + "	:	Param value:	"+ myParam.AsValueString());
                    }
                }
            }
            lines.Add(" ");
            lines.Add("Families:");
            ElementClassFilter       FamilyFilter    = new ElementClassFilter(typeof(Family));
            FilteredElementCollector FamilyCollector = new FilteredElementCollector(curDoc);
            ICollection <Element>    AllFamilies     = FamilyCollector.WherePasses(FamilyFilter).ToElements();

            foreach (Family Fmly in AllFamilies)
            {
                string FamilyName = Fmly.Name;

                lines.Add("Family ID:	"+ Fmly.Id.ToString() + "	,	Family name:	"+ FamilyName);
                foreach (Parameter myParam in Fmly.Parameters)
                {
                    lines.Add("	Param ID:	"+ myParam.Id.IntegerValue.ToString() + "	,	Param name:	"+ myParam.Definition.Name + "	:	Param value:	"+ myParam.AsValueString());
                }

                lines.Add("Family Symbols:");

                foreach (ElementId symid in Fmly.GetFamilySymbolIds())
                {
                    FamilySymbol FmlyS = curDoc.GetElement(symid) as FamilySymbol;



                    lines.Add(" Family Symbol ID:	"+ FmlyS.Id.ToString() + "	,	Family Symbol name:	"+ FmlyS.Name);

                    foreach (Parameter myParam in FmlyS.Parameters)
                    {
                        if (myParam.StorageType == StorageType.String)
                        {
                            lines.Add("	Param ID:	"+ myParam.Id.IntegerValue.ToString() + "	,	Param name:	"+ myParam.Definition.Name + "	:	Param value:	"+ myParam.AsString());
                        }
                        else
                        {
                            lines.Add("	Param ID:	"+ myParam.Id.IntegerValue.ToString() + "	,	Param name:	"+ myParam.Definition.Name + "	:	Param value:	"+ myParam.AsValueString());
                        }
                    }
                }
            }

            System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog1.Filter = "Text file|*.txt";
            saveFileDialog1.Title  = "Save model parameters";
            saveFileDialog1.ShowDialog();

            // If the file name is not an empty string open it for saving.
            if (saveFileDialog1.FileName != "")
            {
                System.IO.File.WriteAllLines(saveFileDialog1.FileName, lines.ToArray());
            }
            return(Autodesk.Revit.UI.Result.Succeeded);
        }
Пример #56
0
        public override void Update(GameTime gameTime, Game1 game)
        {
            if (MapEditor.bIsRunning)
            {
                #region firstrun
                if (firstRun)
                {
                    mapXSizeInput = new ActiveInput("X-Size map: ", "0", Vector2.Zero, game);
                    mapYSizeInput = new ActiveInput("Y-Size map: ", "0", Vector2.Zero, game);
                    mapNameInput  = new ActiveInput("Map name: ", "Map", Vector2.Zero, game);
                    mapXSizeInput.bNumericInputOnly = true;
                    mapYSizeInput.bNumericInputOnly = true;
                    activeInputButtons.Add(mapXSizeInput);
                    activeInputButtons.Add(mapYSizeInput);
                    activeInputButtons.Add(mapNameInput);
                    mapXSizeInput.bHasMinValue = true;
                    mapXSizeInput.minValue     = 1;
                    mapYSizeInput.bHasMinValue = true;
                    mapYSizeInput.minValue     = 1;

                    firstRun = false;

                    localScenes.Add(mapBuilder);
                }
                #endregion

                if (Game1.bIsDebug)
                {
                    openMap.Filter           = "CGMAPC Files (.cgmapc)|*.cgmapc";
                    openMap.InitialDirectory = Game1.rootTBAGW;
                }
                else
                {
                    openMap.Filter           = "CGMAP Files (.cgmap)|*.cgmap";
                    openMap.InitialDirectory = Game1.rootContentExtra;
                }
                openMap.FilterIndex = 1;
                openMap.Multiselect = false;
                saveMap.Filter      = "CGMAP Files (.cgmap)|*.cgmap";
                saveMap.Title       = "Save a CGMAP File";
                if (Game1.bIsDebug)
                {
                    saveMap.InitialDirectory = Game1.rootTBAGW;
                }
                else
                {
                    saveMap.InitialDirectory = Game1.rootContentExtra;
                }

                bool usingActiveInput = false;

                Vector2 EditorCursorPos = Mouse.GetState().Position.ToVector2() + new Vector2(cameraPosX, -cameraPosY);
                loadMapButton.Update(gameTime);
                if (loadMapButton.buttonBox.Contains(EditorCursorPos))
                {
                    if (Mouse.GetState().LeftButton == ButtonState.Pressed && Game1.bIsActive && !KeyboardMouseUtility.AnyButtonsPressed())
                    {
                        System.Windows.Forms.DialogResult testDia = openMap.ShowDialog();

                        if (testDia == System.Windows.Forms.DialogResult.OK && openMap.FileName.Contains(openMap.InitialDirectory))
                        {
                            //  Console.WriteLine("You selected: " + openMap.FileName);
                            loadedMap = EditorFileWriter.MapReader(openMap.FileName);
                        }
                    }
                }

                #region MapEditor only logic

                foreach (var item in activeInputButtons)
                {
                    item.Update(gameTime);
                    item.Contains(EditorCursorPos);
                }

                foreach (var item in activeInputButtons)
                {
                    if (item.bEnableInput)
                    {
                        usingActiveInput = true;
                        break;
                    }
                }

                int i = 0;
                foreach (var item in activeInputButtons)
                {
                    item.position = new Vector2(100, 200 + 75 * i);
                    i++;
                }

                CreateMapButton.position = new Vector2(activeInputButtons[activeInputButtons.Count - 1].position.X, activeInputButtons[activeInputButtons.Count - 1].position.Y + 75);

                CreateMapButton.Update(gameTime);
                if (CreateMapButton.ButtonBox().Contains(EditorCursorPos) && Mouse.GetState().LeftButton == ButtonState.Pressed && !KeyboardMouseUtility.AnyButtonsPressed())
                {
                    bool bCorrectSave = false;
                    while (!bCorrectSave)
                    {
                        try
                        {
                            if (Game1.bIsDebug)
                            {
                                BasicMap newMap = new BasicMap();
                                newMap.mapName           = mapNameInput.ReturnInputString();
                                saveMap.InitialDirectory = Game1.rootTBAGW;
                                System.Windows.Forms.DialogResult dia = saveMap.ShowDialog();
                                if (saveMap.FileName != "" && dia == System.Windows.Forms.DialogResult.OK && saveMap.FileName.StartsWith(saveMap.InitialDirectory))
                                {
                                    newMap.mapName = Path.GetFileNameWithoutExtension(saveMap.FileName);
                                    mapNameInput.AssignInput(Path.GetFileNameWithoutExtension(saveMap.FileName));
                                    //  Console.WriteLine("Line= " + Path.GetDirectoryName(saveMap.FileName));
                                    EditorFileWriter.MapWriter(saveMap.FileName, newMap);
                                    Console.WriteLine(newMap.mapLocation);
                                    loadedMap    = EditorFileWriter.MapReader(saveMap.FileName);;
                                    bCorrectSave = true;
                                }
                                else if (dia == System.Windows.Forms.DialogResult.Cancel)
                                {
                                    bCorrectSave = true;
                                }
                                else
                                {
                                    //  Console.WriteLine("Yow");
                                    System.Windows.Forms.MessageBox.Show("Make sure you save the map within the application folder.");
                                }
                            }
                            else
                            {
                                BasicMap newMap = new BasicMap();
                                newMap.mapName           = mapNameInput.ReturnInputString();
                                saveMap.InitialDirectory = Game1.rootContentExtra;
                                System.Windows.Forms.DialogResult dia = saveMap.ShowDialog();
                                if (saveMap.FileName != "" && dia == System.Windows.Forms.DialogResult.OK && saveMap.FileName.StartsWith(Game1.rootContentExtra))
                                {
                                    newMap.mapName = Path.GetFileNameWithoutExtension(saveMap.FileName);
                                    mapNameInput.AssignInput(Path.GetFileNameWithoutExtension(saveMap.FileName));
                                    //  Console.WriteLine("Line= " + Path.GetDirectoryName(saveMap.FileName));
                                    EditorFileWriter.MapWriter(saveMap.FileName, newMap);
                                    Console.WriteLine(newMap.mapLocation);
                                    loadedMap    = EditorFileWriter.MapReader(saveMap.FileName);;
                                    bCorrectSave = true;
                                }
                                else if (dia == System.Windows.Forms.DialogResult.Cancel)
                                {
                                    bCorrectSave = true;
                                }
                                else
                                {
                                    //  Console.WriteLine("Yow");
                                    System.Windows.Forms.MessageBox.Show("Make sure you save the map within the application folder.");
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Console.Out.WriteLine("Error:\n" + e);
                        }
                    }
                }

                if (currentScene == 0 && !usingActiveInput)
                {
                    if (Keyboard.GetState().IsKeyDown(Keys.S))
                    {
                        cameraPosY -= cameraSpeed;
                    }

                    if (Keyboard.GetState().IsKeyDown(Keys.Z))
                    {
                        cameraPosY += cameraSpeed;
                    }

                    if (Keyboard.GetState().IsKeyDown(Keys.Q))
                    {
                        cameraPosX -= cameraSpeed;
                    }

                    if (Keyboard.GetState().IsKeyDown(Keys.D))
                    {
                        cameraPosX += cameraSpeed;
                    }
                }
                #endregion

                if (loadedMap != default(BasicMap))
                {
                    currentScene     = (int)MapEditor.MapEditorScenes.MapBuilder;
                    bRerunFileLoader = true;
                    mapBuilder.Start(game, loadedMap);
                    loadedMap  = default(BasicMap);
                    bIsRunning = false;
                }



                if (Mouse.GetState().RightButton == ButtonState.Pressed && !KeyboardMouseUtility.AnyButtonsPressed() && currentScene > 0)
                {
                    switch (currentScene)
                    {
                    case (int)MapEditorScenes.MapEditor:
                        System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.MessageBox.Show("You sure want to exit Map editing? NOTE: be sure to save first!", "Leaving", System.Windows.Forms.MessageBoxButtons.YesNo);
                        if (dialogResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            currentScene--;
                        }
                        else if (dialogResult == System.Windows.Forms.DialogResult.No)
                        {
                            //do something else
                        }

                        break;
                    }
                }
            }
            else if (!MapEditor.bIsRunning)
            {
                mapBuilder.Update(gameTime, game);
            }

            MapEditorMatrix = Matrix.CreateTranslation(-cameraPosX, cameraPosY, 1);
        }
Пример #57
0
        private void bt_save_curve_data_Click(object sender, RoutedEventArgs e)         //保存曲线数据
        {
            var ofd = new System.Windows.Forms.SaveFileDialog();

            ofd.Filter = "*.csv|*.csv";
            if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            StreamWriter sw = new StreamWriter(ofd.FileName);

            //由于x轴一定是整数,所以按x轴作为索引。取得曲线的x轴极值坐标
            fit_screen_data();
            Int64 i = 0;
            //遍历所有曲线的标题,写入文件,按标题来取值
            string s     = "";
            var    cv_id = new List <int>();         //参与输出的曲线的名称,按顺序

            for (int j = 0; j < chart1.Series.Count; j++)
            {
                if (chart1.Series[j].Points.Count > 0)              //若此曲线有点
                {
                    cv_id.Add(j);
                    s += chart1.Series[j].Name + ",";
                }
            }
            if (cv_id.Count == 0)
            {
                return;
            }
            s = s.Substring(0, s.Length - 1);
            sw.WriteLine(s);
            var mi = new int[cv_id.Count];                   //各曲线的索引

            for (i = (Int64)curv_x_min; i < curv_x_max; i++) //i为横坐标值
            {
                s = "";
                int flag = 0;
                for (int j = 0; j < cv_id.Count; j++)           //遍历所有曲线
                {
                    var ser = chart1.Series[cv_id[j]];
                    for (; mi[j] < ser.Points.Count; mi[j]++)
                    {
                        int cur_x_val = (int)(ser.Points[mi[j]].XValue);
                        if (cur_x_val > i)
                        {
                            break;                                        //若还没到,就过
                        }
                        if (cur_x_val == i)
                        {
                            s   += string.Format("{0}", ser.Points[mi[j]].YValues[0]);
                            flag = 1;
                            break;
                        }
                    }
                    s += ",";                     //每个曲线加一个逗号
                }
                if (flag == 0)
                {
                    continue;
                }
                s = s.Substring(0, s.Length - 1);
                sw.WriteLine(s);
            }
            sw.Close();
        }
Пример #58
0
        /// <summary>
        /// 导出lst
        /// </summary>
        private void itmLst_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog()
                {
                    DefaultExt      = "lst",
                    FileName        = "MoeLoaderList.lst",
                    Filter          = "lst文件|*.lst",
                    OverwritePrompt = false
                };
                if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string text = "";
                    int    success = 0, repeat = 0;
                    //读存在的lst内容
                    string[] flst     = null;
                    bool     havelst  = File.Exists(saveFileDialog1.FileName);
                    bool     isexists = false;

                    if (havelst)
                    {
                        flst = File.ReadAllLines(saveFileDialog1.FileName);
                    }

                    foreach (DownloadItem i in dlList.SelectedItems)
                    {
                        //查找重复项
                        try
                        {
                            isexists = havelst && flst.Any(x => x.Split('|')[2] == i.Host && x.Split('|')[4] == i.Id.ToSafeString());
                        }
                        catch { }

                        if (!isexists)
                        {
                            //url|文件名|域名|上传者|ID(用于判断重复)|免文件校验
                            text += i.Url
                                    + "|" + i.LocalFileName
                                    + "|" + i.Host
                                    + "|" + i.Author
                                    + "|" + i.Id
                                    + "|" + (i.NoVerify ? 'v' : 'x')
                                    + "\r\n";
                            success++;
                        }
                        else
                        {
                            repeat++;
                        }
                    }
                    File.AppendAllText(saveFileDialog1.FileName, text);
                    MessageBox.Show("成功保存 " + success + " 个地址\r\n" + repeat + " 个地址已在列表中\r\n", MainWindow.ProgramName,
                                    MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存失败:\r\n" + ex.Message, MainWindow.ProgramName, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Пример #59
0
        /// <summary>
        /// 导出审批表word
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="Type">0-首营供货商,1-首营客户,2-首营药品</param>
        /// <returns></returns>
        public bool CreateWord(string Filename, string Name, int Type)
        {
            Word._Application oWord = new Word.Application();
            Word._Document    oDoc  = null;
            try
            {
                object oMissing = System.Reflection.Missing.Value;

                oWord.Visible = false;
                object oTemplate = Filename;
                oDoc = oWord.Documents.Open(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);
                oDoc.Activate();

                #region 这是首营信息们
                if (b != null)
                {
                    this.insertMarks(oDoc, 0);
                    this.insertGsp(oDoc, b.GSPLCID, b.id);
                    this.insertMedicineBussiness(oDoc, b.MedicineBusinessLCID);
                    this.insertBussiness(oDoc, b.BusinessLCID);
                    this.insertOrg(oDoc, b.OrganizationCodeLCID);
                    this.insertTax(oDoc, b.TaxRegisterLCID);
                    this.insertInstB(oDoc, b.InstrumentsBusinessLCID);
                    this.insertInstP(oDoc, b.InstrumentsProductionLCID);
                    this.insertHealth(oDoc, b.HealthLCID);
                    this.InsertGMP(oDoc, b.GMPLCID);
                    this.insertDelegate(oDoc);
                    this.insertSCXKZ(oDoc, b.MedicineProductionLCID);
                    this.insertQualityAgreement(oDoc);
                    this.insertBank(oDoc);

                    Service.Models.QueryApprovalFlowRecordModel aq = new Service.Models.QueryApprovalFlowRecordModel
                    {
                        FlowId = b.ApprovalFlowId
                    };

                    var c = baseform.PharmacyDatabaseService.SearchApprovalFlowRecordsByQueryModel(out msg, aq).OrderBy(r => r.ApproveTime).ToList();

                    if (oDoc.Bookmarks["flow1"] != null)
                    {
                        for (int i = 0; i < c.Count; i++)
                        {
                            oDoc.Bookmarks["flow" + (i + 1)].Select();
                            oDoc.Bookmarks["flow" + (i + 1)].Range.Text = c[i].Comment;
                            var o = ListUsers.Where(r => r.Id == c[i].ApproveUserId).FirstOrDefault();
                            oDoc.Bookmarks["flowuser" + (i + 1)].Range.Text = o.Employee.Name + "  " + c[i].ApproveTime.ToLongDateString();
                        }
                    }
                }

                if (p != null)
                {
                    this.insertPurchaseBasicInfo(oDoc);
                    this.insertGsp(oDoc, p.GSPLCID, p.Id);
                    this.insertMedicineBussiness(oDoc, p.MedicineBusinessLCID);
                    this.insertBussiness(oDoc, p.BusinessLCID);
                    this.insertOrg(oDoc, p.OrganizationCodeLCID);
                    this.insertTax(oDoc, p.TaxRegisterLCID);
                    this.insertInstB(oDoc, p.InstrumentsBusinessLCID);
                    this.insertInstP(oDoc, p.InstrumentsProductionLCID);
                    this.insertHealth(oDoc, p.HealthLCID);
                    this.InsertGMP(oDoc, p.GMPLCID);
                    this.insertLn(oDoc, p.LnstitutionLegalPersonLCID);
                    this.InsertMMInst(oDoc, p.MmedicalInstitutionLCID);
                    this.insertDelegate(oDoc);
                    this.insertQualityAgreement(oDoc);
                }

                if (d != null)
                {
                    this.InsertDrugInfo(oDoc);
                }

                #region 医疗器械信息
                if (Inst != null)
                {
                    oDoc.Bookmarks["T1"].Select();
                    oDoc.Bookmarks["T1"].Range.Text = BugsBox.Pharmacy.AppClient.Common.PharmacyClientConfig.Config.Store.Name;

                    oDoc.Bookmarks["D1"].Range.Text  = Inst.ProductGeneralName;
                    oDoc.Bookmarks["D2"].Range.Text  = Inst.LicensePermissionNumber;
                    oDoc.Bookmarks["D3"].Range.Text  = Inst.PerformanceStandards;
                    oDoc.Bookmarks["D4"].Range.Text  = Inst.StandardCode;
                    oDoc.Bookmarks["D5"].Range.Text  = Inst.Code;
                    oDoc.Bookmarks["D6"].Range.Text  = Inst.DocCode;
                    oDoc.Bookmarks["D7"].Range.Text  = Inst.Pinyin;
                    oDoc.Bookmarks["D8"].Range.Text  = Inst.BarCode;
                    oDoc.Bookmarks["D11"].Range.Text = Inst.DictionaryMeasurementUnitCode;
                    oDoc.Bookmarks["D12"].Range.Text = Inst.DictionaryDosageCode;
                    oDoc.Bookmarks["D13"].Range.Text = Inst.DictionarySpecificationCode;
                    oDoc.Bookmarks["D14"].Range.Text = Inst.FactoryName;
                    oDoc.Bookmarks["D15"].Range.Text = Inst.Contact;
                    oDoc.Bookmarks["D16"].Range.Text = Inst.BusinessScopeCode;
                    oDoc.Bookmarks["D17"].Range.Text = Inst.IsApproval;
                    oDoc.Bookmarks["D18"].Range.Text = Inst.Valid;
                    oDoc.Bookmarks["D19"].Range.Text = Inst.WareHouses;
                    oDoc.Bookmarks["D20"].Range.Text = Inst.WareHouseZone;
                    oDoc.Bookmarks["D21"].Range.Text = Inst.DrugStorageTypeCode;
                    oDoc.Bookmarks["D22"].Range.Text = Inst.MaxInventoryCount.ToString();
                    oDoc.Bookmarks["D23"].Range.Text = Inst.MinInventoryCount.ToString();
                    oDoc.Bookmarks["D24"].Range.Text = Inst.ValidPeriod.ToString() + "个月";
                    oDoc.Bookmarks["D25"].Range.Text = Inst.DrugCategoryCode;
                    oDoc.Bookmarks["D26"].Range.Text = Inst.Price.ToString();
                    oDoc.Bookmarks["D27"].Range.Text = Inst.SalePrice.ToString();
                    oDoc.Bookmarks["D28"].Range.Text = Inst.LimitedUpPrice.ToString();
                    oDoc.Bookmarks["D29"].Range.Text = Inst.LimitedLowPrice.ToString();
                    //oDoc.Bookmarks["D31"].Range.Text = Inst.Description;
                    oDoc.Bookmarks["D48"].Range.Text = Inst.CreateTime.ToString();
                    oDoc.Bookmarks["D49"].Range.Text = Inst.CreateUserName;
                }
                #endregion

                #region 保健食品信息
                if (this.Food != null)
                {
                    oDoc.Bookmarks["T1"].Select();
                    oDoc.Bookmarks["T1"].Range.Text = BugsBox.Pharmacy.AppClient.Common.PharmacyClientConfig.Config.Store.Name;

                    oDoc.Bookmarks["D1"].Range.Text  = Food.ProductGeneralName;
                    oDoc.Bookmarks["D2"].Range.Text  = Food.LicensePermissionNumber;
                    oDoc.Bookmarks["D3"].Range.Text  = Food.PerformanceStandards;
                    oDoc.Bookmarks["D4"].Range.Text  = Food.LicensePermissionOutValidDate.ToShortDateString();
                    oDoc.Bookmarks["D5"].Range.Text  = Food.Code;
                    oDoc.Bookmarks["D6"].Range.Text  = Food.DocCode;
                    oDoc.Bookmarks["D7"].Range.Text  = Food.Pinyin;
                    oDoc.Bookmarks["D8"].Range.Text  = Food.BarCode;
                    oDoc.Bookmarks["D11"].Range.Text = Food.DictionaryMeasurementUnitCode;
                    oDoc.Bookmarks["D12"].Range.Text = Food.DictionaryDosageCode;
                    oDoc.Bookmarks["D13"].Range.Text = Food.DictionarySpecificationCode;
                    oDoc.Bookmarks["D14"].Range.Text = Food.FactoryName;
                    oDoc.Bookmarks["D15"].Range.Text = Food.Contact;
                    oDoc.Bookmarks["D16"].Range.Text = Food.BusinessScopeCode;
                    oDoc.Bookmarks["D17"].Range.Text = Food.IsApproval;
                    oDoc.Bookmarks["D18"].Range.Text = Food.Valid;
                    oDoc.Bookmarks["D19"].Range.Text = Food.WareHouses;
                    oDoc.Bookmarks["D20"].Range.Text = Food.WareHouseZone;
                    oDoc.Bookmarks["D21"].Range.Text = Food.DrugStorageTypeCode;
                    oDoc.Bookmarks["D22"].Range.Text = Food.MaxInventoryCount.ToString();
                    oDoc.Bookmarks["D23"].Range.Text = Food.MinInventoryCount.ToString();
                    oDoc.Bookmarks["D24"].Range.Text = Food.ValidPeriod.ToString() + "个月";
                    oDoc.Bookmarks["D25"].Range.Text = Food.IsImport;



                    oDoc.Bookmarks["D26"].Range.Text = Food.Price.ToString();
                    oDoc.Bookmarks["D27"].Range.Text = Food.SalePrice.ToString();
                    oDoc.Bookmarks["D28"].Range.Text = Food.LimitedUpPrice.ToString();
                    oDoc.Bookmarks["D29"].Range.Text = Food.LimitedLowPrice.ToString();

                    oDoc.Bookmarks["D30"].Range.Text = Food.Origin;
                    oDoc.Bookmarks["D31"].Range.Text = Food.Description;

                    oDoc.Bookmarks["D48"].Range.Text = Food.CreateTime.ToString();
                    oDoc.Bookmarks["D49"].Range.Text = Food.CreateUserName;
                }

                #endregion

                #endregion

                #region word保存
                System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
                sfd.Filter     = "Word Document(*.doc)|*.doc";
                sfd.DefaultExt = "Word Document(*.doc)|*.doc";
                sfd.FileName   = Name + DateTime.Now.Ticks + ".doc";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    object filename = sfd.FileName;
                    oDoc.SaveAs(ref filename, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                ref oMissing, ref oMissing);
                    oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
                    if (oDoc != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
                        oDoc = null;
                    }
                    if (oWord != null)
                    {
                        oWord.Quit();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
                        oWord = null;
                    }
                    return(true);
                }
                else
                {
                    if (oDoc != null)
                    {
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
                        oDoc = null;
                    }
                    if (oWord != null)
                    {
                        oWord.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
                        oWord = null;
                    }
                    return(false);
                }
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(Name + ":审批信息表导出失败!");
                if (oWord != null)
                {
                    oWord.Quit(Word.WdSaveOptions.wdDoNotSaveChanges);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
                    oWord = null;
                }
                if (oDoc != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
                    oDoc = null;
                }
                return(false);
            }
            finally
            {
                if (oWord != null)
                {
                    oWord.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
                    oWord = null;
                }
                if (oDoc != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
                    oDoc = null;
                }
            }
            #endregion
        }
        public void ExportExcel()
        {
            if ((dt == null) || (dt.Rows.Count == 0))
            {
                Toolkit.MessageBox.Show("当前可导出数据为零!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
            sfd.Filter = "导出文件 (*.csv)|*.csv";
            //sfd.Filter = "Excel(*.xlsx)|*.xlsx|Excel(*.xls)|*.xls";
            sfd.FilterIndex      = 0;
            sfd.RestoreDirectory = true;
            sfd.Title            = "导出文件保存路径";
            sfd.ShowDialog();
            string strFilePath = sfd.FileName;

            if (strFilePath != "")
            {
                if (File.Exists(strFilePath))
                {
                    try
                    {
                        File.Delete(strFilePath);
                    }
                    catch (Exception ex)
                    {
                        Toolkit.MessageBox.Show("导出文件时出错,文件可能正被打开!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                }
                StreamWriter sw          = new StreamWriter(new FileStream(strFilePath, FileMode.CreateNew), Encoding.Default);
                string       tableHeader = " ";
                foreach (DataColumn c in dt.Columns)
                {
                    GridViewColumn gvc = new GridViewColumn();
                    tableHeader += c.ColumnName + ",";
                }
                sw.WriteLine(title);
                sw.WriteLine(tableHeader);

                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    DataRow       row = dt.Rows[j];
                    StringBuilder sb  = new StringBuilder();
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        sb.Append(row[i]);
                        sb.Append(",");
                    }
                    sw.WriteLine(sb);
                }

                //StringBuilder sum_sb = new StringBuilder();
                //for (int i = 0; i < dt.Columns.Count; i++)
                //{
                //    if (i == 0)
                //    {
                //        sum_sb.Append("共计");
                //    }
                //    else if (columnNumbers.Contains(i))
                //    {
                //        sum_sb.Append(sumColumns[columnNumbers.IndexOf(i)]);
                //    }
                //    sum_sb.Append(",");
                //}
                //sw.WriteLine(sum_sb);

                sw.Close();
                //MessageBox.Show("导出文件成功!", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                Toolkit.MessageBox.Show("导出文件成功!", "系统提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }