private void BrowseButtonOnClick(object sender, EventArgs eventArgs)
 {
     FolderBrowserDialog fbd = new FolderBrowserDialog();
     if (fbd.ShowDialog() == DialogResult.OK){
         textBox1.Text = fbd.SelectedPath;
     }
 }
		private void btnBrowseDir_Click(object sender, RoutedEventArgs e) {
			var dialog = new FolderBrowserDialog {
				Description = "Select the directory containing PCSX2"
			};
			if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
				tbPcsx2Dir.Text = dialog.SelectedPath;
		}
Example #3
1
 private void btnBrowser_Click(object sender, EventArgs e)
 {
     FolderBrowserDialog path = new FolderBrowserDialog();
     //path.RootFolder = Environment.SpecialFolder.;
     path.ShowDialog();
     txtFrom.Text = path.SelectedPath;
 }
Example #4
1
 private void btnChooseDir_Click(object sender, RoutedEventArgs e)
 {
     var dialog = new FolderBrowserDialog();
     dialog.ShowDialog();
     if (dialog.SelectedPath.IsNullOrEmpty()) return;
     MainData.Path = dialog.SelectedPath;
 }
Example #5
1
 private void button10_Click(object sender, EventArgs e)
 {
     FolderBrowserDialog dlg = new FolderBrowserDialog();
     dlg.SelectedPath = Application.StartupPath + "\\Output";
     dlg.ShowDialog();
     textBox8.Text = dlg.SelectedPath;
 }
 private void BtnExportAll_Click(object sender, System.EventArgs e)
 {
     using (FolderBrowserDialog browserDlg = new FolderBrowserDialog())
     {
         browserDlg.Description = "Export all files";
         if (browserDlg.ShowDialog() == DialogResult.OK)
         {
             foreach (OContainer.fileEntry file in container.content)
             {
                 string fileName = Path.Combine(browserDlg.SelectedPath, file.name);
                 string dir = Path.GetDirectoryName(fileName);
                 if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
                 if (file.loadFromDisk)
                 {
                     byte[] buffer = new byte[file.fileLength];
                     container.data.Seek(file.fileOffset, SeekOrigin.Begin);
                     container.data.Read(buffer, 0, buffer.Length);
                     File.WriteAllBytes(fileName, buffer);
                 }
                 else
                     File.WriteAllBytes(fileName, file.data);
             }
         }
     }
 }
Example #7
1
        private void cmdBatch_Click(object sender, EventArgs e)
        {
            try
            {
                FolderBrowserDialog dlgFolder = new FolderBrowserDialog();

                dlgFolder.Description = "Batch files all image files from this folder.";

                if (dlgFolder.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    DirectoryInfo dirInfo = new DirectoryInfo(dlgFolder.SelectedPath.ToString());

                    FileInfo[] ImageFiles = dirInfo.GetFiles("*.jpg").Concat(dirInfo.GetFiles("*.jpeg")).Concat(dirInfo.GetFiles("*.png")).ToArray();

                    for (int i = 0; i < ImageFiles.Length; ++i)
                    {
                        FileInfo ImageFile = ImageFiles[i];
                        Bitmap ImageBitmap = new Bitmap(ImageFile.FullName);

                        ProcessImage(ImageBitmap);
                    }

                    MessageBox.Show("Image Files Process Completed", "Process Completed", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }
        private void btnPackInputBrowse_Click(object sender, System.EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                tbPackInput.Text = fbd.SelectedPath;
        }
        public void Execute(IMenuCommand command)
        {
            IDiagram diagram = this.DiagramContext.CurrentDiagram;
            IModelStore modelStore = diagram.ModelStore;

            string SqlFile = @"C:\MyLoStore\MyLoStorePostgres.sql";
            string PythonFile = @"C:\MyLoStore\MyLoStore.py";

            FolderBrowserDialog openFolderDialog1 = new FolderBrowserDialog();
            openFolderDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
            openFolderDialog1.Description =
                "Select the directory that you want to use for generated output";

            if (openFolderDialog1.ShowDialog() == DialogResult.OK)
            {
                string folderName = openFolderDialog1.SelectedPath;
                SqlFile = folderName + @"\MyLoStorePostgres.sql";
                PythonFile = folderName + @"\MyLoStore.py";

                using (StreamWriter fsSql = new StreamWriter(SqlFile, false))
                {
                    using (StreamWriter fsPy = new StreamWriter(PythonFile, false))
                    {

                        SQLWriter mySql = new SQLWriter(SQLGenerateRun.Postgres);
                        PythonClassWriter py = new PythonClassWriter();
                        SQLGenerator sqlGen = new SQLGenerator(fsSql, mySql, fsPy, py, modelStore);
                        sqlGen.GenerateMySQL();
                    }
                }
            }
        }
Example #10
1
 private void btnExport_Click(object sender, EventArgs e)
 {
     FolderBrowserDialog fbd = new FolderBrowserDialog();
     DialogResult result = fbd.ShowDialog();
     if (result == DialogResult.Cancel) {
         //do nothing, cancel was clicked
     } else if (fbd.SelectedPath != null) {
         if (Directory.GetFiles(fbd.SelectedPath).Length == 0) {
             int count = 0;
             foreach (ListViewItem item in lvExport.Items) {
                 try {
                     string source = item.ImageKey + @"\" + item.SubItems[3].Text + ".jpg";
                     string destination = fbd.SelectedPath + @"\"
                         + item.SubItems[1].Text + "-"       //firstname
                         + item.Text + "-"                   //last name
                         + item.SubItems[2].Text + "-"       //grade
                         + item.SubItems[3].Text             //ID
                         + ".jpg";
                     File.Copy(source, destination);
                     count++;
                 } catch (Exception) {
                     //skip that one, probably an IOException due to file exists already
                     //HOWEVER, 2013-14 missed 1 file
                 }
             }
             MessageBox.Show("Copied " + count + " picture" + (count == 1 ? "." : "s."));
         } else {
             string error = "Files exist in the folder you selected.\n\nPlease create or select an empty folder and try again.";
             string caption = "Choose an Empty Folder";
             MessageBox.Show(error, caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Example #11
1
        private void BrowseClick(object sender, EventArgs e)
        {
            var browseDialog = new FolderBrowserDialog();

            if (browseDialog.ShowDialog() == DialogResult.OK)
                Directory.Text = browseDialog.SelectedPath;
        }
        private void btnInputFolder_Click(object sender, RoutedEventArgs e)
        {
            var fbd = new FolderBrowserDialog
            {
                SelectedPath =
                    Directory.Exists(txtInputFolder.Text)
                        ? txtInputFolder.Text
                        : VariousFunctions.GetApplicationLocation()
            };
            if (fbd.ShowDialog() != DialogResult.OK) return;

            SelectedPlugins.Clear();
            txtInputFolder.Text = fbd.SelectedPath;

            var di = new DirectoryInfo(txtInputFolder.Text);
            FileInfo[] fis = di.GetFiles();
            foreach (
                FileInfo fi in
                    fis.Where(
                        fi =>
                            (fi.Name.EndsWith(".asc") || fi.Name.EndsWith(".alt") || fi.Name.EndsWith(".ent") || fi.Name.EndsWith(".xml")) &&
                            Path.GetFileNameWithoutExtension(fi.Name).Length == 4))
            {
                SelectedPlugins.Add(new PluginEntry
                {
                    IsSelected = true,
                    LocalMapPath = fi.FullName,
                    PluginClassMagic = fi.Name.Remove(fi.Name.Length - 3)
                });
            }
        }
        private void FolderStore_Click(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog FolderDialog = new FolderBrowserDialog();
            FolderDialog.ShowDialog();

            FolderSave = FolderDialog.SelectedPath;
        }
Example #14
0
        public List<string> OpenFolderDialog(DataSet dataSet, string contractNbr)
        {
            List<string> returnPaths = new List<string>();
            List<string> listOfSuppliers = UniqueSupplierInDataSet(dataSet);

            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = String.Format("Välj mapp för avtal\nAvtalsnr: {0}", contractNbr);

            if(fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK){
                returnPaths.Add(fbd.SelectedPath);
            }

            foreach (string supplierNbr in listOfSuppliers)
            {
                Leverantör supplier = db.GetSupplier(supplierNbr);
                if (supplier != null)
                {
                    fbd.Description = String.Format("Välj mapp för leverantörsavtal\nLevnr: {0}\nLevnamn: {1}", supplier.Leverantörnr, supplier.Leverantörsnamn);
                }
                else
                {
                    fbd.Description = String.Format("Välj mapp för leverantörsavtal\nLevnr: {0}\nLevnamn: {1}", supplierNbr, "{namn saknas}");
                }

                if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    returnPaths.Add(fbd.SelectedPath);
                }
            }
            return returnPaths;
        }
Example #15
0
 private void button1_Click(object sender, EventArgs e)
 {
     FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
     folderBrowserDialog1.ShowDialog();
     if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
         textBox1.Text = folderBrowserDialog1.SelectedPath;
 }
        public string ShowFolderDialog(object owner)
        {
            IWin32Window win32Window = owner as IWin32Window;
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            DialogResult result = win32Window != null ? dialog.ShowDialog(win32Window) : dialog.ShowDialog();

            return result == DialogResult.OK ? dialog.SelectedPath : string.Empty;
        }
Example #17
0
 private void Browse_Click(object sender, EventArgs e)
 {
     FolderBrowserDialog dilog = new FolderBrowserDialog();
     dilog.Description = "选择WOW文件夹";
     if (dilog.ShowDialog() == DialogResult.OK || dilog.ShowDialog() == DialogResult.Yes)
     {
         textBox1.Text = dilog.SelectedPath;
     }
 }
Example #18
0
        static void Main(string[] args)
        {
            string folder;

             if (args.Length == 0)
             {
            Console.WriteLine("For the future. Usage: WPConsoleTool.exe \"folder\\path\"\n");
            Console.WriteLine(" ");
            FolderBrowserDialog folderChooser = new FolderBrowserDialog() { Description = STR_PleaseChooseTheFolderYourPhonesImages, RootFolder = Environment.SpecialFolder.MyPictures, ShowNewFolderButton = false };
            folderChooser.ShowDialog();
            while (!Directory.Exists(folder = folderChooser.SelectedPath))
            {
               DialogResult res = MessageBox.Show("You must choose the folder with your phone's images. Would you like to try again?", "No folder selected", MessageBoxButtons.RetryCancel, MessageBoxIcon.Stop);

               if (res == DialogResult.Cancel)
               {
                  return;
               }

               folderChooser.ShowDialog();
            }

            folderChooser.Dispose();
             }
             else
             {
            folder = args[0];
             }

             WPPictureFolderFixer fixer = new WPPictureFolderFixer(folder);

             Console.WriteLine(STR_InstructionsAndOptionsPrompt);

             Console.Write("\n\nEnter an option (1 or 2): ");

             char key;
             while ((key = Char.ToUpper(Convert.ToChar(Console.Read()))) != CHAR_Option1 && key != CHAR_Option2) { }

             WPPictureFolderFixerResult result = null;
             try
             {
            result = fixer.Run(key == CHAR_Option1 ? true : false, Console.WriteLine);
             }
             catch (Exception e)
             {
            Console.WriteLine("FATAL ERROR! Please, see below:\n");
            Console.WriteLine(e);
            return;
             }

             Console.WriteLine(string.Format("\nOperation Complete!\n{0}", result));
             Console.WriteLine("Press any key to continue... ");
             Console.ReadKey();
        }
Example #19
0
 private void ButtonChooseFolder_Click(object sender, EventArgs e)
 {
     FolderBrowserDialog dlg = new FolderBrowserDialog();
     if (dlg.ShowDialog() == DialogResult.Cancel)
         return;
     TextBoxFolder.Text = dlg.SelectedPath;
 }
Example #20
0
        private void button2_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            if (!String.IsNullOrEmpty(textBox2.Text))
            {
                folderBrowser.SelectedPath = textBox2.Text;
            }
            folderBrowser.ShowDialog();

            if (!String.IsNullOrEmpty(folderBrowser.SelectedPath))
            {
                listBox1.Items.Clear();
                textBox2.Text = folderBrowser.SelectedPath;

                DirectoryInfo directoryInfo = new DirectoryInfo(folderBrowser.SelectedPath);
                foreach (FileInfo fileInfo in directoryInfo.GetFiles())
                {
                    Console.WriteLine("Extension : " + fileInfo.Extension);
                    if (fileInfo.Extension.ToLower().Equals(".apk"))
                    {
                        listBox1.Items.Add(fileInfo);
                    }
                }
            }
        }
Example #21
0
 private void BrowseSource_Click(object sender, EventArgs e)
 {
     FolderBrowserDialog dialog = new FolderBrowserDialog();
     dialog.SelectedPath = PushDestination.Text;
     if (dialog.ShowDialog() == DialogResult.OK)
         PushDestination.Text = dialog.SelectedPath;
 }
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            var dialog =
                new FolderBrowserDialog
                    {
                        Description = "Select a folder",
                        RootFolder = Environment.SpecialFolder.Desktop,
                        ShowNewFolderButton = false
                    };
            if (dialog.ShowDialog(this) == DialogResult.OK)
            {
                var folder = dialog.SelectedPath;

                // Check for duplicates
                var bDuplicate = false;
                foreach (ListViewItem item in m_lstFolders.Items)
                {
                    if (string.Compare(folder, item.Text, StringComparison.OrdinalIgnoreCase) != 0)
                        continue;

                    bDuplicate = true;
                    break;
                }

                // Add item to ListView
                if (!bDuplicate)
                    m_lstFolders.Items.Add(folder);
            }
            dialog.Dispose();
        }
Example #23
0
        /// <summary>
        /// 选择一个文件夹并返回它的路径
        /// </summary>
        public static string ChooseDirectory()
        {
            var fileFetch = new FolderBrowserDialog();
            fileFetch.ShowDialog();

            return fileFetch.SelectedPath;
        }
Example #24
0
        /// <summary>
        /// Opens a a FolderBrowserDialog with the path in "getter" preselected and 
        /// if the DialogResult.OK is returned uses "setter" to set the path
        /// </summary>
        /// <param name="getter"></param>
        /// <param name="setter"></param>
        public void ShowFolderBrowserDialogWithPreselectedPath(Func<string> getter, Action<string> setter)
        {
            string directoryInfoPath = null;
            try
            {
                directoryInfoPath = new DirectoryInfo(getter()).FullName;
            }
            catch (Exception)
            {
                // since the DirectoryInfo stuff is for convenience we swallow exceptions
            }

            using (var dialog = new FolderBrowserDialog
            {
                RootFolder = Environment.SpecialFolder.Desktop,
                // if we do not use the DirectoryInfo then a path with slashes instead of backslashes won't work
                SelectedPath = directoryInfoPath ?? getter()
            })
            {
                // TODO: do we need ParentForm or is "this" ok?
                if (dialog.ShowDialog(ParentForm) == DialogResult.OK)
                {
                    setter(dialog.SelectedPath);
                }
            }
        }
Example #25
0
        private void btnLoadData_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog dlgFolder = new FolderBrowserDialog())
            {
                if (dlgFolder.ShowDialog() == DialogResult.OK)
                {

                    for (int i = 0; i < this.feretDataSet.faces.Rows.Count; i++)
                    {
                        this.feretDataSet.faces.Rows[i].Delete();

                    }

                    updateDatabase();

                    BackgroundWorker worker = new BackgroundWorker();
                    worker.WorkerReportsProgress = true;
                    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
                    worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
                    worker.RunWorkerAsync(dlgFolder.SelectedPath);

                    lstInfo.Enabled = false;
                    //lstSelect.Enabled = false;
                    btnLoadData.Enabled = false;
                    btnSaveSetList.Enabled = false;
                    dataGridView1.Enabled = false;
                }

            }
        }
Example #26
0
 private void btnSelectFolder_Click(object sender, EventArgs e)
 {
     FolderBrowserDialog dlg = new FolderBrowserDialog();
     if (dlg.ShowDialog(this) != DialogResult.OK)
         return;
     txtDestFolder.Text = dlg.SelectedPath;
 }
Example #27
0
        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog FBD = new FolderBrowserDialog();

            if (FBD.ShowDialog() == DialogResult.OK)
            {
                checkedListBox1.Items.Clear();
                //now create an array for files
                string[] files = Directory.GetFiles(FBD.SelectedPath);
                //now create an array for directories
                string[] dirs = Directory.GetDirectories(FBD.SelectedPath);

                //now just show the files/dirs in checkedListBox1
                //use a foreach loop

                foreach (string file in files)
                {
                    checkedListBox1.Items.Add(file);
                }

                //now do the same for dirs
                foreach (string dir in dirs)
                {
                    checkedListBox1.Items.Add(dir);
                }
            }
        }
 private void browseButton_Click(object sender, EventArgs e)
 {
     FolderBrowserDialog folderDialog = new FolderBrowserDialog();
     DialogResult result = folderDialog.ShowDialog();
     if (result == DialogResult.OK)
         pathTextBox.Text = folderDialog.SelectedPath;
 }
        private void btnInputFolder_Click(object sender, RoutedEventArgs e)
        {
            var fbd = new FolderBrowserDialog
            {
                SelectedPath =
                    Directory.Exists(txtInputFolder.Text)
                        ? txtInputFolder.Text
                        : VariousFunctions.GetApplicationLocation()
            };
            if (fbd.ShowDialog() != DialogResult.OK) return;

            GeneratorMaps.Clear();
            txtInputFolder.Text = fbd.SelectedPath;

            var di = new DirectoryInfo(txtInputFolder.Text);
            FileInfo[] fis = di.GetFiles("*.map");
            foreach (
                FileInfo fi in
                    fis.Where(
                        fi =>
                            !fi.Name.ToLower().StartsWith("campaign") && !fi.Name.ToLower().StartsWith("shared") &&
                            !fi.Name.ToLower().StartsWith("single_player_shared")))
            {
                GeneratorMaps.Add(new MapEntry
                {
                    IsSelected = true,
                    LocalMapPath = fi.FullName,
                    MapName = fi.Name
                });
            }
        }
Example #30
0
 private void Button_Select_Click(Object sender, RoutedEventArgs e)
 {
     using (var d = new FolderBrowserDialog()) {
         var r = d.ShowDialog();
         if (r == System.Windows.Forms.DialogResult.OK) FolderLocation.Text = d.SelectedPath;
     }
 }
Example #31
0
        public override int Execute(params string[] parameters)
        {
            Win.MessageBoxResult result
                = Win.MessageBox.Show("Перед экспортом FBX, нужно настроить параметры экспорта в "
                                      + "FBX на экспорт ЛИБО В ФОРМАТЕ ASCII, ЛИБО В ДВОИЧНОМ ФОРМАТЕ ВЕРСИИ НЕ НОВЕЕ 2018. "
                                      + "Рекомендуется так же отключить экспорт источников света и камер. "
                                      + "\n\nНачать выгрузку FBX?", "Выгрузка FBX", Win.MessageBoxButton.YesNo);
            if (result == Win.MessageBoxResult.Yes)
            {
                try
                {
                    Document doc = Application.ActiveDocument;
                    DocumentSelectionSets selectionSets  = doc.SelectionSets;
                    FolderItem            rootFolderItem = selectionSets.RootItem;
                    List <FolderItem>     folders        = new List <FolderItem>();
                    foreach (SavedItem item in rootFolderItem.Children)
                    {
                        if (item is FolderItem)
                        {
                            folders.Add(item as FolderItem);
                        }
                    }

                    if (folders.Count == 0)
                    {
                        WinForms.MessageBox.Show("Для работы этой команды необходимо наличие папок с сохраненными наборами выбора",
                                                 "Отменено", WinForms.MessageBoxButtons.OK);
                        return(0);
                    }

                    //Вывести окно для выбора корневой папки для формирования структуры
                    SelectRootFolderWindow selectRootFolderWindow = new SelectRootFolderWindow(folders, false, null);
                    bool?resultRootSelect = selectRootFolderWindow.ShowDialog();
                    if (resultRootSelect != null && resultRootSelect.Value)
                    {
                        string initialPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        string docPath     = doc.FileName;
                        if (!String.IsNullOrEmpty(docPath))
                        {
                            initialPath = Path.GetDirectoryName(docPath);
                        }


                        WinForms.FolderBrowserDialog fbd = new WinForms.FolderBrowserDialog();
                        fbd.Description         = "Выберите расположение файлов FBX";
                        fbd.ShowNewFolderButton = true;
                        fbd.SelectedPath        = initialPath;
                        WinForms.DialogResult fbdResult = fbd.ShowDialog();
                        if (fbdResult == WinForms.DialogResult.OK)
                        {
                            FolderItem rootFolder = selectRootFolderWindow.RootFolder;
                            FBXExport.ManualUse   = false;
                            FBXExport.FBXSavePath = fbd.SelectedPath;
                            ExportBySelSets(rootFolder, doc);

                            Win.MessageBox.Show("Готово", "Готово", Win.MessageBoxButton.OK,
                                                Win.MessageBoxImage.Information);
                        }
                    }
                }
                catch (Exception ex)
                {
                    CommonException(ex, "Ошибка при экспорте объектов по отдельным наборам выбора");
                }
                finally
                {
                    FBXExport.ManualUse   = true;
                    FBXExport.FBXSavePath = null;
                    FBXExport.FBXFileName = null;
                }
            }



            return(0);
        }
Example #32
0
        private void abrirBaseDeDatosToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (System.Windows.Forms.FolderBrowserDialog dialogo = new System.Windows.Forms.FolderBrowserDialog())
                {
                    dialogo.Description = "Abrir";

                    if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        DirectoryInfo di = new DirectoryInfo(dialogo.SelectedPath);

                        if (di.GetFiles("*.dd").Count() != 0)
                        {
                            string snom = di.GetFiles("*.dd")[0].FullName;
                            ((Control)TabPageAtributos).Enabled = true;
                            AgregaTabla.Enabled = true;
                            txtBAgrega.Enabled  = true;
                            cmbTablas.Enabled   = true;
                            eliminarBaseDeDatosActualToolStripMenuItem.Enabled = true;
                            modificarBaseDeDatosToolStripMenuItem.Enabled      = true;

                            cmbTablas.Items.Clear();
                            lTablas = new List <Tabla>();
                            using (Stream st = File.Open(snom, FileMode.Open))
                            {
                                var binfor = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                                Dic = new Diccionario();
                                Dic = (Diccionario)binfor.Deserialize(st);
                                labNombreBD.Text = Dic.NombreBD;
                                Tabla auxTabla;
                                for (int i = 0; i < Dic.LNombresTablas.Count; i++)
                                {
                                    cmbTablas.Items.Add(Dic.LNombresTablas[i]);
                                    string PathTabla = Dic.Ruta + "\\" + Dic.LNombresTablas[i] + ".tab";
                                    using (Stream str = File.Open(PathTabla, FileMode.Open))
                                    {
                                        auxTabla = new Tabla();
                                        var binforTab = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                                        auxTabla = (Tabla)binforTab.Deserialize(str);
                                        lTablas.Add(auxTabla);
                                    }
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("No existe la Base de Datos");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Se Cancelo La Operación");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error");
            }
        }
Example #33
0
        private void 打开文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            person_sum = 0;
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 1500; j++)
                {
                    person[i].top_xmin[j]  = person[i].top_ymin[j] = person[i].top_xlen[j] = person[i].top_ylen[j] = 0.0f;
                    person[i].hor1_xmin[j] = person[i].hor1_ymin[j] = person[i].hor1_xlen[j] = person[i].hor1_ylen[j] = 0.0f;
                    person[i].hor2_xmin[j] = person[i].hor2_ymin[j] = person[i].hor2_xlen[j] = person[i].hor2_ylen[j] = 0.0f;
                    person[i].hor3_xmin[j] = person[i].hor3_ymin[j] = person[i].hor3_xlen[j] = person[i].hor3_ylen[j] = 0.0f;
                }
            }
            mode = 4;
            X    = this.Width;  //获取窗体的宽度
            Y    = this.Height; //获取窗体的高度
            if (folderdia.ShowDialog() == DialogResult.OK)
            {
                string text = folderdia.SelectedPath;
                foldername = text;
                int cur_line;
                int cur_frame;
                int cur_person;
                /* 重置表格 */
                this.uiDataGridView1.Rows.Clear();
                /* 顶视 */
                string[] f1;
                f1 = System.IO.Directory.GetDirectories(foldername, "*top");
                if (f1 == null)
                {
                    //textBox2.Text = "未找到视频!";
                    return;
                }
                image_file_top = System.IO.Directory.GetFiles(f1[0], "*.jpg");
                pos_file_top   = System.IO.Directory.GetFiles(f1[0], "*.txt");
                this.uiDataGridView1.Rows.Add(new System.String[] {
                    "TopView",
                    "",
                    ""
                });
                lines      = System.IO.File.ReadAllLines(pos_file_top[0]);
                cur_line   = 0;
                cur_frame  = 0;
                cur_person = 0;
                while (cur_line < lines.Length)
                {
                    string[] words = lines[cur_line].Split(',');
                    if (Int32.Parse(words[0]) < cur_frame)
                    {
                        cur_person++;
                    }
                    cur_frame = Int32.Parse(words[0]) - 1;
                    person[cur_person].top_xmin[cur_frame] = float.Parse(words[2]);
                    person[cur_person].top_ymin[cur_frame] = float.Parse(words[3]);
                    person[cur_person].top_xlen[cur_frame] = float.Parse(words[4]);
                    person[cur_person].top_ylen[cur_frame] = float.Parse(words[5]);
                    cur_line++;
                }
                cur_person++;
                if (cur_person > person_sum)
                {
                    person_sum = cur_person;
                }

                /* 平视1 */
                string[] f2;
                f2 = System.IO.Directory.GetDirectories(foldername, "*hor1");
                if (f2 == null)
                {
                    //textBox2.Text = "未找到视频!";
                    return;
                }
                image_file_hor1 = System.IO.Directory.GetFiles(f2[0], "*.jpg");
                pos_file_hor1   = System.IO.Directory.GetFiles(f2[0], "*.txt");
                this.uiDataGridView1.Rows.Add(new System.String[] {
                    "HorizontalView1",
                    "",
                    ""
                });
                lines      = System.IO.File.ReadAllLines(pos_file_hor1[0]);
                cur_line   = 0;
                cur_frame  = 0;
                cur_person = 0;
                while (cur_line < lines.Length)
                {
                    string[] words = lines[cur_line].Split(',');
                    if (Int32.Parse(words[0]) < cur_frame)
                    {
                        cur_person++;
                    }
                    cur_frame = Int32.Parse(words[0]) - 1;
                    person[cur_person].hor1_xmin[cur_frame] = float.Parse(words[2]);
                    person[cur_person].hor1_ymin[cur_frame] = float.Parse(words[3]);
                    person[cur_person].hor1_xlen[cur_frame] = float.Parse(words[4]);
                    person[cur_person].hor1_ylen[cur_frame] = float.Parse(words[5]);
                    cur_line++;
                }
                cur_person++;
                if (cur_person > person_sum)
                {
                    person_sum = cur_person;
                }

                /* 平视2 */
                string[] f3;
                f3 = System.IO.Directory.GetDirectories(foldername, "*hor2");
                if (f3.Length == 0)
                {
                    mode = 2;
                    pictureBox2.Visible  = false;
                    label2.Visible       = false;
                    pictureBox3.Visible  = false;
                    label3.Visible       = false;
                    pictureBox1.Width    = Convert.ToInt32(268 * (X / 920));
                    pictureBox1.Height   = Convert.ToInt32(177 * (Y / 551));
                    pictureBox4.Width    = Convert.ToInt32(268 * (X / 920));
                    pictureBox4.Height   = Convert.ToInt32(177 * (Y / 551));
                    pictureBox1.Location = new System.Drawing.Point(147, 87);
                    label1.Location      = new System.Drawing.Point(147, 87);
                    pictureBox4.Location = new System.Drawing.Point(147, 280);
                    label4.Location      = new System.Drawing.Point(147, 280);
                    label4.Text          = "HorizontalView1";
                }
                else
                {
                    image_file_hor2 = System.IO.Directory.GetFiles(f3[0], "*.jpg");
                    pos_file_hor2   = System.IO.Directory.GetFiles(f3[0], "*.txt");
                    this.uiDataGridView1.Rows.Add(new System.String[] {
                        "HorizontalView2",
                        "",
                        ""
                    });
                    lines      = System.IO.File.ReadAllLines(pos_file_hor2[0]);
                    cur_line   = 0;
                    cur_frame  = 0;
                    cur_person = 0;
                    while (cur_line < lines.Length)
                    {
                        string[] words = lines[cur_line].Split(',');
                        if (Int32.Parse(words[0]) < cur_frame)
                        {
                            cur_person++;
                        }
                        cur_frame = Int32.Parse(words[0]) - 1;
                        person[cur_person].hor2_xmin[cur_frame] = float.Parse(words[2]);
                        person[cur_person].hor2_ymin[cur_frame] = float.Parse(words[3]);
                        person[cur_person].hor2_xlen[cur_frame] = float.Parse(words[4]);
                        person[cur_person].hor2_ylen[cur_frame] = float.Parse(words[5]);
                        cur_line++;
                    }
                    cur_person++;
                    if (cur_person > person_sum)
                    {
                        person_sum = cur_person;
                    }
                }

                if (mode != 2)
                {
                    /* 平视3 */
                    string[] f4;
                    f4 = System.IO.Directory.GetDirectories(foldername, "*hor3");
                    if (f4.Length == 0)
                    {
                        mode = 3;
                        pictureBox2.Visible  = true;
                        label2.Visible       = true;
                        pictureBox3.Visible  = false;
                        label3.Visible       = false;
                        pictureBox1.Width    = Convert.ToInt32(245 * (X / 920));
                        pictureBox1.Height   = Convert.ToInt32(169 * (Y / 551));
                        pictureBox4.Width    = Convert.ToInt32(245 * (X / 920));
                        pictureBox4.Height   = Convert.ToInt32(169 * (Y / 551));
                        pictureBox1.Location = new System.Drawing.Point(146, 87);
                        label1.Location      = new System.Drawing.Point(146, 87);
                        pictureBox4.Location = new System.Drawing.Point(270, 259);
                        label4.Location      = new System.Drawing.Point(266, 259);
                        label4.Text          = "HorizontalView2";
                    }
                    else
                    {
                        mode = 4;
                        pictureBox2.Visible  = true;
                        label2.Visible       = true;
                        pictureBox3.Visible  = true;
                        label3.Visible       = true;
                        pictureBox1.Width    = Convert.ToInt32(245 * (X / 920));
                        pictureBox1.Height   = Convert.ToInt32(169 * (Y / 551));
                        pictureBox4.Width    = Convert.ToInt32(245 * (X / 920));
                        pictureBox4.Height   = Convert.ToInt32(169 * (Y / 551));
                        pictureBox1.Location = new System.Drawing.Point(Convert.ToInt32(12 * (X / 920)), Convert.ToInt32(74 * (Y / 551)));
                        label1.Location      = new System.Drawing.Point(Convert.ToInt32(12 * (X / 920)), Convert.ToInt32(74 * (Y / 551)));
                        pictureBox4.Location = new System.Drawing.Point(Convert.ToInt32(266 * (X / 920)), Convert.ToInt32(259 * (Y / 551)));
                        label4.Location      = new System.Drawing.Point(Convert.ToInt32(266 * (X / 920)), Convert.ToInt32(259 * (Y / 551)));
                        label4.Text          = "HorizontalView3";
                        image_file_hor3      = System.IO.Directory.GetFiles(f4[0], "*.jpg");
                        //pos4 = System.IO.Directory.GetDirectories(f4[0], "*xml");
                        pos_file_hor3 = System.IO.Directory.GetFiles(f4[0], "*.txt");
                        this.uiDataGridView1.Rows.Add(new System.String[] {
                            "HorizontalView3",
                            "",
                            ""
                        });
                        lines      = System.IO.File.ReadAllLines(pos_file_hor3[0]);
                        cur_line   = 0;
                        cur_frame  = 0;
                        cur_person = 0;
                        while (cur_line < lines.Length)
                        {
                            string[] words = lines[cur_line].Split(',');
                            if (Int32.Parse(words[0]) < cur_frame)
                            {
                                cur_person++;
                            }
                            cur_frame = Int32.Parse(words[0]) - 1;
                            person[cur_person].hor3_xmin[cur_frame] = float.Parse(words[2]);
                            person[cur_person].hor3_ymin[cur_frame] = float.Parse(words[3]);
                            person[cur_person].hor3_xlen[cur_frame] = float.Parse(words[4]);
                            person[cur_person].hor3_ylen[cur_frame] = float.Parse(words[5]);
                            cur_line++;
                        }
                        cur_person++;
                        if (cur_person > person_sum)
                        {
                            person_sum = cur_person;
                        }
                    }
                }
            }
            setTag(this);
        }
Example #34
0
        //图片文件名转换
        private void conversePhotoName_Click(object sender, EventArgs e)
        {
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult      dr         = MessageBox.Show("请确认照相完毕,然后进行转换!", "系统警示", messButton);

            if (dr == DialogResult.OK)//如果点击“确定”按钮
            {
                System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
                dialog.Description = "请选择照片所在的文件夹";

                if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string filePath = dialog.SelectedPath;
                    if (string.IsNullOrEmpty(filePath))
                    {
                        MessageBox.Show(this, "文件夹路径不能为空", "提示");
                        return;
                    }
                    else
                    {
                        //具体文件保存位置
                        //对字符串进行处理
                        //string srcDir= filePath ;
                        //string descDir = FileUtils.ProjectPath + projectName + "\\photo";
                        //复制图片
                        // FileUtils.file_copy(srcDir, descDir);
                        //更新form1中的lists
                        CommonUtils.loadDataToLists();
                        //进行改名处理

                        //数据库中编号1对应照片名称DSC_0001.JPG    以此类推......
                        //先获取已编号的学生数据
                        List <string> noPhotoList = new List <string>();
                        for (int i = 0; i < dataTable.Rows.Count; i++)
                        {
                            string strId        = int.Parse(dataTable.Rows[i][0].ToString()).ToString("0000");
                            string strIdCardNum = dataTable.Rows[i][3].ToString();
                            //string srcPath = FileUtils.ProjectPath + projectName + "\\photo\\DSC_" + strId + ".JPG";
                            string srcPath = filePath + "\\DSC_" + strId + ".JPG";
                            //进行改名并复制操作:
                            if (File.Exists(srcPath))
                            {
                                string destPath = FileUtils.ProjectPath + projectName + "\\photo\\" + strIdCardNum + ".JPG";
                                File.Copy(srcPath, destPath, true);
                            }
                            else
                            {
                                //说明此学生已经编号,但是没有导入此学生的照片,
                                noPhotoList.Add(strId);
                            }
                        }


                        //处理完毕
                        if (noPhotoList.Count == 0)
                        {
                            //正常
                            MessageBox.Show("图片文件名转换完毕!");
                        }
                        else
                        {
                            //数据处理不正常
                            StringBuilder sb = new StringBuilder();
                            sb.Append("编号为: ");
                            for (int i = 0; i < noPhotoList.Count; i++)
                            {
                                string s = noPhotoList[i] + "  ";
                                sb.Append(s);
                            }
                            sb.Append("的学生没有照片!");
                            MessageBox.Show(sb.ToString());
                        }
                    }
                }
            }
        }
Example #35
0
        static BatchCommands()
        {
            BatchCommands.AddFileCommand = new RelayCommand <Object>
                                           (
                delegate
            {
                OpenFileDialog dlg = new OpenFileDialog()
                {
                    Filter      = "All Files (*.*)|*.*",
                    Multiselect = true
                };

                if (dlg.ShowDialog() == true)
                {
                    FileHelper.AddNewFiles(dlg.FileNames);
                }
            }
                                           );

            BatchCommands.AddFolderCommand = new RelayCommand <Object>
                                             (
                delegate
            {
                using (WinForms.FolderBrowserDialog dlg = new WinForms.FolderBrowserDialog()
                {
                    Description = "Select a folder to add its files",
                    ShowNewFolderButton = false
                })
                {
                    if (dlg.ShowDialog() == WinForms.DialogResult.OK)
                    {
                        FileHelper.AddNewFiles(Directory.GetFiles(dlg.SelectedPath));
                    }
                }
            }
                                             );

            BatchCommands.BatchRenameCommand = new RelayCommand <Object>
                                               (
                delegate
            {
                MessageBoxResult result = MessageBox.Show(App.Current.MainWindow,
                                                          "The files will be renamed according to the new file names."
                                                          + Environment.NewLine
                                                          + "This operation is NOT reversible."
                                                          + Environment.NewLine
                                                          + Environment.NewLine
                                                          + "Continue?",
                                                          App.Current.MainWindow.Title,
                                                          MessageBoxButton.YesNo,
                                                          MessageBoxImage.Question,
                                                          MessageBoxResult.No);

                if (result == MessageBoxResult.Yes)
                {
                    using (BackgroundWorker backgroundWorker = new BackgroundWorker()
                    {
                        WorkerReportsProgress = true
                    })
                    {
                        backgroundWorker.DoWork             += Routines.BatchRenameBackgroundWorker_DoWork;
                        backgroundWorker.ProgressChanged    += Routines.BatchRenameBackgroundWorker_ProgressChanged;
                        backgroundWorker.RunWorkerCompleted += Routines.BatchRenameBackgroundWorker_RunWorkerCompleted;

                        AppState.Current.IsBusy = true;

                        backgroundWorker.RunWorkerAsync();
                    }
                }
            },
                delegate
            {
                return(AppState.Current?.Files.Count > 0 &&
                       AppState.Current?.Files.Count(f => f.IsModified) > 0);
            }
                                               );
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            string instanceUrl = "https://greenwayhealth.my.salesforce.com/";
            string accessToken = "";
            string apiVersion  = "v37.0";
            string folderPath  = "";

            ForceClient client = new ForceClient(instanceUrl, accessToken, apiVersion);

            // Empty TextBlock
            statusBlock.Text = "";

            using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
            {
                dialog.SelectedPath = Properties.Settings.Default.MPPFolderPath;
                System.Windows.Forms.DialogResult result = dialog.ShowDialog();
                folderPath = dialog.SelectedPath;
                Properties.Settings.Default.MPPFolderPath = dialog.SelectedPath;
                Properties.Settings.Default.Save();
            }

            DirectoryInfo objDirectoryInfo = new DirectoryInfo(folderPath);

            FileInfo[] mppFiles = objDirectoryInfo.GetFiles("*.mpp", SearchOption.TopDirectoryOnly);

            if (mppFiles.Length == 0)
            {
                System.Windows.MessageBox.Show("There are no MPP files");
            }
            else
            {
                // Read mpp files
                foreach (var file in mppFiles)
                {
                    ProjectReader reader      = new MPPReader();
                    ProjectFile   projectObj  = reader.read($"{file.FullName}");
                    var           projectName = file.Name.Replace(".mpp", "");

                    // Get Tasks from MPP file
                    foreach (net.sf.mpxj.Task task in ToEnumerable(projectObj.getAllTasks()))
                    {
                        // Filter tasks to be updated
                        if (task.getID().toString() == "222")
                        {
                            var projects = await client.QueryAsync <Project>(
                                $"SELECT Id, Name, EHR_Actual_Go_Live_Date__c FROM pse__Proj__c where Name like 'Baton Rouge Primary Care Collaborative%' limit 1");

                            foreach (var project in projects.Records)
                            {
                                DateTime startDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(
                                    task.getStart().getTime()).ToLocalTime();
                                DateTime endDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(
                                    task.getFinish().getTime()).ToLocalTime();

                                string startDataVal = startDate.ToString("yyyy-MM-ddTHH:mm:ss+0000");
                                string endDataVal   = startDate.ToString("yyyy-MM-ddTHH:mm:ss+0000");

                                var updateProject = new Project()
                                {
                                    name = project.name,
                                    EHR_Actual_Go_Live_Date__c = startDataVal,
                                    Practice_Management_Actual_Go_Live_Date__c = startDataVal
                                };

                                var success = await client.UpdateAsync("pse__Proj__c", project.Id, updateProject);

                                var responseMessage = "is successfully updated!";
                                if (success.Success == true)
                                {
                                    responseMessage = "is not updated";
                                }

                                statusBlock.Text = statusBlock.Text + $"Project: {project.name} # " +
                                                   $"Task: {task.getID().toString()} {responseMessage} \n";

                                //Resource r = projectObj.getResourceByUniqueID(task.getUniqueID());

                                //if (r != null)
                                //{
                                //    Console.WriteLine($"{r.getName()}");
                                //}
                            }
                        }
                    }
                }
            }
        }
Example #37
0
        /*private void CheckIfDocBackup(){
         * IsBackup=false;
         *                  DirectoryInfo dirInfo=new DirectoryInfo(textDocPath.Text);
         *                  FileInfo[] fi=dirInfo.GetFiles();
         *                  for(int i=0;i<fi.Length;i++){
         *                          if(fi[i].Name=="Backup"){
         *    IsBackup=true;
         *  }
         *                  }
         * }*/

        private void buBrowseDoc_Click(object sender, System.EventArgs e)
        {
            fb.ShowDialog();
            textDocPath.Text = fb.SelectedPath + @"\";
        }
Example #38
0
        private async void SelectSourceFolder()
        {
            while (true)
            {
                var folderDialog = new WinForms.FolderBrowserDialog
                {
                    Description = @"select a new source folder to add source locations list"
                };
                if (string.IsNullOrEmpty(_lastSource) == false)
                {
                    folderDialog.SelectedPath = _lastSource;
                }
                var folderDialogResult = folderDialog.ShowDialog();
                if (folderDialogResult != System.Windows.Forms.DialogResult.OK)
                {
                    break;
                }
                if (folderDialog.SelectedPath.Length < 4)
                {
                    await this.ShowMessageAsync("cannot accept the location", "You have selected a drive . \nplease select a folder ", MessageDialogStyle.Affirmative, new MetroDialogSettings { AffirmativeButtonText = "OK" });

                    continue;
                }
                var selectedDir = new DirectoryInfo(folderDialog.SelectedPath);
                if (selectedDir.FullName == DestinationTextBox.Text)
                {
                    await this.ShowMessageAsync("Cannot add Folder", "Cannot add selected folder because it is selected as the destination folder.\nplease select deferent location and try again ", MessageDialogStyle.Affirmative, new MetroDialogSettings { AffirmativeButtonText = "OK" });

                    return;
                }

                if (!selectedDir.Exists)
                {
                    var result = await this.ShowMessageAsync("Folder dose not exists", "The selected directory not exist in the given path. \ndo you want to try another location?", MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings { AffirmativeButtonText = "Yes", NegativeButtonText = "No" });

                    if (result == MessageDialogResult.Affirmative)
                    {
                        continue;
                    }
                    return;
                }
                var have = false;
                foreach (ComboBoxItem cbi in SourceLocationsComboBox.Items)
                {
                    have = ((string)cbi.ToolTip == selectedDir.FullName);
                }

                if (!have)
                {
                    var comboBoxItem = new ComboBoxItem
                    {
                        ToolTip    = selectedDir.FullName,
                        Tag        = selectedDir.FullName,
                        IsSelected = true,
                        Content    = selectedDir.Name
                    };
                    SourceLocationsComboBox.Items.Add(comboBoxItem);
                    _lastSource = selectedDir.FullName;
                }
                break;
            }
        }
Example #39
0
        static void Main()
        {
            try
            {
                //Serializacao.SerializaXml(new Config() {  CaminhoBase="dasdcascac"}, "D:\\config.xml");
                Geral.Config = Serializacao.DeserializaXml <Config>(AppDomain.CurrentDomain.BaseDirectory + "Config.xml");


                bool baseOK = false;

                //new Assistente.DAO.BaseDAO().Salvar(baseOK);
                Application.EnableVisualStyles();
                try
                {
                    Application.SetCompatibleTextRenderingDefault(false);
                }
                catch (Exception) { }

                baseOK = BancoDados.ValidaCaminhoBase();//AppDomain.CurrentDomain.BaseDirectory + "config.xml");

                if (!baseOK)
                {
                    System.Windows.Forms.FolderBrowserDialog fbdBackup;
                    fbdBackup             = new System.Windows.Forms.FolderBrowserDialog();
                    fbdBackup.Description = "Informe o local onde está ou será armazenado o arquivo do banco de dados.";
                    if (fbdBackup.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        baseOK = BancoDados.CriarBase(fbdBackup.SelectedPath.ToString() + "\\");//, AppDomain.CurrentDomain.BaseDirectory);
                    }
                }
                if (baseOK)
                {    //Application.Run(new Assistente.View.Forms.frmAssitente());
                    BancoDados.Config(TipoConexao.SQLite, new string[] { BancoDados.CaminhoBase + "AssistenteDB.db3" });

                    BancoDados.AbrirSessao();
                    //Geral.VerificarConfiguracoes();

                    //if (new Assistente.View.Forms.frmLogin().Carregar())
                    //{
                    //if (Geral.AmbienteLocal.CaminhoPenDrive.Trim().Length >0
                    //    && File.Exists(Geral.AmbienteLocal.CaminhoPenDrive + "AssistenteDB.db3") &&
                    //MessageBox.Show("Deseja copiar o arquivo a base do Pen Drive?", "Base", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                    //{
                    //    BancoDados.FecharSessao();
                    //    //if (File.Exists(Geral.AmbienteLocal.CaminhoLocal + "AssistenteDB.db3"))
                    //    File.Delete(Geral.AmbienteLocal.CaminhoLocal + "AssistenteDB.db3");
                    //    FileSystem.CopyFile(Geral.AmbienteLocal.CaminhoPenDrive + "AssistenteDB.db3",
                    //        Geral.AmbienteLocal.CaminhoLocal + "AssistenteDB.db3", UIOption.AllDialogs);
                    //    BancoDados.AbrirSessao();
                    //}
                    AtualizaVersao.AtualizarScripts();

                    //Application.Run(new Assistente.View.Forms.frmAssistente());
                    Application.Run(new Assistente.View.Forms.frmTarefas());

                    Serializacao.SerializaXml(Geral.Config, AppDomain.CurrentDomain.BaseDirectory + "Config.xml");


                    //}
                }
            }
            catch (Exception ex)
            {
                Assistente.Controle.WinControls.ApresentarErro(Assistente.Excecoes.AssistErroException.TratarErro(ex));
            }
        }
        ///<summary> This gets called when when the user runs this command.</summary>
        public override IRhinoCommand.result RunCommand(IRhinoCommandContext context)
        {
            // Verify that we have materials to remap textures
            MRhinoMaterialTable materialTable = context.m_doc.m_material_table;
            int materialCount = materialTable.MaterialCount();

            if (0 == materialCount)
            {
                RhUtil.RhinoApp().Print("No material found.\n");
                return(IRhinoCommand.result.nothing);
            }

            // Prompt the user for the new texture folder
            FolderBrowserDialog folderBrowser = new System.Windows.Forms.FolderBrowserDialog();

            folderBrowser.Description = "Select new texture folder";
            folderBrowser.RootFolder  = System.Environment.SpecialFolder.Desktop;
            DialogResult result = folderBrowser.ShowDialog();

            if (result != DialogResult.OK)
            {
                return(IRhinoCommand.result.cancel);
            }

            // The folder to search fo textures
            string searchFolder = folderBrowser.SelectedPath;

            // We will cache the search results (for performance)
            Dictionary <string, string> textureMap = new Dictionary <string, string>();

            // Used for reporting the results of the remap
            int numMaterials = 0;
            int numTextures  = 0;
            int numRemapped  = 0;

            // Iterate through the material table
            for (int i = 0; i < materialCount; i++)
            {
                // Get a material
                IRhinoMaterial oldMaterial = materialTable[i];

                // Validate...
                if (null == oldMaterial)
                {
                    continue;
                }

                // .. and validate...
                if (oldMaterial.IsDeleted() || oldMaterial.IsReference())
                {
                    continue;
                }

                numMaterials++;

                // .. and validate.
                int textureCount = oldMaterial.m_textures.Count();
                if (0 == textureCount)
                {
                    continue;
                }

                numTextures += textureCount;

                // Copy the material
                OnMaterial newMaterial = new OnMaterial(oldMaterial);
                bool       bModify     = false;

                for (int j = 0; j < textureCount; j++)
                {
                    string texturePath = newMaterial.m_textures[j].m_filename;
                    string textureName = Path.GetFileName(texturePath).ToLower();

                    // See if the material to remap has already been found
                    string mapValue;
                    if (textureMap.TryGetValue(textureName, out mapValue))
                    {
                        // Do the remap
                        newMaterial.m_textures[j].m_filename = mapValue;
                        numRemapped++;
                        bModify = true;
                    }
                    else
                    {
                        // The material to remap has not been found (already), so go searching
                        string[] searchResults = Directory.GetFiles(searchFolder, textureName, SearchOption.AllDirectories);
                        if (null != searchResults && searchResults.Length > 0)
                        {
                            // Do the remap (use the first one found...)
                            newMaterial.m_textures[j].m_filename = searchResults[0];
                            // Add the results of the search to the dictionary
                            textureMap.Add(textureName, searchResults[0]);
                            numRemapped++;
                            bModify = true;
                        }
                        else
                        {
                            // Oops...
                            RhUtil.RhinoApp().Print(string.Format("Unable to remap {0}\n", texturePath));
                        }
                    }
                }

                // Modify the existing material by replacing with with the new one
                if (bModify)
                {
                    materialTable.ModifyMaterial(newMaterial, oldMaterial.m_material_index);
                }
            }

            // Remapping textures requries a full redraw
            if (numRemapped > 0)
            {
                context.m_doc.Regen();
            }

            // Report the results
            if (1 == numMaterials)
            {
                RhUtil.RhinoApp().Print(string.Format("1 material found\n", numMaterials));
            }
            else
            {
                RhUtil.RhinoApp().Print(string.Format("{0} materials found\n", numMaterials));
            }

            if (1 == numTextures)
            {
                RhUtil.RhinoApp().Print(string.Format("1 texture found\n", numTextures));
            }
            else
            {
                RhUtil.RhinoApp().Print(string.Format("{0} textures found\n", numTextures));
            }

            if (1 == numRemapped)
            {
                RhUtil.RhinoApp().Print(string.Format("1 texture remapped\n", numRemapped));
            }
            else
            {
                RhUtil.RhinoApp().Print(string.Format("{0} textures remapped\n", numRemapped));
            }

            return(IRhinoCommand.result.success);
        }
Example #41
0
        /// <summary>
        /// Calling this method is identical to calling the ShowDialog method of the provided
        /// FolderBrowserDialog, except that an attempt will be made to scroll the Tree View
        /// to make the currently selected folder visible in the dialog window.
        /// </summary>
        /// <param name="dlg"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        private static bool?ShowFolderBrowser(FormsFolderBrowserDialog dlg, Window owner = null)
        {
            DialogResult result  = DialogResult.Cancel;
            int          retries = 40;
            NativeWindow parent  = null;

            if (owner != null)
            {
                parent = new NativeWindow();
                parent.AssignHandle(new WindowInteropHelper(owner).Handle);
            }

            using (Timer t = new Timer()) {
                t.Tick += (s, a) => {
                    if (retries > 0)
                    {
                        --retries;
                        IntPtr hwndDlg = FindWindow((string)null, _topLevelSearchString);
                        if (hwndDlg != IntPtr.Zero)
                        {
                            IntPtr hwndFolderCtrl = GetDlgItem(hwndDlg, _dlgItemBrowseControl);
                            if (hwndFolderCtrl != IntPtr.Zero)
                            {
                                IntPtr hwndTV = GetDlgItem(hwndFolderCtrl, _dlgItemTreeView);

                                if (hwndTV != IntPtr.Zero)
                                {
                                    IntPtr item = SendMessage(hwndTV, (uint)TVM_GETNEXTITEM, new IntPtr(TVGN_CARET), IntPtr.Zero);
                                    if (item != IntPtr.Zero)
                                    {
                                        // Let's send this 40 times until we drill it into the folder browser's thick skull.
                                        // Otherwise it will just go back to the beginning.
                                        SendMessage(hwndTV, TVM_ENSUREVISIBLE, IntPtr.Zero, item);
                                        //retries = 0;
                                        //t.Stop();
                                    }
                                }
                            }
                        }
                    }

                    else
                    {
                        //
                        //  We failed to find the Tree View control.
                        //
                        //  As a fall back (and this is an UberUgly hack), we will send
                        //  some fake keystrokes to the application in an attempt to force
                        //  the Tree View to scroll to the selected item.
                        //
                        t.Stop();
                        //SendKeys.Send("{TAB}{TAB}{DOWN}{DOWN}{UP}{UP}");
                    }
                };

                t.Interval = 10;
                t.Start();

                result = dlg.ShowDialog(parent);
                // Very important, I've learned my lesson
                parent.ReleaseHandle();
            }

            return(result == DialogResult.OK);
        }
Example #42
0
        public static Project LoadProject(string path)
        {
            try
            {
                Project project = JsonConvert.DeserializeObject <Project>(File.ReadAllText(path));
                // when the project has been moved
                if (project.Path != path)
                {
                    project.Path = path;
                }

                if (!Directory.Exists(project.OutputFolder))
                {
                    WarningAlert.Show("Output folder not found.\nPlease specify an output folder.");
                    System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
                    DialogResult result = dialog.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        project.OutputFolder = dialog.SelectedPath;
                        SaveProjectTask   task       = new SaveProjectTask(project);
                        ProcessTaskDialog saveDialog = new ProcessTaskDialog(task, "Saving...");
                        saveDialog.ShowDialog();
                        if (saveDialog.TaskToExecute.IsCanceled)
                        {
                            throw new Exception("Could not save the project.");
                        }
                    }
                    else
                    {
                        throw new Exception("Invalid path.");
                    }
                }


                if (!Directory.Exists(project.OutputFolder))
                {
                    WarningAlert.Show("Project folder not found.\nPlease specify an output folder.");
                    System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
                    DialogResult result = dialog.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        project.ProjectFolder = dialog.SelectedPath;
                        SaveProjectTask   task       = new SaveProjectTask(project);
                        ProcessTaskDialog saveDialog = new ProcessTaskDialog(task, "Saving...");
                        saveDialog.ShowDialog();
                        if (saveDialog.TaskToExecute.IsCanceled)
                        {
                            throw new Exception("Could not save the project.");
                        }
                    }
                    else
                    {
                        throw new Exception("Invalid path.");
                    }
                }
                return(JsonConvert.DeserializeObject <Project>(File.ReadAllText(path)));
            }
            catch (Exception ex)
            {
                ErrorAlert.Show("Could not load project:\n" + ex.Message);
            }
            return(null);
        }
Example #43
0
 private void btnBrowseFolder_Click(object sender, System.EventArgs e)
 {
     folderBrowserDialog1.ShowDialog();
     txtOutputFolder.Text = folderBrowserDialog1.SelectedPath;
 }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            #region Console/List Button Styling
            List <Button> toggleButtons = new List <Button>()
            {
                NetworkConsoleButton, DebugConsoleButton, WorldGenConsoleButton, PlayerListButton, AdminButton, PermittedButton, BannedButton
            };

            if (toggleButtons.Contains(sender))
            {
                var accentBrush = (Brush)FindResource("MahApps.Brushes.Accent");
                var textBrush   = (Brush)FindResource("MahApps.Brushes.Text");

                foreach (Button button in toggleButtons)
                {
                    if (sender == button)
                    {
                        button.Foreground      = accentBrush;
                        button.BorderBrush     = accentBrush;
                        button.BorderThickness = new Thickness(1);
                    }
                    else
                    {
                        button.Foreground      = textBrush;
                        button.BorderBrush     = null;
                        button.BorderThickness = new Thickness(0);
                    }
                }
            }
            #endregion

            #region List Buttons
            if (sender == AdminButton)
            {
                LeTransit.Content = adminView;
            }
            if (sender == PermittedButton)
            {
                LeTransit.Content = permittedView;
            }
            if (sender == BannedButton)
            {
                LeTransit.Content = bannedView;
            }
            if (sender == PlayerListButton)
            {
                LeTransit.Content = playerView;
            }
            #endregion

            #region Console Buttons
            if (sender == NetworkConsoleButton)
            {
                LeTransit.Content = networkConsole;
                currentConsole    = Enums.ConsoleType.Network;
                ClearBadgeForButton(NetworkConsoleButton);
                return;
            }
            if (sender == DebugConsoleButton)
            {
                LeTransit.Content = debugConsole;
                currentConsole    = Enums.ConsoleType.Debug;
                ClearBadgeForButton(DebugConsoleButton);
                return;
            }
            if (sender == WorldGenConsoleButton)
            {
                LeTransit.Content = worldConsole;
                currentConsole    = Enums.ConsoleType.WorldGen;
                ClearBadgeForButton(WorldGenConsoleButton);
                return;
            }
            #endregion

            #region Setting Tab Buttons
            if (sender == SteamButton)
            {
                if (SteamManager.SteamCMD.GetSteamCMDState() != SteamManager.SteamCMD.SteamCMDState.Installed)
                {
                    SteamManager.SteamCMD.DownloadAndInstall();
                }
                //else
                // TODO: Uninstall SteamCMD?
            }

            if (sender == SteamUpdate)
            {
                if (ValheimServer.ValidatePath(workingDirectory))
                {
                    var version = SteamManager.Server.GetVersion(workingDirectory);
                    var latest  = SteamManager.Server.GetLatestVersion();

                    if (version == latest)
                    {
                        MessageBox.Show("Latest version is already installed, not update necessary.", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        MessageBoxResult mbr = MessageBox.Show("Update Available!", "Update?", MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (mbr == MessageBoxResult.Yes)
                        {
                            await SteamManager.Server.UpdateValdiate(workingDirectory);
                        }
                        else
                        {
                            return;
                        }
                    }
                }
            }
            #endregion

            if (sender == ServerDirButton)
            {
                using (WinForms.FolderBrowserDialog fbd = new WinForms.FolderBrowserDialog())
                {
                    fbd.RootFolder          = Environment.SpecialFolder.MyComputer;
                    fbd.ShowNewFolderButton = true;
                    fbd.Description         = "Browse to the Valheim Dedicated Server directory";

                    if (fbd.ShowDialog() == WinForms.DialogResult.OK)
                    {
                        string path = fbd.SelectedPath;
                        if (!String.IsNullOrWhiteSpace(path))
                        {
                            // Make sure the directory exists
                            if (Directory.Exists(path) && ValheimManager.IsValidServerDirectory(path))
                            {
                                // Save the location
                                ServerDirTextBox.Text       = path;
                                workingDirectory            = path;
                                Settings.Default.ServerPath = path;
                                Settings.Default.Save();

                                UpdateWorlds();
                            }
                            else
                            {
                                if (!ValheimManager.IsValidServerDirectory(path))
                                {
                                    MessageBox.Show("Specified directory does not seem to be a valid directory! Make sure you're choosing the folder containing the Valheim server files.", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                                }
                                else
                                {
                                    MessageBox.Show("Specified directory does not seem to Exist!", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                                }
                            }
                        }
                    }
                    else
                    {
                        // User cancelled
                    }
                }
            }
            if (sender == SaveDirButton)
            {
                using (WinForms.FolderBrowserDialog fbd = new WinForms.FolderBrowserDialog())
                {
                    fbd.RootFolder          = Environment.SpecialFolder.MyComputer;
                    fbd.ShowNewFolderButton = true;
                    fbd.Description         = "Choose a Directory";

                    if (fbd.ShowDialog() == WinForms.DialogResult.OK)
                    {
                        string path = fbd.SelectedPath;
                        if (Directory.Exists(path))
                        {
                            SaveDirTextBox.Text       = path;
                            saveDirectory             = path;
                            Settings.Default.SavePath = path;
                            Settings.Default.Save();

                            UpdateWorlds();
                        }
                    }
                    else
                    {
                        // User cancelled
                    }
                }
            }
            if (sender == StartButton)
            {
                if (!String.IsNullOrWhiteSpace(workingDirectory) && File.Exists(Path.Combine(workingDirectory, "valheim_server.exe")))
                {
                    if (!ValheimServer.IsServerRunning())
                    {
                        // Check all parameters before we start the serveroni
                        await ValheimServer.StartAsync(new ValheimServer.ServerSettings {
                            ServerPath     = Path.Combine(workingDirectory, "valheim_server.exe"),
                            ServerName     = ServerNameTextBox.Text,
                            ServerPassword = ServerPasswordTextBox.Password,
                            ServerPort     = (int)ServerPortNUD.Value,
                            SaveDirectory  = null,
                            WorldName      = WorldNameTextBox.Text
                        });
                    }
                    else
                    {
                        if (MessageBox.Show("Are you sure you wish to stop the server?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                        {
                            ValheimServer.Stop();
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Error, unable to locate valheim_server.exe!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            if (sender == CreateTaskButton)
            {
                Scheduling.TaskWindow window = new Scheduling.TaskWindow();
                window.Owner = this;
                bool dr = window.ShowDialog().GetValueOrDefault();

                if (dr)
                {
                }
            }
        }
Example #45
0
        private static void SetupSpaceEngInstallAlias()
        {
            string spaceEngineersDirectory = null;

            // TODO look at Steam/config/Config.VDF?  Has alternate directories.
            var steamDir =
                Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Valve\\Steam", "SteamPath", null) as string;

            if (steamDir != null)
            {
                spaceEngineersDirectory = Path.Combine(steamDir, _steamSpaceEngineersDirectory);
                // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                if (File.Exists(Path.Combine(spaceEngineersDirectory, _spaceEngineersVerifyFile)))
                {
                    _log.Debug("Found Space Engineers in {0}", spaceEngineersDirectory);
                }
                else
                {
                    _log.Debug("Couldn't find Space Engineers in {0}", spaceEngineersDirectory);
                }
            }
            if (spaceEngineersDirectory == null)
            {
                var dialog = new System.Windows.Forms.FolderBrowserDialog
                {
                    Description = "Please select the SpaceEngineers installation folder"
                };
                do
                {
                    if (dialog.ShowDialog() != DialogResult.OK)
                    {
                        var ex = new FileNotFoundException("Unable to find the Space Engineers install directory, aborting");
                        _log.Fatal(ex);
                        LogManager.Flush();
                        throw ex;
                    }
                    spaceEngineersDirectory = dialog.SelectedPath;
                    if (File.Exists(Path.Combine(spaceEngineersDirectory, _spaceEngineersVerifyFile)))
                    {
                        break;
                    }
                    if (MessageBox.Show(
                            $"Unable to find {0} in {1}.  Are you sure it's the Space Engineers install directory?",
                            "Invalid Space Engineers Directory", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        break;
                    }
                } while (true);  // Repeat until they confirm.
            }
            if (!JunctionLink(SpaceEngineersInstallAlias, spaceEngineersDirectory))
            {
                var ex = new IOException($"Failed to create junction link {SpaceEngineersInstallAlias} => {spaceEngineersDirectory}. Aborting.");
                _log.Fatal(ex);
                LogManager.Flush();
                throw ex;
            }
            string junctionVerify = Path.Combine(SpaceEngineersInstallAlias, _spaceEngineersVerifyFile);

            if (!File.Exists(junctionVerify))
            {
                var ex = new FileNotFoundException($"Junction link is not working.  File {junctionVerify} does not exist");
                _log.Fatal(ex);
                LogManager.Flush();
                throw ex;
            }
        }
        /// <summary>
        /// 将选中的文件导出到指定文件夹
        /// </summary>
        private void ExportToDisk()
        {
            WinForm.FolderBrowserDialog InfoNodeDialog = null;
            String SavePath             = "";
            String SaveFileNameWithPath = "";
            String SaveFileName         = "";

            byte[] fileContent = null;
            if (dgFiles.SelectedItems.Count > 0)
            {
                var fileInfo = dgFiles.SelectedItems[0] as DBFileInfo;
                //设置要导出的文件夹
                InfoNodeDialog             = new WinForm.FolderBrowserDialog();
                InfoNodeDialog.Description = "选择用于保存文件的文件夹";
                SavePath = System.IO.Path.GetDirectoryName(fileInfo.FilePath);
                //提取用户选择的第一个文件路径,如果其存在,则将其作为保存导出文件的文件夹
                //如果不存在,导出到"我的文档"文件夹
                if (System.IO.Directory.Exists(SavePath))
                {
                    InfoNodeDialog.SelectedPath = SavePath;
                }
                else
                {
                    InfoNodeDialog.RootFolder = Environment.SpecialFolder.MyDocuments;
                }

                if (InfoNodeDialog.ShowDialog() == WinForm.DialogResult.OK)
                {
                    SavePath = InfoNodeDialog.SelectedPath;
                    try
                    {
                        int exportedFiles = 0;
                        //循环导出所有文件。
                        foreach (DBFileInfo dbFile in dgFiles.SelectedItems)
                        {
                            SaveFileName         = System.IO.Path.GetFileName(dbFile.FilePath);
                            SaveFileNameWithPath = SavePath + "\\" + SaveFileName;
                            fileContent          = accessObj.getFileContent(fileInfo.ID);
                            if (fileContent != null)
                            {
                                File.WriteAllBytes(SaveFileNameWithPath, fileContent);
                            }
                            exportedFiles++;
                            //在主窗体上显示相关信息
                            if (_dataObject.MainWindow != null)
                            {
                                _dataObject.MainWindow.ShowInfo("正在导出" + SaveFileName);
                            }
                        }
                    }
                    catch (IOException)
                    {
                        //忽略不能导出的文件(比如正在尝试覆盖的文件正在使用中,不能被覆盖)
                    }
                    //导出结束
                    String info = string.Format("文件导出结束,共导出{0}个文件到{1}", dgFiles.SelectedItems.Count, SavePath);

                    if (_dataObject.MainWindow != null)
                    {
                        _dataObject.MainWindow.ShowInfo(info);
                    }
                    //自动在Explorer中打开文件夹
                    Process.Start(SavePath);
                }
            }
        }
        public static string findSims3Root()
        {
            //string path32 = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{C05D8CDB-417D-4335-A38C-A0659EDFD6B8}";
            //string path64 = "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{C05D8CDB-417D-4335-A38C-A0659EDFD6B8}"

            if (sims3root != "")
            {
                //Console.WriteLine("Returning already stored path");
                return(sims3root);
            }

            string installLocation = "";

            try
            {
                //Console.WriteLine("Attempting to get path from common registry...");
                installLocation = Helpers.getCommonRegistryValue("sims3root");
                if (!String.IsNullOrEmpty(installLocation))
                {
                    // Check install location just in case...
                    try
                    {
                        if (File.Exists(Path.Combine(installLocation, Helpers.getGameSubPath("\\GameData\\Shared\\Packages\\FullBuild0.package"))))
                        {
                            //Helpers.saveCommonRegistryValue("sims3root", installLocation);
                            sims3root = installLocation;
                            return(installLocation);
                        }
                    }
                    catch (DirectoryNotFoundException dex)
                    {
                    }
                    catch (FileNotFoundException fex)
                    {
                    }
                }

                //Console.WriteLine("Attempting to get path from registry...");
                string path32 = "Software\\Sims\\The Sims 3";
                string path64 = "Software\\Wow6432Node\\Sims\\The Sims 3";

                string path32Alt = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{C05D8CDB-417D-4335-A38C-A0659EDFD6B8}";
                string path64Alt = "Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{C05D8CDB-417D-4335-A38C-A0659EDFD6B8}";

                RegistryKey key;
                key = Registry.LocalMachine.OpenSubKey(path32, false);
                if (key == null)
                {
                    // Try Alt location
                    key = Registry.LocalMachine.OpenSubKey(path32Alt, false);
                    if (key == null)
                    {
                        // No Key exists... check 64 bit location
                        key = Registry.LocalMachine.OpenSubKey(path64, false);
                        if (key == null)
                        {
                            key = Registry.LocalMachine.OpenSubKey(path64Alt, false);
                            if (key == null)
                            {
                                // Can't find Sims 3 root - uh oh!
                                key.Close();
                                return("");
                            }
                        }
                    }
                }
                installLocation = key.GetValue("Install Dir").ToString();
                key.Close();
            }
            catch (Exception)
            {
                //MessageBox.Show(e.Message);
            }

            // Check to see if FullBuild0.package exists within this root
            bool getManualPath = false;

            if (!String.IsNullOrEmpty(installLocation))
            {
                try
                {
                    if (File.Exists(Path.Combine(installLocation, Helpers.getGameSubPath("\\GameData\\Shared\\Packages\\FullBuild0.package"))))
                    {
                        Helpers.saveCommonRegistryValue("sims3root", installLocation);
                        sims3root = installLocation;
                        return(installLocation);
                    }
                    else
                    {
                        // No FullBuild0 found, have to get a manual path
                        getManualPath = true;
                    }
                }
                catch (DirectoryNotFoundException dex)
                {
                    getManualPath = true;
                }
                catch (FileNotFoundException fex)
                {
                    getManualPath = true;
                }
            }
            else
            {
                getManualPath = true;
            }

            if (getManualPath)
            {
                getManualPath = false;

                // Check for existance of XML file in the Application.Startup folder - this can be used to override
                // paths where none can be found (ie on Macs)
                if (File.Exists(Path.Combine(Application.StartupPath, "pathOverrides.xml")))
                {
                    Stream        xmlStream = File.OpenRead(Path.Combine(Application.StartupPath, "pathOverrides.xml"));
                    XmlTextReader xtr       = new XmlTextReader(xmlStream);

                    while (xtr.Read())
                    {
                        if (xtr.NodeType == XmlNodeType.Element)
                        {
                            switch (xtr.Name)
                            {
                            case "path":
                                xtr.MoveToAttribute("name");
                                switch (xtr.Value)
                                {
                                case "sims3root":
                                    installLocation = xtr.GetAttribute("location");
                                    break;
                                }
                                break;
                            }
                        }
                    }

                    xtr.Close();
                    xmlStream.Close();

                    if (!String.IsNullOrEmpty(installLocation))
                    {
                        try
                        {
                            if (File.Exists(Path.Combine(installLocation, Helpers.getGameSubPath("\\GameData\\Shared\\Packages\\FullBuild0.package"))))
                            {
                                Helpers.saveCommonRegistryValue("sims3root", installLocation);
                                sims3root = installLocation;
                                return(installLocation);
                            }
                        }
                        catch (DirectoryNotFoundException dex)
                        {
                            getManualPath = true;
                        }
                        catch (FileNotFoundException fex)
                        {
                            getManualPath = true;
                        }
                    }
                }

                // If we got to this point we have to show a dialog to the user asking them where to find the sims3root

                System.Windows.Forms.FolderBrowserDialog fBrowse = new System.Windows.Forms.FolderBrowserDialog();
                fBrowse.Description  = @"Please find your Sims 3 root (usually C:\Program Files\Electronic Arts\The Sims 3\) ";
                fBrowse.Description += "NOTE: This is NOT where your Sims3.exe file is!";
                if (fBrowse.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (fBrowse.SelectedPath != "")
                    {
                        try
                        {
                            if (File.Exists(Path.Combine(fBrowse.SelectedPath, Helpers.getGameSubPath("\\GameData\\Shared\\Packages\\FullBuild0.package"))))
                            {
                                Helpers.saveCommonRegistryValue("sims3root", fBrowse.SelectedPath);
                                sims3root = fBrowse.SelectedPath;
                                return(fBrowse.SelectedPath);
                            }
                            else
                            {
                                return("");
                            }
                        }
                        catch (DirectoryNotFoundException dex)
                        {
                            getManualPath = true;
                        }
                        catch (FileNotFoundException fex)
                        {
                            getManualPath = true;
                        }
                    }
                }
            }

            sims3root = installLocation;
            return(installLocation);
        }
 //Click Event Handler for 'Destination Folder' button click
 private void DestinationFolder_Click(object sender, RoutedEventArgs e)
 {
     System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
     DialogResult dialogResult = folderBrowserDialog.ShowDialog();
 }
Example #49
0
        private void btnExportGCode_Click(object sender, EventArgs e)
        {
            List <SettingsObject> settingsOutput = generateSettingsOutput();

            if (formSettings != null)
            {
                foreach (List <SettingsObject> x in formSettings)
                {
                    if (x != null)
                    {
                        foreach (SettingsObject y in x)
                        {
                            settingsOutput.Add(y);
                        }
                    }
                }
            }

            foreach (SettingsObject x in settingsOutput)
            {
                int indexFound = configDefaults.FindIndex(str => str.Contains(x.get_gSO()));


                if (indexFound != -1)
                {
                    //settings_blah = 10%
                    int indexLength = configDefaults[indexFound].IndexOf('=');

                    Console.WriteLine(indexFound + " " + indexLength + " " + configDefaults[indexFound]);

                    configDefaults[indexFound] = configDefaults[indexFound].Substring(0, indexLength + 1) + " " + x.get_config_Value();
                }
                else
                {
                    Console.WriteLine("Index not found for " + x.get_gSO());
                }
            }
            // Console.WriteLine($"Current Directory is '{Environment.CurrentDirectory}'"); debug - Alex
            string docPath = (@"..\\..\\..\\..\\ToolpathGen\\resource");

            // Write the string array to a new file
            using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "config.ini")))
            {
                foreach (string line in configDefaults)
                {
                    outputFile.WriteLine(line);
                }
            }

            // Promt user for G-code file deposit directory
            String filePath = "";
            var    dialog   = new System.Windows.Forms.FolderBrowserDialog();

            dialog.Description = "Choose G-code deposit directory";
            FORMS.DialogResult result = dialog.ShowDialog();
            if (result == FORMS.DialogResult.OK)
            {
                filePath = dialog.SelectedPath;
            }
            int length = filePath.Length;

            char[] filePathArray = new char[length];
            for (int i = 0; i < filePath.Length; i++)
            {
                filePathArray[i] = filePath[i];
            }
            filePath += "\\";


            // Write data to file, then call slicing algorithm/toolpath
            try
            {
                ((UserControl1)elementHost1.Child).writeData();

                System.Diagnostics.Process.Start("..\\..\\..\\..\\ToolpathGen\\Debug\\ToolpathGen.exe", filePath);
            }
            catch
            {
                MessageBox.Show("Try loading in an .stl file before exporting g-code.");
            }
        }
Example #50
0
 private void btnBrowse_Click(object sender, System.EventArgs e)
 {
     folderBrowserDialog1.ShowDialog();
     FilePath.Text  = folderBrowserDialog1.SelectedPath;
     FilePath.Text += @"\ACMS_Back_db.mdf";
 }
Example #51
0
 private void btnFrom_Click(object sender, System.EventArgs e)
 {
     fldFrom.SelectedPath = txtFrom.Text;
     fldFrom.ShowDialog();
     txtFrom.Text = fldFrom.SelectedPath;
 }
Example #52
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            FolderBrowserDialog fbgRootDir;
            SaveFileDialog      fdCSVPath;
            DirectoryInfo       rootDirInfo;


            fbgRootDir = new System.Windows.Forms.FolderBrowserDialog();
            // Set the help text description for the FolderBrowserDialog.
            fbgRootDir.Description =
                "Select the root folder that you want to traverse.";
            // Do not allow the user to create new files via the FolderBrowserDialog.
            fbgRootDir.ShowNewFolderButton = false;
            // Default to the My Computer folder.
            fbgRootDir.RootFolder = Environment.SpecialFolder.MyComputer;


            fdCSVPath              = new System.Windows.Forms.SaveFileDialog();
            fdCSVPath.DefaultExt   = "csv";
            fdCSVPath.Filter       = "Comma-separated files (*.csv)|*.csv";
            fdCSVPath.AddExtension = true;
            fdCSVPath.Title        = "Select the location of the output logs";

            DialogResult result = fbgRootDir.ShowDialog();

            if (result == DialogResult.OK)
            {
                fdCSVPath.InitialDirectory = fbgRootDir.SelectedPath;
                if (fdCSVPath.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (File.Exists(fdCSVPath.FileName))
                        {
                            File.Delete(fdCSVPath.FileName);
                        }
                        rootDirInfo = new DirectoryInfo(fbgRootDir.SelectedPath);

                        using (System.IO.StreamWriter file = new System.IO.StreamWriter(fdCSVPath.FileName, true))
                        {
                            file.WriteLine(DateTime.Now);
                            //file.WriteLine("\"File Name\",\"Version\",\"Is Central\",\"Central File Name\",\"Link Type\",\"Path\",\"Absolute Path\"");
                            file.WriteLine("\"File Name\",\"Version\",\"Is Central\",\"Central File Name\"");
                        }

                        //using (System.IO.StreamWriter file = new System.IO.StreamWriter(rootDirInfo.FullName + "\\DesignFiles_AutoCADFiles.csv", true))
                        //{
                        //    file.WriteLine(DateTime.Now);
                        //    file.WriteLine("\"File Name\",\"Version\"");
                        //}

                        ProcessFolder(rootDirInfo, fdCSVPath.FileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace, "Error getting file information",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                }
            }
        }
Example #53
0
        private void buttonMediaDirectory_Click(object sender, System.EventArgs e)
        {
            mediaDirectoryBrowserDialog.Description = "Select the directory contains media files:";
            if (mediaDirectoryBrowserDialog.ShowDialog(this) == DialogResult.OK)
            {
                DirectoryInfo theDirectoryInfo = new DirectoryInfo(this.mediaDirectoryBrowserDialog.SelectedPath);
                FileInfo[]    dcmFiles         = null;
                if (theDirectoryInfo != null)
                {
                    // Get all the subdirectories
                    FileSystemInfo[] infos       = theDirectoryInfo.GetFileSystemInfos();
                    ArrayList        allDCMFiles = new ArrayList();
                    foreach (FileSystemInfo f in infos)
                    {
                        if (f is DirectoryInfo)
                        {
                            // Get all the files in a specific directory
                            FileInfo[] dcmFilesInSubDir = ((DirectoryInfo)f).GetFiles();
                            if (dcmFilesInSubDir.Length != 0)
                            {
                                foreach (FileInfo fileNext in dcmFilesInSubDir)
                                {
                                    if ((fileNext.Extension.ToLower() == ".dcm") || (fileNext.Extension == null) || (fileNext.Extension == ""))
                                    {
                                        allDCMFiles.Add(fileNext);
                                    }
                                }
                            }
                        }
                        else if (f is FileInfo)
                        {
                            if ((f.Extension.ToLower() == ".dcm") || (f.Extension == null) || (f.Extension == ""))
                            {
                                allDCMFiles.Add(f);
                            }
                        }
                    }

                    dcmFiles = (FileInfo[])allDCMFiles.ToArray(typeof(FileInfo));
                    allDCMFiles.Clear();
                }

                if (dcmFiles.Length != 0)
                {
                    string[] filesToSend = new string[dcmFiles.Length];

                    for (int i = 0; i < dcmFiles.Length; i++)
                    {
                        filesToSend[i] = dcmFiles[i].FullName;
                    }

                    System.IAsyncResult ar =
                        _EmulatorSession.EmulatorSessionImplementation.BeginEmulateStorageSCU(
                            filesToSend,
                            this.RadioButtonMultAssoc.Checked,
                            this.CheckBoxValidateOnImport.Checked,
                            this.CheckBoxNewStudy.Checked,
                            Convert.ToUInt16(this.NummericRepeat.Value),
                            _StorageScuAsyncCallback);

                    // Close this form.
                    _SendButtonClicked = true;
                    Close();
                }
                else
                {
                    string msg =
                        string.Format(
                            "The selected directory {0} doesn't contain any media file.\n Please select other directory.",
                            this.mediaDirectoryBrowserDialog.SelectedPath);
                    MessageBox.Show(msg, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }
Example #54
0
        /// <summary>
        /// Exports all elements in 3D View to separate .fbx files.
        /// </summary>
        public string Export(Autodesk.Revit.DB.Document document)
        {
            Autodesk.Revit.DB.Document doc        = document;
            Autodesk.Revit.DB.View     activeView = doc.ActiveView;

            FBXExportOptions options = new FBXExportOptions();

            if (activeView.ViewType != ViewType.ThreeD)
            {
                TaskDialog.Show("Warning", "Can only be run in 3D View.");
                return("Failed");
            }

            ElementOwnerViewFilter elementOwnerViewFilter =
                new ElementOwnerViewFilter(activeView.Id);

            FilteredElementCollector col
                = new FilteredElementCollector(doc, activeView.Id)
                  .WhereElementIsNotElementType();

            ICollection <ElementId> allAlements = col.ToElementIds();

            IList <Element> viewElements = col.ToElements();

            using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
            {
                if (folderDialog.ShowDialog() != DialogResult.OK)
                {
                    return("No folder chosen.");
                }

                string folder = folderDialog.SelectedPath;

                // Filtered element collector is iterable
                ViewSet viewSet = new ViewSet();

                int c = 0;

                foreach (Element e in col)
                {
                    using (Transaction tx = new Transaction(doc))
                    {
                        tx.Start(String.Format("Export element {0}", e.Id.ToString()));
                        activeView.IsolateElementTemporary(e.Id);
                        activeView.ConvertTemporaryHideIsolateToPermanent();
                        viewSet.Insert(activeView);

                        doc.Export(folder, e.Id.ToString(), viewSet, options);

                        activeView.UnhideElements(allAlements);
                        doc.Regenerate();
                        tx.Commit();
                    }

                    viewSet.Clear();
                    c++;
                }

                string runMessage = String.Format("Run {0} times", c);

                TaskDialog.Show("Result", runMessage);

                return(String.Format("Successfully exported {0} elements", c));
            }
        }
Example #55
0
        private void SelectRootFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var rootFolder = new System.Windows.Forms.FolderBrowserDialog();

            rootFolder.ShowDialog();
        }
Example #56
0
 private void Browse_Click(object sender, RoutedEventArgs e)
 {
     if (Model.isWorking)
     {
         test.Content = "Engine is working, please wait for a completion message to pop up";
         return;
     }
     using (var dialog = new System.Windows.Forms.FolderBrowserDialog()) { if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                                                                           {
                                                                               path = dialog.SelectedPath;
                                                                           }
     }
 }
Example #57
0
        private void buttonScanFile_Click(object sender, EventArgs e)
        {
            string root       = Environment.CurrentDirectory.ToString();
            string selectPath = "";

            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.SelectedPath = root;
            dialog.Description  = "请选择Txt所在文件夹";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show(this, "文件夹路径不能为空", "提示");
                    return;
                }
            }
            else
            {
                return;
            }
            listViewFileList.Items.Clear();
            listViewFileList.Update();

            selectPath = dialog.SelectedPath;
            itemName   = selectPath.Substring(selectPath.LastIndexOf(@"\") + 1);
            ReadConfig(itemName + "_UpdateVersion.xml");
            this.Text = packetText + "    " + selectPath;

            ArrayList arr    = FileAccessHelper.GetAllFileName(selectPath);
            bool      update = false;

            verModle.PubNumber = (Convert.ToInt32(verModle.PubNumber) + 1).ToString();
            foreach (var item in arr)
            {
                ListViewItem lvi     = new ListViewItem();
                string       stritem = item.ToString().Substring(root.Length, item.ToString().Length - root.Length);
                if (!verModle.fileDic.ContainsKey(stritem.ToString()))
                {
                    FileDetails file = new FileDetails();
                    file.lastime   = FileAccessHelper.GetFileUpdateTime(root + stritem.ToString());
                    file.version   = "1";
                    file.pubnumber = verModle.PubNumber;
                    verModle.fileDic[stritem.ToString()] = file;
                    if (!update)
                    {
                        verModle.LastTime = DateTime.Now.ToString();
                        verModle.Version  = (Convert.ToInt32(verModle.Version) + 1).ToString();
                        update            = true;
                    }
                    lvi.BackColor = Color.Pink;
                }
                else
                {
                    string lasttime = FileAccessHelper.GetFileUpdateTime(root + stritem.ToString());
                    verModle.fileDic[stritem.ToString()].pubnumber = verModle.PubNumber;
                    if (verModle.fileDic[stritem.ToString()].lastime != lasttime)
                    {
                        verModle.fileDic[stritem.ToString()].version = (Convert.ToInt32(verModle.fileDic[stritem.ToString()].version) + 1).ToString();
                        verModle.fileDic[stritem.ToString()].lastime = lasttime;
                        if (!update)
                        {
                            verModle.LastTime = DateTime.Now.ToString();
                            verModle.Version  = (Convert.ToInt32(verModle.Version) + 1).ToString();
                            update            = true;
                        }
                        lvi.BackColor = Color.Pink;
                    }
                }

                lvi.Text = stritem.ToString();
                lvi.SubItems.Add(verModle.fileDic[stritem.ToString()].version);
                lvi.SubItems.Add(verModle.fileDic[stritem.ToString()].lastime);
                listViewFileList.Items.Add(lvi);
            }
        }
Example #58
0
        /// <summary>
        /// Function Which gets Called on Loading the Plug-In
        /// </summary>
        /// <param name="p">Parameters</param>
        public void Loaded(ViewLoadedParams p)
        {
            BDmenuItem = new MenuItem {
                Header = "Beyond Dynamo"
            };
            DynamoViewModel VM = p.DynamoWindow.DataContext as DynamoViewModel;

            BeyondDynamo.Utils.DynamoWindow = p.DynamoWindow;

            Utils.DynamoVM = VM;
            Utils.LogMessage("Loading Menu Items Started...");

            Utils.LogMessage("Loading Menu Items: Latest Version Started...");
            LatestVersion = new MenuItem {
                Header = "New version available! Download now!"
            };
            LatestVersion.Click += (sender, args) =>
            {
                System.Diagnostics.Process.Start("www.github.com/JoelvanHerwaarden/BeyondDynamo2.X/releases");
            };
            if (this.currentVersion < this.latestVersion)
            {
                BDmenuItem.Items.Add(LatestVersion);
            }
            else
            {
                Utils.LogMessage("Loading Menu Items: Latest Version is installed");
            }

            Utils.LogMessage("Loading Menu Items: Latest Version Completed");

            #region THIS CAN BE RUN ANYTIME

            Utils.LogMessage("Loading Menu Items: Chang Node Colors Started...");
            ChangeNodeColors = new MenuItem {
                Header = "Change Node Color"
            };
            ChangeNodeColors.Click += (sender, args) =>
            {
                //Get the current Node Color Template
                System.Windows.ResourceDictionary dynamoUI = Dynamo.UI.SharedDictionaryManager.DynamoColorsAndBrushesDictionary;

                //Initiate a new Change Node Color Window
                ChangeNodeColorsWindow colorWindow = new ChangeNodeColorsWindow(dynamoUI, config)
                {
                    // Set the owner of the window to the Dynamo window.
                    Owner = BeyondDynamo.Utils.DynamoWindow
                };
                colorWindow.Left = colorWindow.Owner.Left + 400;
                colorWindow.Top  = colorWindow.Owner.Top + 200;

                //Show the Color window
                colorWindow.Show();
            };
            ChangeNodeColors.ToolTip = new ToolTip()
            {
                Content = "This lets you change the Node Color Settings in your Dynamo nodes in In-Active, Active, Warning and Error state"
            };

            Utils.LogMessage("Loading Menu Items: Batch Remove Trace Data Started...");
            BatchRemoveTraceData = new MenuItem {
                Header = "Remove Session Trace Data from Dynamo Graphs"
            };
            BatchRemoveTraceData.Click += (sender, args) =>
            {
                //Make a ViewModel for the Remove Trace Data window

                //Initiate a new Remove Trace Data window
                RemoveTraceDataWindow window = new RemoveTraceDataWindow()
                {
                    Owner     = p.DynamoWindow,
                    viewModel = VM
                };
                window.Left = window.Owner.Left + 400;
                window.Top  = window.Owner.Top + 200;

                //Show the window
                window.Show();
            };
            BatchRemoveTraceData.ToolTip = new ToolTip()
            {
                Content = "Removes the Session Trace Data / Bindings from muliple Dynamo scripts in a given Directory" +
                          "\n" +
                          "\nSession Trace Data / Bindings is the trace data binding with the current Revit model and elements." +
                          "\nIt can slow your scripts down if you run them because it first tries the regain the last session in which it was used."
            };

            Utils.LogMessage("Loading Menu Items: Order Player Nodes Started...");
            OrderPlayerInput = new MenuItem {
                Header = "Order Input/Output Nodes"
            };
            OrderPlayerInput.Click += (sender, args) =>
            {
                //Open a FileBrowser Dialog so the user can select a Dynamo Graph
                System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog();
                fileDialog.Filter = "Dynamo Files (*.dyn)|*.dyn";
                if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    if (BeyondDynamoFunctions.IsFileOpen(VM, fileDialog.FileName))
                    {
                        Forms.MessageBox.Show("Please close the file before using this command", "Order Input/Output Nodes");
                        return;
                    }
                    //Get the selected filePath
                    string DynamoFilepath = fileDialog.FileName;
                    string DynamoString   = File.ReadAllText(DynamoFilepath);
                    if (DynamoString.StartsWith("<"))
                    {
                        //Call the SortInputNodes Function
                        BeyondDynamoFunctions.SortInputOutputNodesXML(fileDialog.FileName);
                    }
                    else if (DynamoString.StartsWith("{"))
                    {
                        //Call the SortInputNodes Function
                        BeyondDynamoFunctions.SortInputOutputNodesJson(fileDialog.FileName);
                    }
                    else
                    {
                        return;
                    }
                }
            };
            OrderPlayerInput.ToolTip = new ToolTip()
            {
                Content = "Select a Dynamo file and it will let you sort the Nodes marked as 'Input'' & Output'" +
                          "\n" +
                          "\n Only Watch nodes which are marked as Output are displayed in the Dynamo Player. " +
                          "\nOther nodes will show up in Refinery"
            };

            Utils.LogMessage("Loading Menu Items: Player Scripts Started...");
            PlayerScripts = new MenuItem {
                Header = "Player Graphs"
            };
            OpenPlayerPath = new MenuItem {
                Header = "Open Player Path"
            };
            OpenPlayerPath.Click += (sender, args) =>
            {
                System.Diagnostics.Process.Start(this.config.playerPath);
            };

            SetPlayerPath = new MenuItem {
                Header = "Set Player Path"
            };
            List <MenuItem> extraMenuItems = new List <MenuItem> {
                SetPlayerPath, OpenPlayerPath
            };
            SetPlayerPath.Click += (sender, args) =>
            {
                Forms.FolderBrowserDialog browserDialog = new Forms.FolderBrowserDialog();
                if (this.config.playerPath != null)
                {
                    browserDialog.SelectedPath = this.config.playerPath;
                }
                if (browserDialog.ShowDialog() == Forms.DialogResult.OK)
                {
                    if (browserDialog.SelectedPath != null)
                    {
                        PlayerScripts.Items.Clear();
                        BeyondDynamoFunctions.RetrievePlayerFiles(PlayerScripts, VM, browserDialog.SelectedPath, extraMenuItems);
                        this.config.playerPath = browserDialog.SelectedPath;
                    }
                }
            };
            Utils.LogMessage("Playerpath = " + this.config.playerPath);
            if (this.config.playerPath != null | this.config.playerPath != string.Empty)
            {
                try
                {
                    if (Directory.Exists(Path.GetDirectoryName(this.config.playerPath)))
                    {
                        BeyondDynamoFunctions.RetrievePlayerFiles(PlayerScripts, VM, this.config.playerPath, extraMenuItems);
                    }
                }
                catch (Exception e)
                {
                    Utils.LogMessage("Loading Player Path Warning: " + e.Message);
                    PlayerScripts.Items.Add(SetPlayerPath);
                }
            }
            else
            {
                PlayerScripts.Items.Add(SetPlayerPath);
            }

            //BDmenuItem.Items.Add(ChangeNodeColors);
            //Utils.LogMessage("Loading Menu Items: Chang Node Colors Completed");
            //BDmenuItem.Items.Add(BatchRemoveTraceData);
            //Utils.LogMessage("Loading Menu Items: Batch Remove Trace Data Completed");
            BDmenuItem.Items.Add(OrderPlayerInput);
            Utils.LogMessage("Loading Menu Items: Order Player Nodes Completed");
            BDmenuItem.Items.Add(PlayerScripts);
            Utils.LogMessage("Loading Menu Items: Player Scripts Completed");

            BDmenuItem.Items.Add(new Separator());
            BDmenuItem.Items.Add(new Separator());
            #endregion

            # region THESE FUNCTION ONLY WORK INSIDE A SCRIPT
Example #59
0
        private async void SelectDestinationFolder()
        {
            while (true)
            {
                var folderDialog = new WinForms.FolderBrowserDialog
                {
                    Description = @"Select Folder to use as destination location"
                };
                if (folderDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    break;
                }
                var directory = new DirectoryInfo(folderDialog.SelectedPath);
                if (directory.FullName == DestinationTextBox.Text)
                {
                    return;
                }
                if (
                    SourceLocationsComboBox.Items.OfType <ComboBoxItem>()
                    .Any(cbi => (string)cbi.ToolTip == directory.FullName))
                {
                    await this.ShowMessageAsync("Cannot add Folder", "Cannot add selected folder because it is contains in the source folders list.\nplease select deferent location and try again ", MessageDialogStyle.Affirmative, new MetroDialogSettings { AffirmativeButtonText = "OK" });

                    return;
                }
                if (!directory.Exists)
                {
                    try
                    {
                        directory.Create();
                        if (!directory.Exists)
                        {
                            throw new Exception("cannot create directory");
                        }
                    }
                    catch (Exception)
                    {
                        var result = await this.ShowMessageAsync("Cannot create the Directory.", "The selected folder dose not exists and cannot create it\nDo you want to try deferent location?", MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings { AffirmativeButtonText = "Yes", NegativeButtonText = "No" });

                        if (result == MessageDialogResult.Affirmative)
                        {
                            continue;
                        }
                        return;
                    }
                }
                var rushTestFile = new FileInfo(directory.FullName + "\\" + "rushTestFile.rush");
                try
                {
                    var stream = rushTestFile.Create();
                    stream.Close();

                    if (rushTestFile.Exists)
                    {
                        rushTestFile.Delete();
                    }
                    else
                    {
                        throw new Exception("cannot create file");
                    }
                }
                catch (Exception)
                {
                    var result = await this.ShowMessageAsync("specified location is not accessible.", "Cannot use this folder as the destination location.\nbecause this program cannot create or delete files on that location\nmake sure rush have read and write perditions on that folder", MessageDialogStyle.AffirmativeAndNegative, new MetroDialogSettings { AffirmativeButtonText = "Yes", NegativeButtonText = "No" });

                    if (result == MessageDialogResult.Affirmative)
                    {
                        continue;
                    }
                    return;
                }
                DestinationTextBox.Text = directory.FullName;
                break;
            }
        }
        private void saveAs_btn_Click(object sender, RoutedEventArgs e)
        {
            Random rd         = new Random();
            string nwfilename = @"\SurveyData" + rd.Next(5000) + ".csv";
            string newfile    = @"";

            Winforms.FolderBrowserDialog dialog = new Winforms.FolderBrowserDialog();
            Winforms.DialogResult        r      = dialog.ShowDialog();
            if (r == Winforms.DialogResult.OK)
            {
                newfile = dialog.SelectedPath + nwfilename;
            }

            try
            {
                FileStream f = new FileStream(newfile, FileMode.Create);
                try
                {
                    using (StreamWriter sw = new StreamWriter(f))
                    {
                        sw.WriteLine("Closed Loop Point Table");
                        sw.WriteLine("Stand Point,Target Point,Degree,Minute,Second,Distance,Diff Elev(Delta Z),East(X),North(Y),Elevation(Z),CW,CCW,World Angle,StartZ,E,N,Sum Distance,Differential to start pt(X),Differential to start pt(Y),Differential to start pt(Z),Total Differential From Start Pt");
                        #region start writing
                        for (int i = 0; i < closedpt_list.Count; i++)
                        {
                            if (i == 0)
                            {
                                sw.Write(closedpt_list[i].Standpt + ",");
                                sw.Write(closedpt_list[i].TargetPoint + ",");
                                sw.Write(closedpt_list[i].Degree + ",");
                                sw.Write(closedpt_list[i].Minute + ",");
                                sw.Write(closedpt_list[i].Second + ",");
                                sw.Write(closedpt_list[i].Distance + ",");
                                sw.Write(closedpt_list[i].DeltaZ + ",");
                                sw.Write(closedpt_list[i].X + ",");
                                sw.Write(closedpt_list[i].Y + ",");
                                sw.Write(closedpt_list[i].Z + ",");
                                sw.Write(closedpt_list[i].Cw + ",");
                                sw.Write(closedpt_list[i].Ccw + ",");
                                sw.Write(closedpt_list[i].WorldA + ",");
                                sw.Write(closedpt_list[i].StartZ + ",");
                                sw.Write(closedpt_list[i].E + ",");
                                sw.Write(closedpt_list[i].N + ",");
                                sw.Write(closedpt_list[i].Sum_distance + ",");
                                sw.Write(closedpt_list[i].Diff_x + ",");
                                sw.Write(closedpt_list[i].Diff_y + ",");
                                sw.Write(closedpt_list[i].Diff_z + ",");
                                sw.Write(totalDiffFromStartPoint.ToString());
                                sw.WriteLine();
                            }
                            else
                            {
                                sw.Write(closedpt_list[i].Standpt + ",");
                                sw.Write(closedpt_list[i].TargetPoint + ",");
                                sw.Write(closedpt_list[i].Degree + ",");
                                sw.Write(closedpt_list[i].Minute + ",");
                                sw.Write(closedpt_list[i].Second + ",");
                                sw.Write(closedpt_list[i].Distance + ",");
                                sw.Write(closedpt_list[i].DeltaZ + ",");
                                sw.Write(closedpt_list[i].X + ",");
                                sw.Write(closedpt_list[i].Y + ",");
                                sw.Write(closedpt_list[i].Z + ",");
                                sw.Write(closedpt_list[i].Cw + ",");
                                sw.Write(closedpt_list[i].Ccw + ",");
                                sw.Write(closedpt_list[i].WorldA + ",");
                                sw.Write(closedpt_list[i].StartZ + ",");
                                sw.Write(closedpt_list[i].E + ",");
                                sw.Write(closedpt_list[i].N + ",");
                                sw.Write(closedpt_list[i].Sum_distance + ",");
                                sw.Write(closedpt_list[i].Diff_x + ",");
                                sw.Write(closedpt_list[i].Diff_y + ",");
                                sw.Write(closedpt_list[i].Diff_z + ",");
                                sw.WriteLine();
                            }
                        }
                        #endregion

                        sw.WriteLine();
                        sw.WriteLine();
                        sw.WriteLine("Referent Point Table");
                        sw.WriteLine("Stand Point,Target Point,Degree,Minute,Second,Distance,Diff Elev(Delta Z),East(X),North(Y),Elevation(Z),CW,CCW,World Angle,E,N,Differential to start pt(Z)");


                        for (int i = 0; i < Referentpt_list.Count; i++)
                        {
                            sw.Write(Referentpt_list[i].RefPoint.TargetPoint + ",");
                            sw.Write(Referentpt_list[i].TargetPoint + ",");
                            sw.Write(Referentpt_list[i].Degree + ",");
                            sw.Write(Referentpt_list[i].Minute + ",");
                            sw.Write(Referentpt_list[i].Second + ",");
                            sw.Write(Referentpt_list[i].Distance + ",");
                            sw.Write(Referentpt_list[i].DeltaZ + ",");
                            sw.Write(Referentpt_list[i].X + ",");
                            sw.Write(Referentpt_list[i].Y + ",");
                            sw.Write(Referentpt_list[i].Z + ",");
                            sw.Write(Referentpt_list[i].Cw + ",");
                            sw.Write(Referentpt_list[i].Ccw + ",");
                            sw.Write(Referentpt_list[i].WorldA + ",");
                            sw.Write(Referentpt_list[i].E + ",");
                            sw.Write(Referentpt_list[i].N + ",");
                            sw.Write(Referentpt_list[i].Diff_z);
                            sw.WriteLine();
                        }
                    }
                    f.Close();
                    this.ShowMessageAsync("Saved", "Path location of saved file:" + newfile);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }