public MainWindow()
        {
            InitializeComponent();
            openFolderDialog = new FolderBrowserDialog();
            openFolderDialog.Description = "Podaj katalog z przykładami";
            openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "*JPEG|*.jpg|Wszystkie pliki|*.*";
            openFileDialog.Title = "Podaj plik przeznaczony do rozponania";

            ojIterations = 10;
            iterationsText.Text = ojIterations.ToString();
            printLineDelegate = printByDispatcher;
            saveImagesDelegate = saveImages;
            createLearningExamplesDelegate = createLearningExamples;
            getFilesDelegate = getFiles;
            setExamplesDelegate = setExamples;
            OnStateChange = stateChange;
            OnReductionFinished = reductionFinished;
            OnReductionStarted = reductionStarted;
            files = null;
            learnButton.IsEnabled = false;
            compareButton.IsEnabled = false;
            outputDimension = 7;
            dimensionText.Text = outputDimension.ToString();

            dataBaseFileName = "C:\\database.db";
            dataBasePathText.Text = dataBaseFileName;
            getDataBaseFileNameDelegate += DBFN;

            examplesHeight = 0;
            examplesWidth = 0;
        }
        //导入“张三|123”文本格式数据
        private void btn_insert_Click(object sender, RoutedEventArgs e)
        {
            //打开文本
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "文本文件|*.txt";
            if (ofd.ShowDialog() != true)
            {
                return;
            }
            string filename = ofd.FileName;

            //把文件一次读取到string集合中
            IEnumerable<string> lines = File.ReadLines(filename, Encoding.Default);

            foreach (string line in lines)
            {
                string[] segs = line.Split('|', ' ');
                string name = segs[0];
                string age = segs[1];
                SqlHelper.ExecuteQuery("insert into custome(Name,Age)values(@Name,@Age)",
                    new SqlParameter("@Name", name),
                    new SqlParameter("@Age", Convert.ToInt32(age)));
            }
            MessageBox.Show("导入成功" + lines.Count() + "条数据!");
        }
Exemple #3
0
        protected override void mergeTiffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

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

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

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

                    ImageIOHelper.MergeTiff(openFileDialog1.FileNames, saveFileDialog1.FileName);
                    MessageBox.Show(this, Properties.Resources.Mergecompleted + Path.GetFileName(saveFileDialog1.FileName) + Properties.Resources.created, strProgName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
		private void ImportImageButtonClick(object sender, RoutedEventArgs e)
		{
			OpenFileDialog openFileDialog = new OpenFileDialog();
#if WPF
			openFileDialog.Filter = "Image Files (*.png, *.jpg, *.bmp)|*.png;*.jpg;*.bmp";
#else
			openFileDialog.Filter = "Image Files (*.png, *.jpg)|*.png;*.jpg";
#endif
			bool? dialogResult = openFileDialog.ShowDialog();
			if (dialogResult.HasValue && dialogResult.Value == true)
			{
				Image image = new Image();
#if WPF
				image.Source = new BitmapImage(new Uri(openFileDialog.FileName, UriKind.Absolute));
#else
					using (var fileOpenRead = openFileDialog.File.OpenRead())
					{
						BitmapImage bitmap = new BitmapImage();
						bitmap.SetSource(fileOpenRead);
						image.Source = bitmap;
					}
#endif
				Viewbox viewBox = new Viewbox() { Stretch = Stretch.Fill, Margin = new Thickness(-4) };
				viewBox.Child = image;
				RadDiagramShape imageShape = new RadDiagramShape()
				{
					Content = viewBox
				};
				this.diagram.Items.Add(imageShape);
			}
		}
        //导入“1300000	"北京市"	"联通"”文本格式数据
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "文本文件|*.txt";
            if (ofd.ShowDialog() == false)
            {
                return;
            }

            string[] lines = File.ReadLines(ofd.FileName, Encoding.Default).ToArray();

            for (int i = 1; i < lines.Count(); i++)
            {
                string line = lines[i];
                string[] str = line.Split('\t');
                string startTeLNum = str[0];
                string city = str[1];
                city = city.Trim('"');
                string telType = str[2];
                telType = telType.Trim('"');
                SqlHelper.ExecuteQuery(@"Insert into T_TelNum(StartTelNum,TelType,TelArea) 
                    values(@StartTelNum,@TelType,@TelArea)",
                    new SqlParameter("@StartTelNum", startTeLNum),
                new SqlParameter("@TelType", telType),
                new SqlParameter("@TelArea", city));
            }
            MessageBox.Show("导入成功!"+lines.Count()+"条数据");
        }
        private void Add()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.DefaultExt = ".dll";
            ofd.Filter = "*.dll|*.dll";

            if (ofd.ShowDialog() == true)
            {
                var types =
                    App.Pyrite.ModulesControl.RegisterChecker(ofd.FileName).Value.ToList().Union(
                        App.Pyrite.ModulesControl.RegisterAction(ofd.FileName).Value.ToList()
                        );
                if (types.Count() == 0)
                {
                    System.Windows.MessageBox.Show("Ни одного типа не зарегистрировано");
                }
                else
                {
                    var str = "Зарегистрированы следующие типы: ";
                    foreach (var typeName in types.Select(x => x.Name))
                    {
                        str += "\r\n" + typeName;
                    }
                    System.Windows.MessageBox.Show(str);
                }
            }

            Refresh();

            lvDlls.SelectedItem = ofd.FileName;

            App.Pyrite.CommitChanges();
        }
        private void Button3_Click(object sender, RoutedEventArgs eArgs)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            if (dlg.ShowDialog() != true)
                return;

            var txtLines = System.IO.File.ReadAllLines(dlg.FileName);
            var pts = new ObservableCollection<NehPoint>();

            var idexFile = Path.ChangeExtension(dlg.FileName, ".idx");
            using (var idexStream = new FileStream(idexFile, FileMode.Create))
            {
                using (var gsiWriter = new IDEXFileWriter(idexStream))
                {
                    foreach (var ln in txtLines)
                    {
                        if (!string.IsNullOrEmpty(ln.Trim())) {
                        var pt = new NehPoint(ln);
                        gsiWriter.AddPoint(pt.Id, pt.E, pt.N, pt.H, null);
                        pts.Add(pt);
                        }
                    }
                }
            }
            PtsGrid.ItemsSource = pts;
            MessageBox.Show("Saved to: \r\n" + idexFile);
        }
        private void btnPopupLoadFile_Click(object sender, RoutedEventArgs e)
        {
            var fileDialog = new OpenFileDialog { Multiselect = false };
            var ftoload = fileDialog.ShowDialog(this);
            if (ftoload.Value)
            {
                try
                {
                    var tabs = JObject.Parse(File.ReadAllText(fileDialog.FileName))["tabs"] as JArray;

                    List<StashBookmark> tabb = new List<StashBookmark>();

                    foreach (JObject tab in tabs)
                    {
                        string name = tab["n"].Value<string>();
                        int index = tab["i"].Value<int>();
                        var c = tab["colour"].Value<JObject>();
                        var color = Color.FromArgb(0xFF, c["r"].Value<byte>(), c["g"].Value<byte>(), c["b"].Value<byte>());
                        StashBookmark sb = new StashBookmark(name, index, color);
                        tabb.Add(sb);
                    }

                    Tabs = tabb;
                    cbTabs.SelectedIndex = 0;

                }
                catch (Exception ex)
                {
                    Popup.Error(L10n.Message("An error occurred while attempting to load stash data."), ex.Message);
                }
            }
        }
Exemple #9
0
        /// <summary>
        /// Initializes the gamePath if not specefied defines new one
        /// </summary>
        private void InitGamePath()
        {
            if (AppSettings.getPropertyValue<string>("GamePath").Length > 2 || Directory.Exists(AppSettings.getPropertyValue<string>("GamePath")) == false)
            {
                RegistryKey regKey = Registry.CurrentUser;
                regKey = regKey.OpenSubKey(@"Software\Valve\Steam");

                if (regKey != null && regKey.GetValue("SteamPath") != null && Directory.Exists(regKey.GetValue("SteamPath").ToString().Replace("/", "\\") + "\\steamapps\\common\\Arma 3"))
                {
                    AppSettings.setProperty("GamePath", regKey.GetValue("SteamPath").ToString().Replace("/", "\\") + "\\steamapps\\common\\Arma 3");
                    AppSettings.SaveAsync();
                    return;
                }
                else
                    if (MessageBox.Show("Unable to locate \"arma3.exe\"!" + Environment.NewLine + "Do you want so specify it?", "Installation not found!", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) == MessageBoxResult.Yes)
                    {
                        OpenFileDialog ofd = new OpenFileDialog();
                        ofd.Filter = "Arma 3|arma3.exe";

                        if (ofd.ShowDialog() == true)
                        {
                            AppSettings.setProperty("GamePath", ofd.FileName.Replace("\\" + ofd.FileName.Split('\\')[ofd.FileName.Split('\\').Length - 1], ""));
                            AppSettings.SaveAsync();
                        }
                        else
                            Environment.Exit(1223);
                    }
                    else
                        Environment.Exit(1223);
            }
        }
      private void SelectFile(object sender, RoutedEventArgs e)
      {
         SoundItem soundItem = DataContext as SoundItem;
         if (soundItem == null)
            return;

         string oldPath = soundItem.FilePath;

         // Open a dialog to have the user pick a file.
         // NOTE: I made a default filter for WAV files but for all I know the
         // SoundPlayer class will play others.  I added the "All files" filter
         // for this situation.
         OpenFileDialog ofd = new OpenFileDialog();
         ofd.Title = "Select .wav file";
         ofd.Filter = "WAV files (*.wav)|*.wav|All files (*.*)|*.*";
         ofd.Multiselect = false;
         
         DirectoryInfo di = SoundController.GetSoundProfileDirectory();
         ofd.InitialDirectory = di.FullName;

         bool? result = ofd.ShowDialog();

         // If the user canceled or otherwise exited, do nothing.
         if (result == null || result == false)
            return;

         // Set the new path and submit it for loading.
         soundItem.FilePath = ofd.FileName;
         if (soundItem.Submit() != Status.Success)
         {
            soundItem.FilePath = oldPath;
         }
      }
        /// <summary>
        /// Get the nodes from the selected text file
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnNodefileSel_OnClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
            //openFileDialog.InitialDirectory = citiesIn.filepath;
            if (openFileDialog.ShowDialog() == true)
            {
                txtboxNodefile.Text = @"...\" + openFileDialog.SafeFileName;
                citiesIn.filepath = openFileDialog.FileName;
            }

            // set the value of the combobox
            nodelist = citiesIn.GetCitieses();
            maxNumofCities = nodelist.Count;
            List<string> citynames = nodelist.Select(cityNode => cityNode.city).ToList();
            comboboxStartCity.ItemsSource = citynames;
            comboboxStartCity.SelectedIndex = 0;
            lboxManualSelectNodes.ItemsSource = citynames;

            if (RandomNodeSelect.IsChecked == true)
                lboxManualSelectNodes.IsEnabled = false;
            else
                lboxManualSelectNodes.IsEnabled = true;

            // draw the circles
            _drawlines(citylisttodraw);
        }
        public void CustomButtonClick()
        {
            var openDialog = new OpenFileDialog
              {
            CheckFileExists = true,
            Filter = "Sitecore Package or ZIP Archive (*.zip)|*.zip",
            Title = "Choose Package",
            Multiselect = true
              };
              if (openDialog.ShowDialog(Window.GetWindow(this)) == true)
              {
            foreach (string path in openDialog.FileNames)
            {
              var fileName = Path.GetFileName(path);

              if (string.IsNullOrEmpty(fileName))
              {
            continue;
              }

              FileSystem.FileSystem.Local.File.Copy(path, Path.Combine(ApplicationManager.ConfigurationPackagesFolder, fileName));

              var products = this.checkBoxItems.Where(item => !item.Name.Equals(fileName, StringComparison.OrdinalIgnoreCase)).ToList();
              products.Add(new ProductInCheckbox(Product.GetFilePackageProduct(Path.Combine(ApplicationManager.ConfigurationPackagesFolder, fileName))));
              this.checkBoxItems = new ObservableCollection<ProductInCheckbox>(products);
              this.unfilteredCheckBoxItems = new ObservableCollection<ProductInCheckbox>(products);
              this.filePackages.ItemsSource = this.checkBoxItems;

              this.SelectAddedPackage(fileName);
            }
              }
        }
Exemple #13
0
        public void LoadImage()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Bitmap Image (.bmp)|*.bmp|PNG Image (.png)|*.png|JPEG Image (.jpeg)|*.jpeg|JPG Image (.jpg)|*.jpg";

            bool? result = ofd.ShowDialog();

            string fileName = "";
            if (result != null)
                fileName = ofd.FileName;

            if (fileName == "")
                return;

            canvas.Children.Clear();
            BitmapImage image;
            using (FileStream stream = new FileStream(fileName, FileMode.Open))
            {
                stream.Position = 0;
                image = new BitmapImage();
                image.BeginInit();
                image.StreamSource = stream;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.EndInit();
            }
            canvas.Background = new ImageBrush(image);
        }
Exemple #14
0
        internal async Task Load_File(CancellationToken cancellation, IProgress<Tuple<string, int>> currentTaskAndPercentComplete)
        {
            if (UnsavedChangesPresent && !_window.Confirm_Discard_Changes()) return;

            var dialog = new OpenFileDialog
            {
                DefaultExt = DataFileExt,
                Filter = DataFileFilter
            };
            if (dialog.ShowDialog() ?? false)
            {
                FileList = await FileAccess.LoadInfo(dialog.FileName, cancellation, currentTaskAndPercentComplete);
                if (cancellation.IsCancellationRequested)
                {
                    return;
                }

                UnsavedChangesPresent = false;
                if (FileList.Any())
                {
                    FileIndex = 0;
                    RectangleIndex = 0;
                    RectangleHasFocus = false;
                    await _window.Canvas.LoadImage(this, FileIndex);
                    _window.Canvas.LoadRectangles(this, FileIndex);
                }
            }
        }
		private void btnRun_Click(object sender, RoutedEventArgs e)
		{
			OpenFileDialog dlg = new OpenFileDialog();
			dlg.Filter = "Programs|*.exe|All files|*.*";
			dlg.DefaultExt = ".exe";
			if (!(dlg.ShowDialog() ?? false))
				return;
			string path = dlg.FileName;

			// remove UI before disposing profiler
			//this.timeLine.ValuesList.Clear();
			if (this.provider != null)
				this.provider.Close();

			if (this.profiler != null)
				this.profiler.Dispose();
			
			string pathToDb = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(typeof(Profiler.Controller.Profiler).Assembly.Location), "output.sdps");
			if (File.Exists(pathToDb))
				File.Delete(pathToDb);
			
			this.database = new TempFileDatabase();
			
			this.profiler = new Profiler.Controller.Profiler(path, database.GetWriter(), new ProfilerOptions());
			profiler.RegisterFailed += delegate { MessageBox.Show("register failed"); };
			profiler.DeregisterFailed += delegate { MessageBox.Show("deregister failed"); };

			this.profiler.OutputUpdated += profiler_OutputUpdated;
			this.profiler.SessionEnded += profiler_SessionEnded;

			this.profiler.Start();

			this.btnRun.IsEnabled = false;
			this.btnStop.IsEnabled = true;
		}
 private void OpenDDL_Click(object sender, RoutedEventArgs e)
 {
   OpenFileDialog dialog = null;
   try
   {
     dialog = new OpenFileDialog();
     dialog.CheckFileExists = true;
     dialog.CheckPathExists = true;
     dialog.Filter = "MigraDoc DDL (*.mdddl)|*.mdddl|All Files (*.*)|*.*";
     dialog.FilterIndex = 1;
     dialog.InitialDirectory = System.IO.Path.Combine(GetProgramDirectory(), "..\\..");
     //dialog.RestoreDirectory = true;
     if (dialog.ShowDialog() == true)
     {
       Document document = DdlReader.DocumentFromFile(dialog.FileName);
       string ddl = DdlWriter.WriteToString(document);
       preview.Ddl = ddl;
     }
   }
   catch (Exception ex)
   {
     MessageBox.Show(ex.Message, Title);
     preview.Ddl = null; // TODO has no effect
   }
   finally
   {
     //if (dialog != null)
     //  dialog.Dispose();
   }
   //UpdateStatusBar();
 }
        // �����Ϳ��� �̺�Ʈ �ڵ鷯 (���� IO�κ�)
        // ������ ������� ���̴� Deserialize�� Serialize �κ�
        void OpenOnExecuted(object sender, ExecutedRoutedEventArgs args)
        {
            OpenFileDialog dlg = new OpenFileDialog();    // ���Ͽ��� ���̾�α� ��ü ����
            dlg.Filter = strFilter;                                   // ǥ�õǴ� �������� ���� (�������ĺκ�)
            Person pers;                                            // PersonŬ���� ��ü ����

            if ((bool)dlg.ShowDialog(this))                      // ���Ͽ��� ���̾�αװ� ����������?
            {
                try
                {
                    // �����̸� ���ڿ��� �д� ��Ʈ�� ���� ��ü ����
                    StreamReader reader = new StreamReader(dlg.FileName);
                    // ��Ʈ������ ��ü�� �籸�� �ؼ� Person ��ü�� ����
                    pers = (Person) xml.Deserialize(reader);
                    reader.Close();
                }
                catch (Exception exc)
                {
                    MessageBox.Show("������ �����ھ�� ��  _�� : " + exc.Message,
                                    Title, MessageBoxButton.OK,  MessageBoxImage.Exclamation);
                    return;
                }
                // DataContext�� ��Ұ� ���ε��� ���Ǵ� ������ �ҽ��� ���� ���� �� ��� ��
                // ���ε��� ��Ÿ Ư���� �θ� ��ҷκ��� ��� �� �� �ֵ��� �ϴ� ����.
                pnlPerson.DataContext = pers;
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = false;
            fileDialog.ShowDialog();
            if (fileDialog.FileName == string.Empty)
            {
                return;
            }

            var titleDialog = new ImageTitleDialogBox();
            titleDialog.Owner = this;
            var result = titleDialog.ShowDialog();
            if (result != true)
            {
                return;
            }

            var newImage = new ImageViewModel()
            {
                Title = titleDialog.tbImageTitle.Text,
                Source = fileDialog.FileName
            };

            var viewModel = (ImageGalleryViewModel)DataContext;
            if (viewModel.CurrentAlbum.AddImage.CanExecute(null))
            {
                viewModel.CurrentAlbum.AddImage.Execute(newImage);
            }
        }
        private void MenuEtude_Click(object sender, RoutedEventArgs e)
        {
            //Configuration de la boite de dialogue ouvrir fichier
            OpenFileDialog open = new OpenFileDialog();
            open.FileName = "Document";
            open.DefaultExt = ".xls; .xlsx"; //Extention de fichier par default
            open.Filter = "Excel document (.xls; .xlsx) | *.xls; *.xlsx"; //Filtre les fichier par extention

            //Afficher la boite de dialogue
            Nullable<bool> result = open.ShowDialog();

            //Traitement d'ouverture de fichier
            if (result == true)
            {
                _filePath = open.FileName;
                
               //DonneesFichierExcelView donneesfichierexcel = new DonneesFichierExcelView(filePath);
                donneesFichierExcel = new DonneesFichierExcelView(_filePath);
                GridMilieu.Children.Clear();
                GridMilieu.Children.Add(donneesFichierExcel);
                MenuHaut.IsEnabled = true;
                MenuHautAfficheDonnees.IsEnabled = false;
                MenuHautParametre.IsEnabled = true;
                MenuHautAnalyse.IsEnabled = true;
                MenuHautImpression.IsEnabled = false;
            }
        }
Exemple #20
0
        public string _ouvrir(typeFichier tf)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (tf == typeFichier.musique)
            {
                ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
                ofd.Filter = "mp3 files (*.mp3)|*.mp3";
                ofd.FilterIndex = 2;
                ofd.RestoreDirectory = true;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    if (ofd.OpenFile() != null)
                    {
                        try
                        {
                            Lecteur = new Audio(ofd.FileName, false);

                        }
                        catch (Exception esx)
                        {
                            MessageBox.Show("Fichier non reconnu." + esx.HResult);
                            return null;
                        }

                        return ofd.FileName;

                    }
                }
                return null;
            }
            else if (tf == typeFichier.image)
            {
                ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
                ofd.Filter = "JPG (*.jpg)|*.jpg";
                ofd.FilterIndex = 2;
                ofd.RestoreDirectory = true;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        if (ofd.OpenFile() != null)// On attribue le chemin du fichier à lire au
                        {

                            return ofd.FileName;

                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                        return null;
                    }
                }
                return null;

            }
            return null;
        }
        private void open_button_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            openFileDialog1.Filter = @"Evennote File(*.note)|*.note";

            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == true)
            {
                Note temp = Evennote.OpenNoteFromFile(openFileDialog1.FileName);

                titleTextBox.Text = temp.Title;

                using (MemoryStream mem = new MemoryStream())
                {
                    TextRange range = new TextRange(temp.Text.ContentStart,
                        temp.Text.ContentEnd);
                    range.Save(mem, DataFormats.XamlPackage);
                    mem.Position = 0;

                    TextRange kange = new TextRange(richTextBox.Document.ContentStart,
                        richTextBox.Document.ContentEnd);
                    kange.Load(mem, DataFormats.XamlPackage);
                }
            }
        }
		private void AddCellButton_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			// Create an instance of the open file dialog box.
			OpenFileDialog openFileDialog1 = new OpenFileDialog();

			// Set filter options and filter index.
			openFileDialog1.DefaultExt = ".000";
			openFileDialog1.Filter = "S57 Cells (.000)|*.000";
			openFileDialog1.Multiselect = true;

			// Call the ShowDialog method to show the dialog box.
			bool? userClickedOK = openFileDialog1.ShowDialog();

			// Process input if the user clicked OK.
			if (userClickedOK == true)
			{
				foreach (string fileName in openFileDialog1.FileNames)
				{
					var hydroLayer = new HydrographicS57Layer() 
					{ 
						Path = fileName,
						ID = Path.GetFileNameWithoutExtension(fileName)
					};
					_hydrographicGroupLayer.ChildLayers.Add(hydroLayer);
					s57CellList.SelectedItem = hydroLayer;
				}
			}
		}
Exemple #23
0
        private void AddImageMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                InitialDirectory = @"C:\Users\Dmitry\Pictures",
                FilterIndex = 2,
                RestoreDirectory = true
            };

            if (openFileDialog.ShowDialog() != null)
            {
                try
                {
                    var image = new BitmapImage(new Uri(openFileDialog.FileName));
                    if(_height == 0)
                    {
                        _height = image.PixelHeight;
                        _width = image.PixelWidth;
                        _pixelsNumber = _width*_height;
                    }
                    _standardImages.Add(image);
                    _standardImageVectors.Add(GetImageVector(BitmapConverter.BitmapImage2Bitmap(image)));
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }
        private void OpenMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (asm != null && asm.Strings.Any(s => s.IsDirty))
            {
                if (MessageBox.Show("You have unsaved changes. Really open a new file?", Title, MessageBoxButton.YesNo) == MessageBoxResult.No)
                    return;
            }

            var ofd = new OpenFileDialog();

            if (ofd.ShowDialog() != true)
                return;

            try
            {
                using (var f = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read))
                {
                    DataContext = asm = CompiledAssembly.Load(f);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Could not open file: {ex}");
            }
        }
 private void SetMode()
 {
     if(IsFileSelector)
     {
         ButtonText = "\uF15C";
         ButtonCommand = new RelayCommand(() => 
         {
             var dlg = new OpenFileDialog();
             if (dlg.ShowDialog() == true)
             {
                 ConfigItemValue = dlg.FileName;
             }
         }, true);
     }
     else
     {
         ButtonText = "\uF07C";
         ButtonCommand = new RelayCommand(() =>
         {
             var dlg = new System.Windows.Forms.FolderBrowserDialog();
             dlg.ShowNewFolderButton = true;
             dlg.ShowDialog();
             if (!String.IsNullOrEmpty(dlg.SelectedPath))
             {
                 ConfigItemValue = dlg.SelectedPath;
             }
         }, true);
     }
 }
Exemple #26
0
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            // 画像を開く
            var dialog = new OpenFileDialog();
            dialog.Filter = "画像|*.jpg;*.jpeg;*.png;*.bmp";
            if (dialog.ShowDialog() != true)
            {
                return;
            }

            // ファイルをメモリにコピー
            var ms = new MemoryStream();
            using (var s = new FileStream(dialog.FileName, FileMode.Open))
            {
                s.CopyTo(ms);
            }
            // ストリームの位置をリセット
            ms.Seek(0, SeekOrigin.Begin);
            // ストリームをもとにBitmapImageを作成
            var bmp = new BitmapImage();
            bmp.BeginInit();
            bmp.StreamSource = ms;
            bmp.EndInit();
            // BitmapImageをSourceに指定して画面に表示する
            this.image.Source = bmp;
        }
 private void button1_Click(object sender, RoutedEventArgs e)
 {
     OpenFileDialog openfiledialog = new OpenFileDialog();
     openfiledialog.ShowDialog();
     //if(openfiledialog.FileOk)
        // System.IO.Stream fileStream = openfiledialog.FileOk;
 }
Exemple #28
0
        /**
         * <summary>Zeigt OpenFileDialog an</summary>
         *
         * <remarks>Beate, 09.10.2013.</remarks>
         */
        private static string OpenFile()
        {
            string[] allfiles = { };
            string filename = string.Empty;
            string path = string.Empty;
            List<string> filenameOnly = new List<string>();
            OpenFileDialog inputDlg = new OpenFileDialog();
            inputDlg.Multiselect = true;
            inputDlg.InitialDirectory = @"";
            inputDlg.Filter = "Xmascup Competitor Dateien|Competitor*.xml";

            if (inputDlg.ShowDialog().Value)
            {
                allfiles = inputDlg.FileNames;
                foreach (string s in allfiles)
                {
                    filename = System.IO.Path.GetFileName(s);
                    path = System.IO.Path.GetDirectoryName(s);
                    filenameOnly.Add(filename);

                }

                MessageBox.Show("Eingabe: " + filename,
                    "Xmascup Dateiauswahl");
                return allfiles[0].ToString();
            }
            else
            {
                MessageBox.Show("Keine Datei ausgewählt !!",
                     "Xmascup Dateiauswahl");
                return "keine Auswahl getroffen";
            }
        }
Exemple #29
0
        private void OpenFileMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var openFileDialog = new OpenFileDialog
            {
                InitialDirectory = @"C:\Users\Dmitry\Pictures",
                FilterIndex = 2,
                RestoreDirectory = true
            };

            if (openFileDialog.ShowDialog() != null)
            {
                try
                {
                    _sourceImage = new BitmapImage(new Uri(openFileDialog.FileName));
                    _noisedImage = _sourceImage;
                    SourceImage.Source = _sourceImage;
                    _width = _sourceImage.PixelWidth;
                    _height = _sourceImage.PixelHeight;
                    _pixelsNumber = _width * _height;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     OpenFileDialog dlg = new OpenFileDialog();
     dlg.FileOk += Dlg_FileOk;
     dlg.Filter = "*.jpg|*.jpg";
     dlg.ShowDialog();
 }
        /*
         * private void UploadActionTable()
         * {
         *  if (MessageConfirm("上傳所有動作到機械人, 機械人內所有動作將會被覆蓋.  建議分開動作獨立上傳."))
         *  {
         *      if (UBT.UploadActionTable())
         *      {
         *          UpdateInfo("上傳資料完成");
         *      }
         *  }
         *
         * }
         */
        private void ConvertAction()
        {
            UpdateInfo();
            int actionId = GetSelectedActionId();

            if (actionId < 0)
            {
                return;
            }

            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "aesx or hts files|*.aesx;*.hts|aesx file (*.aesx)|*.aesx|hts file (*.hts)|*.hts";
            if (openFileDialog.ShowDialog() == true)
            {
                String         fileName = openFileDialog.FileName.Trim();
                String         lName    = fileName.ToLower();
                CONST.UBT_FILE fileType = CONST.UBT_FILE.UNKNOWN;
                if (lName.EndsWith(".aesx"))
                {
                    fileType = CONST.UBT_FILE.AESX;
                }
                if (lName.EndsWith(".hts"))
                {
                    fileType = CONST.UBT_FILE.HTS;
                }
                if (fileType == CONST.UBT_FILE.UNKNOWN)
                {
                    UpdateInfo(String.Format("Invalid file extension {0}", fileName), UTIL.InfoType.error);
                    return;
                }

                char actionCode = UBT.actionTable.action[actionId].actionCode;
                if (MessageConfirm(String.Format("把 UBTech 檔 {0} 的動作檔截入動作 {1} 中, 當前資料將會被覆蓋", fileName, actionCode)))
                {
                    try
                    {
                        long         size       = new FileInfo(fileName).Length;
                        FileStream   fs         = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                        BinaryReader br         = new BinaryReader(fs);
                        byte[]       actionData = null;
                        // File size should not be over 2M, so not need to handle overflow)
                        actionData = br.ReadBytes((int)size);
                        br.Close();
                        fs.Close();
                        string actionName = openFileDialog.SafeFileName;
                        actionName = actionName.Substring(0, actionName.IndexOf('.'));
                        if (UBT.actionTable.ReadFromUBTechFile(actionData, actionId, actionName, fileType))
                        {
                            UpdateInfo(String.Format("Rebuild action table from {0}", fileName));
                        }
                        else
                        {
                            UpdateInfo(String.Format("Error building action from {0}", fileName), UTIL.InfoType.error);
                        }
                    }
                    catch (Exception ex)
                    {
                        UpdateInfo(String.Format("Error reading data from {0}: {1}", fileName, ex.Message), UTIL.InfoType.error);
                    }
                    RefreshActionInfo();
                }
            }
        }
Exemple #32
0
        public void ModelNew()
        {
            OpenFileDialog myOpenFileDialog = new OpenFileDialog();

            myOpenFileDialog.Filter           = string.Format("{1} (*.{0})|*.{0}", FileExtensionEnum.Lib, FileExtensionEnum.Lib.GetDescription());
            myOpenFileDialog.Title            = "选择光谱库";
            myOpenFileDialog.InitialDirectory = Busi.Common.Configuration.FolderSpecLib;
            if (myOpenFileDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            this.statuTxt.Text            = "正在加载光谱库:";
            this.statuProgressBar.Value   = 0;
            this.statuProgressBar.Visible = true;
            this._fileName = myOpenFileDialog.FileName;

            Action a = () =>
            {
                this._model.LibBase = new SpecBase(this._fileName);
                if (this._model.LibBase == null)
                {
                    return;
                }
                this._model.SubModels = new List <PLSSubModel>();

                // 检查性质个数并给出提示
                if (this._model.LibBase.Components.Count < 1)
                {
                    MessageBox.Show("您导入的光谱库没有性质,请先添加性质", "信息提示");
                }


                this._nodes.Clear();



                foreach (var c in this._model.LibBase.Components)
                {
                    var m = new PLSSubModel();
                    m.ParentModel = this._model;
                    m.Comp        = c;
                    this._model.SubModels.Add(m);

                    this._nodes.Add(new MyTreeNode()
                    {
                        IsFinished  = false,
                        ToolTipText = "双击可编辑子模型",
                        PLS         = new PLSFormContent()
                        {
                            ActiveStep = 1,
                            CVResult   = null,
                            Model      = m
                        }
                    });
                }

                this.treeInit();


                this.statuProgressBar.Value   = 100;
                this.statuProgressBar.Visible = false;
                this.statuTxt.Text            = "光谱库加载完成";
            };

            this.BeginInvoke(a);
        }
Exemple #33
0
        /// <summary>
        /// Compacta o arquivo .txt escolhido
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Compactar_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog
            {
                Filter = "TXT files|*.txt"
            };

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                var tamanhoInicial = new System.IO.FileInfo(ofd.FileName).Length;

                // Lendo arquivo
                string arquivo;
                using (var sr = new System.IO.StreamReader(ofd.FileName))
                {
                    arquivo = sr.ReadToEnd();
                }

                // Variáveis para controlar o loop e o dicionário
                Contador = 0;
                var        indice                    = 0;
                var        tamanho                   = 1;
                var        sequenciaNova             = string.Empty;
                Dicionario ultimaSequenciaEncontrada = null;

                // Criando o dicionário e adicionando o simbolo vazio
                var dicionario = new List <Dicionario>
                {
                    new Dicionario {
                        PalavraCodigo = ContadorBinario, Sequencia = ""
                    }
                };

                // Criando variável para armazenar o conteúdo com bits e bytes
                var sequenciaCodificada = new List <SequenciaCodificada>();

                // Percorrendo arquivo
                while (indice < arquivo.Length && indice + tamanho < arquivo.Length + 1)
                {
                    sequenciaNova = arquivo.Substring(indice, tamanho);
                    var sequenciaDicionario = dicionario.Find(d => d.Sequencia == sequenciaNova);

                    if (sequenciaDicionario is null)
                    {
                        if (ultimaSequenciaEncontrada is null)
                        {
                            for (int i = 0; i < dicionario.Last().PalavraCodigo.Length; i++)
                            {
                                sequenciaCodificada.Add(new SequenciaCodificada {
                                    Sequencia = dicionario.First().PalavraCodigo, Bit = true
                                });
                            }
                            sequenciaCodificada.Add(new SequenciaCodificada {
                                Sequencia = sequenciaNova, Bit = false
                            });
                            Contador++;
                            dicionario.Add(new Dicionario {
                                PalavraCodigo = ContadorBinario, Sequencia = sequenciaNova
                            });
                            indice += tamanho;
                            tamanho = 1;
                        }
                        else
                        {
                            for (int i = ultimaSequenciaEncontrada.PalavraCodigo.Length; i < dicionario.Last().PalavraCodigo.Length; i++)
                            {
                                sequenciaCodificada.Add(new SequenciaCodificada {
                                    Sequencia = dicionario.First().PalavraCodigo, Bit = true
                                });
                            }
                            sequenciaCodificada.Add(new SequenciaCodificada {
                                Sequencia = ultimaSequenciaEncontrada.PalavraCodigo, Bit = true
                            });
                            sequenciaCodificada.Add(new SequenciaCodificada {
                                Sequencia = sequenciaNova.Last().ToString(), Bit = false
                            });
                            Contador++;
                            dicionario.Add(new Dicionario {
                                PalavraCodigo = ContadorBinario, Sequencia = sequenciaNova
                            });
                            indice += tamanho;
                            tamanho = 1;
                        }
                        ultimaSequenciaEncontrada = null;
                        sequenciaNova             = string.Empty;
                    }
                    else
                    {
                        ultimaSequenciaEncontrada = sequenciaDicionario;
                        tamanho++;
                    }
                }

                // Última sequência
                if (!string.IsNullOrWhiteSpace(sequenciaNova))
                {
                    if (ultimaSequenciaEncontrada is null)
                    {
                        for (int i = 0; i < dicionario.Last().PalavraCodigo.Length; i++)
                        {
                            sequenciaCodificada.Add(new SequenciaCodificada {
                                Sequencia = dicionario.First().PalavraCodigo, Bit = true
                            });
                        }
                        sequenciaCodificada.Add(new SequenciaCodificada {
                            Sequencia = sequenciaNova, Bit = false
                        });
                    }
                    else
                    {
                        for (int i = ultimaSequenciaEncontrada.PalavraCodigo.Length; i < dicionario.Last().PalavraCodigo.Length; i++)
                        {
                            sequenciaCodificada.Add(new SequenciaCodificada {
                                Sequencia = dicionario.First().PalavraCodigo, Bit = true
                            });
                        }
                        sequenciaCodificada.Add(new SequenciaCodificada {
                            Sequencia = ultimaSequenciaEncontrada.PalavraCodigo, Bit = true
                        });
                    }
                }

                // Removendo 0 inicial
                sequenciaCodificada.RemoveAt(0);

                // Substituindo bytes por bits
                var zerosEum = string.Join(string.Empty, sequenciaCodificada.Select(s => s.Bit ? s.Sequencia : Convert.ToString(s.Sequencia.ToCharArray()[0], 2).PadLeft(8, '0')));

                // Convertendo bits em bytes
                var bytes = new List <byte>();
                int j     = 0;
                while (j + 8 <= zerosEum.Length)
                {
                    var oitoBits   = zerosEum.Substring(j, 8);
                    var bitsEmByte = Convert.ToByte(oitoBits, 2);
                    bytes.Add(bitsEmByte);
                    j += 8;
                }

                // Adicionando zeros a esquerda do último bit para converter em byte, se necessário, e adicionando último byte referente a quantidade de zeros adicionados
                if (j + 8 == zerosEum.Length)
                {
                    bytes.Add(Convert.ToByte(0));
                }
                else
                {
                    var bitsRestantes = zerosEum.Length - j;
                    bytes.Add(Convert.ToByte(zerosEum.Substring(j, bitsRestantes).PadLeft(8, '0'), 2));
                    bytes.Add(Convert.ToByte(8 - bitsRestantes));
                }

                // Gerando arquivo
                var arquivoRetorno = ofd.FileName + ".lz";
                System.IO.File.WriteAllBytes(arquivoRetorno, bytes.ToArray());

                var tamanhoFinal = new System.IO.FileInfo(arquivoRetorno).Length;
                MessageBox.Show("Taxa de compressão: " + (decimal.Divide(tamanhoFinal, tamanhoInicial) * 100).ToString("0.00") + "%");
            }
        }
Exemple #34
0
        /// <summary>
        /// Descompacta o arquivo .txt.lz escolhido
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Descompactar_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog
            {
                Filter = "Arquivos Lempel-Ziv|*.lz"
            };

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                // Lendo arquivo
                var arquivo = System.IO.File.ReadAllBytes(ofd.FileName);

                // Verificando quantidade de zeros adicionados na compactação
                var zerosAdicionados = Convert.ToInt32(arquivo.Last());

                // Removendo último byte
                var bytes = arquivo.ToList();
                bytes.Remove(bytes.Last());

                // Convertendo bytes em blocos de 8 bits
                var bits = string.Empty;
                foreach (var b in bytes)
                {
                    bits += Convert.ToString(b, 2).PadLeft(8, '0');
                }

                // Removendo zeros adicionados na compactação
                bits = bits.Remove(bits.Length - 8, zerosAdicionados);

                // Variáveis para controlar o loop e o dicionário
                Contador = 0;
                var indice           = 0;
                var tamanho          = 8;
                var sequenciaNova    = string.Empty;
                var bytesConvertidos = new List <byte>();

                // Criando o dicionário e adicionando o simbolo vazio
                var dicionario = new List <Dicionario>
                {
                    new Dicionario {
                        PalavraCodigo = ContadorBinario, Sequencia = ""
                    }
                };

                // Percorrendo os bits
                while (indice < bits.Length)
                {
                    // Primeiro símbolo
                    if (dicionario.Count == 1)
                    {
                        sequenciaNova = bits.Substring(indice, tamanho);
                        Contador++;
                        dicionario.Add(new Dicionario {
                            Sequencia = sequenciaNova, PalavraCodigo = ContadorBinario
                        });
                        bytesConvertidos.Add(Convert.ToByte(sequenciaNova, 2));
                        indice += tamanho;
                    }
                    else
                    {
                        tamanho = dicionario.Last().PalavraCodigo.Length;
                        var palavraCodigo = bits.Substring(indice, tamanho);

                        // Removendo zeros a esquerda da palavra-código
                        palavraCodigo = palavraCodigo.TrimStart(new Char[] { '0' });

                        var sequenciaDicionario = string.Empty;
                        if (palavraCodigo.Length > 0)
                        {
                            sequenciaDicionario = dicionario.Find(d => d.PalavraCodigo == palavraCodigo).Sequencia;
                            for (int i = 0; i < sequenciaDicionario.Length; i += 8)
                            {
                                bytesConvertidos.Add(Convert.ToByte(sequenciaDicionario.Substring(i, 8), 2));
                            }
                        }
                        indice += tamanho;
                        tamanho = 8;
                        if (indice + tamanho <= bits.Length)
                        {
                            sequenciaNova = bits.Substring(indice, tamanho);
                            Contador++;
                            dicionario.Add(new Dicionario {
                                Sequencia = string.Concat(sequenciaDicionario, sequenciaNova), PalavraCodigo = ContadorBinario
                            });
                            bytesConvertidos.Add(Convert.ToByte(sequenciaNova, 2));
                        }
                        indice += tamanho;
                    }
                }

                // Convertendo bits em string
                var retorno = System.Text.Encoding.ASCII.GetString(bytesConvertidos.ToArray());

                // Gerando arquivo
                var arquivoRetorno = ofd.FileName + ".txt";
                System.IO.File.WriteAllText(arquivoRetorno, retorno);
                MessageBox.Show("Arquivo descompactado:" + Environment.NewLine + arquivoRetorno);
            }
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            // Set filter options
            openFileDialog1.Filter = "ZTree Pay Files (*.pay)|*.pay|All Files|*.*";


            openFileDialog1.Multiselect = true;

            // Call the ShowDialog method to show the dialog box.
            bool?userClickedOK = openFileDialog1.ShowDialog();

            // Process input if the user clicked OK.
            if (userClickedOK == true)
            {
                readPayFile(openFileDialog1.FileName);
                Microsoft.Office.Interop.Word.Selection       wrdSelection;
                Microsoft.Office.Interop.Word.MailMerge       wrdMailMerge;
                Microsoft.Office.Interop.Word.MailMergeFields wrdMergeFields;
                Microsoft.Office.Interop.Word.Table           wrdTable;
                string StrToAdd;

                // Create an instance of Word  and make it visible.
                wrdApp         = new Microsoft.Office.Interop.Word.Application();
                wrdApp.Visible = true;

                // Add a new document.
                wrdDoc = wrdApp.Documents.Add(ref oMissing, ref oMissing,
                                              ref oMissing, ref oMissing);
                wrdDoc.Select();

                wrdSelection = wrdApp.Selection;



                foreach (Participant partip in this.adat)
                {
                    // Create a MailMerge Data file.
                    //  CreateMailMergeDataFile();

                    wrdSelection.ParagraphFormat.Alignment =
                        Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
                    wrdSelection.Font.Size = 26;
                    wrdSelection.Font.Name = "Arial";
                    wrdSelection.TypeText("Receipt \r\n Seat number: " + partip.boothno);
                    wrdSelection.Font.Size = 10;
                    wrdSelection.Font.Name = "Times New Roman";

                    InsertLines(1);

                    // Create a string and insert it into the document.
                    wrdSelection.ParagraphFormat.Alignment =
                        Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
                    // set color waaaaa                 wrdSelection.Font.TextColor.RGB = 000080;

                    StrToAdd = "\r\n COGNITION AND BEHAVIOR LAB";
                    // wrdSelection.ParagraphFormat.Alignment  =
                    //   Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;



                    try
                    {
                        string location = Application.ResourceAssembly.Location;
                        //MessageBox.Show(location);
                        location = location.Replace(@"\merge.exe", "");
                        //MessageBox.Show(location);
                        location = location + @"\1.png";
                        //MessageBox.Show(location);
                        wrdSelection.InlineShapes.AddPicture(location);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Image file (1.png) not found!");
                    }
                    wrdSelection.TypeText(StrToAdd);



                    wrdSelection.TypeText("\r\nName: " + partip.name);
                    wrdSelection.TypeText("\r\nCPR number: " + partip.cpr);
                    wrdSelection.TypeText("\r\nYour earnings in today’s experiment: " + partip.profit + " kr. \r\n");

                    // Justify the rest of the document.
                    wrdSelection.ParagraphFormat.Alignment =
                        Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;

                    // Create a string and insert it into the document.
                    wrdSelection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
                    StrToAdd = "Aarhus University will automatically transfer the amount you earn into your NemKonto (for this we need your CPR number). This is simply your existing bank account, into which all payments from the public sector flow (e.g. tax refunds or SU student grants). Alexander Koch and his team will start registering the payments with the administration of Aarhus University this week. Then the administrative process might take between 2-6 weeks. You can contact Alexander Koch by email ([email protected]) if you want information on the payment process.";
                    wrdSelection.TypeText(StrToAdd);
                    wrdSelection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
                    InsertLines(1);
                    StrToAdd = "According to Danish law, Aarhus University reports payments to the tax authorities. Please note that, depending on your personal income tax rate, taxes will be deducted from the amount of money you earn in this study. That is, the amount you will receive might be lower than the pre-tax earnings stated above.";
                    wrdSelection.TypeText(StrToAdd);
                    InsertLines(1);

                    // Right justify the line and insert a date field
                    // with the current date.
                    wrdSelection.ParagraphFormat.Alignment =
                        Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;

                    Object objDate = "dddd, MMMM dd, yyyy";
                    wrdSelection.InsertDateTime(ref objDate, ref oFalse, ref oMissing,
                                                ref oMissing, ref oMissing);

                    wrdSelection.InlineShapes.AddHorizontalLineStandard();
                    wrdSelection.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);


                    // Close the original form document.
                    //wrdDoc.Saved = true;

                    /*wrdDoc.Close(ref oFalse,ref oMissing,ref oMissing);
                     *
                     *
                     * // Release References.
                     * wrdSelection = null;
                     * wrdMailMerge = null;
                     * wrdMergeFields = null;
                     * wrdDoc = null;
                     * wrdApp = null;
                     *
                     * // Clean up temp file.
                     * System.IO.File.Delete("C:\\DataDoc.doc");*/
                }
            }
        }
Exemple #36
0
        private void Start_Click(object sender, EventArgs e)
        {
            //pictureBox2.Image = SandDiameterMeasuring.Properties.Resources.屏幕截图_1654_;
            // pictureBox2.Image.Dispose();
            // pictureBox2.Image = null;
            textBox1.Text = ("加载图片");
            OpenFileDialog file = new OpenFileDialog();

            file.InitialDirectory = ".";
            file.Filter           = "所有文件(*.*)|*.*";
            file.ShowDialog();
            if (file.FileName != string.Empty)
            {
                try
                {
                    pathname = file.FileName;   //获得文件的绝对路径
                    this.pictureBox1.Load(pathname);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            string str1 = file.FileName;

            //str1 = "'" + str1 + "'";//加单引号为符合matlab输入规范
            textBox1.Text = (str1);
            //textBox1.Text = (file.FileName);
            DiameterCalculation.Class1 c1 = new DiameterCalculation.Class1();
            //Object sandNumber;
            MWArray        a1 = c1.linktocsharp(str1);
            MWNumericArray a2 = (MWNumericArray)a1;

            textBox2.Text = a2.ToString();

            linktocsharpV3.Class1 v3c1 = new linktocsharpV3.Class1();
            //MWArray DiameterArray = v3c1.linktocsharpV3(str1);
            MWArray[] resultlist = new MWArray[2];
            resultlist = v3c1.linktocsharpV3(2, str1);                    //重要!!!m函数有多个返回值时在第一个参数里写入返回值个数,第二个参数才是输入m函数的第一个输入参数
            MWNumericArray DiameterArray = (MWNumericArray)resultlist[0]; //返回每一粒沙子的直径数组,为n行1列的二维数组
            MWNumericArray SandNumber    = (MWNumericArray)resultlist[1]; //沙尘个数

            double[,] DA = new double[(int)SandNumber, 1];                //matlab函数返回值为二维数组,因此需要用二维数组接收
            DA           = (double[, ])DiameterArray.ToArray();
            //textBox3.Text = DA[(int)a2 - 1, 0].ToString();
            //textBox3.Text = DA[(int)SandNumber - 1, 0].ToString();



            //textBox2.Text = (sandNumber.ToString);
            string pathname2;

            pathname2 = "D:\\op\\tempresult.png";  //获得文件的绝对路径
            //this.pictureBox2.Load(pathname2);//load貌似过时了?
            // this.pictureBox2.Image = Image.FromFile(pathname2);
            //    pictureBox2.Image.Dispose();
            FileStream pFileStream = new FileStream(pathname2, FileMode.Open, FileAccess.Read);

            pictureBox2.Image = Image.FromStream(pFileStream);
            pFileStream.Close();
            pFileStream.Dispose();
        }
Exemple #37
0
        static void Main(string[] args)
        {
            string bmFontExePath = "";
            bool existBMFont = false;
            if (File.Exists(bmFontPathFile))
            {
                StreamReader sr = new StreamReader(bmFontPathFile);
                bmFontExePath = sr.ReadLine();
                string[] temp = bmFontExePath.Split('"');
                sr.Close();
                if (File.Exists(temp[1]))
                {
                    existBMFont = true;
                }
            }
            if(existBMFont != true)
            {
                File.Create(bmFontPathFile).Close();
                //选择BMFONT文件目录
                OpenFileDialog fd = new OpenFileDialog();
                fd.Filter = "EXE文件(*.exe)|*.exe";
                fd.Title = "选择BMFont.exe程序";
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    Console.WriteLine("选择文件");
                    StreamWriter sw = new StreamWriter(bmFontPathFile, false, new System.Text.UTF8Encoding(true));  //使用utf8-BOM编码
                    StringBuilder sb = new StringBuilder();
                    sb.Append("\"");
                    sb.Append(fd.FileName);
                    sb.Append("\"");
                    sw.Write(sb.ToString());
                    sw.Close();
                    Console.WriteLine("bmFont.exe路径为 {0}", sb.ToString());
                    bmFontExePath = sb.ToString();
                }
            }

            Dictionary<string, bool> charDic = new Dictionary<string, bool>();
            StringBuilder languageText = new StringBuilder();
            StringBuilder fileContent = new StringBuilder();
            if (containsPrefab)
            {
                AddAllSpecifiedFile(prefabFolder, "*.prefab");
            }
            if (containsScript)
            {
                AddAllSpecifiedFile(tsFolder, "*.ts");
            }
            if (containsConfig)
            {
                AddAllSpecifiedFile(configFolder, "*.csv");
            } else
            {
                //AddZipCsvFile(configFolder, "*.db");
                //AddZipCsvFile(configFolder, "*.binary");
            }
            foreach (string filePath in fileNameList)
            {
                Console.WriteLine("===>{0}", filePath);
                //string regexStr = "(\"[^\"]*[\u4e00-\u9fa5]+[^\"]*\")|('[^']*[\u4e00-\u9fa5]+[^']*')"
                string regexStr = "(\"[^\"]*[\u4e00-\u9fa5]+[^\"]*\")|('[^']*[\u4e00-\u9fa5]+[^']*')|(`[^`]*[\u4e00-\u9fa5]+[^`]*`)";
                if (filePath.Contains(".csv"))
                {
                    regexStr = "[\u4e00-\u9fa5]";
                }
                string[] fileLines = File.ReadAllLines(filePath);
                for (int i = 0; i < fileLines.Length; i++)
                {
                    string[] split_strings = fileLines[i].Split(spe, StringSplitOptions.None);

                    MatchCollection matches = Regex.Matches(split_strings[0], regexStr);
                    if (matches.Count <= 0)
                    {
                        continue;
                    }
                    foreach (var mathStr in matches)
                    {
                        List<char> charList = mathStr.ToString().ToList<char>();
                        foreach (char character in charList)
                        {
                            string temp = character.ToString();
                            MatchCollection matches1 = Regex.Matches(temp, "[\u4300-\u9fa5]");
                            if (matches1.Count <= 0)
                            {
                                continue;
                            }
                            //Console.Write(temp);
                            if (charDic.ContainsKey(temp))
                            {
                                continue;
                            }
                            charDic[temp] = true;
                            languageText.Append(temp);
                        }

                    }
                }
                Console.WriteLine("");
            }
            if (!File.Exists(txtPath))
            {
                File.Create(txtPath).Close();
            }
            StreamReader sr1 = new StreamReader(specialCharsPath, Encoding.Default);
            string specialChars = sr1.ReadToEnd();
            languageText.Append(specialChars);
            sr1.Close();
            StreamWriter sw1 = new StreamWriter(txtPath, false, new System.Text.UTF8Encoding(true));  //使用utf8-BOM编码
            sw1.Write(languageText.ToString());
            sw1.Close();
            int index = 0;
            while (File.Exists(@"..\..\..\..\mainfnt_" + index + ".png"))
            {
                File.Delete(@"..\..\..\..\mainfnt_" + index + ".png");
                index++;
            }
            Process proc = new Process();
            string targetDir = string.Format(@".\");
            proc.StartInfo.WorkingDirectory = targetDir;
            proc.StartInfo.FileName = "genBMFont.bat";
            Console.WriteLine("bmFontExePath======{0}", bmFontExePath);
            proc.StartInfo.Arguments = string.Format(bmFontExePath);
            proc.Start();
            proc.WaitForExit();
            //todo
            StreamReader reader = new StreamReader(fontFntPath, Encoding.Default);
            String fntContent = reader.ReadToEnd();
            fntContent = fntContent.Replace("size=-", "size=");
            StreamWriter readTxt = new StreamWriter(fontFntPathTemp, false, Encoding.Default);
            readTxt.Write(fntContent);
            readTxt.Flush();
            readTxt.Close();
            reader.Close();
            File.Copy(fontFntPathTemp,fontFntPath, true);
            File.Delete(fontFntPathTemp);

            Console.WriteLine("Done!");
            Console.ReadKey();

        }
        public static void Run(PeriodicalList periodicalList)
        {
            var    project  = periodicalList.Project;
            string fileName = null;

            var journalCollection = new List <Periodical>();

            try
            {
                using (var openFileDialog = new OpenFileDialog
                {
                    Filter = Properties.Resources.FileMacroOpenFileDialogFilters,
                    Title = Properties.Resources.FileMacroOpenFileDialogSubject
                })
                {
                    if (openFileDialog.ShowDialog(periodicalList) != DialogResult.OK)
                    {
                        return;
                    }

                    fileName = openFileDialog.FileName;
                }

                Cursor.Current = Cursors.WaitCursor;

                string journalList;
                var    enc = GetFileEncoding(fileName);
                using (var streamReader = new StreamReader(fileName, enc))
                {
                    journalList = streamReader.ReadToEnd();
                    streamReader.Close();
                }

                var testRegex = new Regex("[\x00-\x1f-[\t\n\r]]", RegexOptions.CultureInvariant | RegexOptions.Compiled);
                if (testRegex.IsMatch(journalList))
                {
                    Cursor.Current = Cursors.Default;
                    MessageBox.Show(periodicalList, Properties.Resources.FileMacroNotSupportedCharactersMessage, periodicalList.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }


                var matchRegex = new Regex(
                    @"^(?<FullName>[^#=;|\t\n]+?)(?: *[#=;|\t] *(?<Abbreviation1>[^#=;|\t\n]*))?(?: *[#=;|\t] *(?<Abbreviation2>[^#=;|\t\n]*))?(?: *[#=;|\t] *(?<Abbreviation3>[^#=;|\t\n]*))?(?: *[#=;|\t] *(?<ISSN>[^#=;|\t\n]*))??$",
                    RegexOptions.CultureInvariant
                    | RegexOptions.Compiled
                    | RegexOptions.Multiline    //IMPORTANT!
                    );


                var    matchCollection = matchRegex.Matches(journalList);
                string sISSN           = string.Empty;

                foreach (Match match in matchCollection)
                {
                    if (string.IsNullOrEmpty(match.Groups["FullName"].Value))
                    {
                        continue;
                    }

                    var journal = new Periodical(project, match.Groups["FullName"].Value);
                    if (!string.IsNullOrEmpty(match.Groups["Abbreviation1"].Value))
                    {
                        journal.StandardAbbreviation = match.Groups["Abbreviation1"].Value;
                    }
                    if (!string.IsNullOrEmpty(match.Groups["Abbreviation2"].Value))
                    {
                        journal.UserAbbreviation1 = match.Groups["Abbreviation2"].Value;
                    }
                    if (!string.IsNullOrEmpty(match.Groups["Abbreviation3"].Value))
                    {
                        journal.UserAbbreviation2 = match.Groups["Abbreviation3"].Value;
                    }

                    if (!string.IsNullOrEmpty(match.Groups["ISSN"].Value))
                    {
                        sISSN = match.Groups["ISSN"].Value;
                        if (IssnValidator.IsValid(sISSN))
                        {
                            journal.Issn = sISSN;
                        }
                    }

                    journalCollection.Add(journal);
                }

                project.Periodicals.AddRange(journalCollection);
            }

            catch (Exception exception)
            {
                Cursor.Current    = Cursors.Default;
                journalCollection = null;
                MessageBox.Show(periodicalList, exception.ToString(), periodicalList.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            finally
            {
                Cursor.Current = Cursors.Default;

                if (journalCollection != null)
                {
                    MessageBox.Show(periodicalList, Properties.Resources.FileMacroResultMessage.FormatString(journalCollection.Count), periodicalList.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            var filePath1 = string.Empty;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "D:\\Facultate Git\\FacultateAn3Sem2\\CN\\Tema2";
                openFileDialog.Filter           = "txt files (.txt)|.txt|All files (.)|*.*";
                openFileDialog.FilterIndex      = 2;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    filePath1 = openFileDialog.FileName;
                }
            }

            string sA = System.IO.File.ReadAllText(filePath1);

            int n = 0;

            while (sA[n] != '\n')
            {
                n++;
            }

            double[,] A  = new double[n / 2, n / 2];
            double[,] _A = new double[n / 2, n / 2];

            int i = 0, j = 0;
            int max = 0;

            foreach (var row in sA.Split('\n'))
            {
                j = 0;
                int nr = 0;
                foreach (var col in row.Trim().Split(' '))
                {
                    if (col.Trim().Contains('.'))
                    {
                        nr++;
                    }
                    A[i, j]  = double.Parse(col.Trim(), System.Globalization.CultureInfo.InvariantCulture);
                    _A[i, j] = (double)A[i, j];
                    j++;
                }
                if (nr > max)
                {
                    max = nr;
                }
                i++;
            }
            if (max != 0)
            {
                n = n - max;
            }
            n = n / 2;


            double[,] A_init = new double[n, n];

            for (i = 0; i < n; i++)
            {
                for (j = 0; j < n; j++)
                {
                    A_init[i, j] = A[i, j];
                }
            }



            double[,] L = new double[n, n];
            double[,] U = new double[n, n];



            for (i = 0; i < n; i++)
            {
                for (int k = i; k < n; k++)
                {
                    double sum = 0;
                    for (j = 0; j < i; j++)
                    {
                        sum += (L[i, j] * U[j, k]);
                    }
                    U[i, k] = A[i, k] - sum;
                    A[i, k] = A_init[i, k] - sum;
                }

                for (int k = i; k < n; k++)
                {
                    if (i == k)
                    {
                        L[i, i] = 1;
                    }
                    if (i != k)
                    {
                        double sum = 0;
                        for (j = 0; j < i; j++)
                        {
                            sum += (L[k, j] * U[j, i]);
                        }
                        L[k, i] = ((double)A[k, i] - sum) / U[i, i];
                        A[k, i] = ((double)A_init[k, i] - sum) / U[i, i];
                    }
                }
            }

            label1.Text = "descompunerea LU intr-o singura matrice\n";

            for (i = 0; i < n; i++)
            {
                for (j = 0; j < n; j++)
                {
                    label1.Text += (A[i, j].ToString() + " ");
                }
                label1.Text += '\n';
            }



            //==================================
            var filePath2 = string.Empty;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "D:\\Facultate Git\\FacultateAn3Sem2\\CN\\Tema2";
                openFileDialog.Filter           = "txt files (.txt)|.txt|All files (.)|*.*";
                openFileDialog.FilterIndex      = 2;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    filePath1 = openFileDialog.FileName;
                }
            }

            string sb = System.IO.File.ReadAllText(filePath1);
            int    m;

            m = n;


            double[,] b      = new double[m, 1];
            double[,] b_init = new double[m, 1];
            int l = 0;

            foreach (var element in sb.Split('\n'))
            {
                b[l, 0] = (double)int.Parse(element);
                l++;
            }
            for (i = 0; i < m; i++)
            {
                Console.WriteLine(b[i, 0]);
            }

            for (i = 0; i < m; i++)
            {
                b_init[i, 0] = b[i, 0];
            }
            double[,] y = new double[m, 1];

            //y[0, 0] = b[0, 0];
            for (i = 1; i < n; i++)
            {
                double sum = 0;
                for (j = 0; j < n; j++)
                {
                    if (i > j)
                    {
                        sum += A[i, j] * b[j, 0];
                    }
                    if (i == j)
                    {
                        //y[j, 0] = (b[j, 0] - sum);
                        b[j, 0] = (b[j, 0] - sum);
                    }
                }
            }
            label2.Text = "Matricea Y\n";
            Console.WriteLine("Y:");
            for (i = 0; i < m; i++)
            {
                label2.Text += b[i, 0].ToString() + '\n';
            }
            //Console.WriteLine(b[i, 0]);

            double[,] x = new double[m, 1];

            x[m - 1, 0] = b[m - 1, 0] / A[n - 1, n - 1];


            for (i = n - 2; i >= 0; i--)
            {
                double sum = 0;
                for (j = n - 1; j >= 0; j--)
                {
                    if (i < j)
                    {
                        sum += A[i, j] * x[j, 0];
                    }
                    else
                    {
                        x[j, 0] = (b[j, 0] - sum) / A[i, j];
                    }
                }
            }

            Console.WriteLine("X:");
            label3.Text = "Matricea X\n";
            for (i = 0; i < m; i++)
            {
                label3.Text += x[i, 0].ToString() + '\n';
            }
            //Console.WriteLine(x[i, 0]);
            Console.WriteLine("======================");

            double[] vectorRezultate = new double[m];

            for (i = 0; i < m; i++)
            {
                double sum = 0;
                for (j = 0; j < m; j++)
                {
                    sum += A_init[i, j] * x[j, 0];
                }

                vectorRezultate[i] = sum;
            }

            for (i = 0; i < n; i++)
            {
                vectorRezultate[i] -= b_init[i, 0];
            }

            label4.Text = "Norma ||A_init * x_Lu - b_init||2 este " + Norma(vectorRezultate).ToString();
            //Console.WriteLine("Norma este egala cu : " + Norma(vectorRezultate));

            Matrix <double> A_check = DenseMatrix.OfArray(A_init);
            Matrix <double> b_check = DenseMatrix.OfArray(b_init);

            Console.WriteLine("Inversa matricei A este : ");
            A_check = A_check.Inverse();
            for (i = 0; i < n; i++)
            {
                for (j = 0; j < n; j++)
                {
                    Console.Write(A_check[i, j].ToString());
                }
                Console.WriteLine();
            }

            var x_lib = A_check.Multiply(b_check);

            Console.WriteLine("Rezultatul ecuatiei Ax=b este:");

            for (i = 0; i < n; i++)
            {
                Console.WriteLine(x_lib[i, 0].ToString());
            }



            for (i = 0; i < n; i++)
            {
                vectorRezultate[i] = x[i, 0] - x_lib[i, 0];
            }

            //Console.WriteLine("Norma ||X_LU - X_LIB||2 este : ");
            label5.Text = "Norma ||X_LU - X_LIB||2 este " + Norma(vectorRezultate).ToString();
            //Console.WriteLine(Norma(vectorRezultate));


            //Console.WriteLine("Ultima norma : ");

            double[] vectorIntermedia = new double[m];

            for (i = 0; i < m; i++)
            {
                double sum = 0;
                for (j = 0; j < m; j++)
                {
                    sum += A_check[i, j] * b_init[j, 0];
                }
                vectorRezultate[i] = sum;
            }

            for (i = 0; i < n; i++)
            {
                vectorRezultate[i] = x[i, 0] - vectorRezultate[i];
            }

            label6.Text = "Norma ||x_LU - A_invers_lib * b_init este " + Norma(vectorRezultate).ToString();

            Console.WriteLine(Norma(vectorRezultate));
        }
Exemple #40
0
        private void BUT_samplephoto_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = "*.jpg|*.jpg";

            ofd.ShowDialog();

            if (File.Exists(ofd.FileName))
            {
                string fn = ofd.FileName;

                Metadata lcMetadata = null;
                try
                {
                    FileInfo lcImgFile = new FileInfo(fn);
                    // Loading all meta data
                    lcMetadata = JpegMetadataReader.ReadMetadata(lcImgFile);
                }
                catch (JpegProcessingException ex)
                {
                    log.InfoFormat(ex.Message);
                    return;
                }

                foreach (AbstractDirectory lcDirectory in lcMetadata)
                {
                    foreach (var tag in lcDirectory)
                    {
                        Console.WriteLine(lcDirectory.GetName() + " - " + tag.GetTagName() + " " + tag.GetTagValue().ToString());
                    }

                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_EXIF_IMAGE_HEIGHT))
                    {
                        TXT_imgheight.Text = lcDirectory.GetInt(ExifDirectory.TAG_EXIF_IMAGE_HEIGHT).ToString();
                    }

                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_EXIF_IMAGE_WIDTH))
                    {
                        TXT_imgwidth.Text = lcDirectory.GetInt(ExifDirectory.TAG_EXIF_IMAGE_WIDTH).ToString();
                    }

                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_FOCAL_PLANE_X_RES))
                    {
                        var unit = lcDirectory.GetFloat(ExifDirectory.TAG_FOCAL_PLANE_UNIT);

                        // TXT_senswidth.Text = lcDirectory.GetDouble(ExifDirectory.TAG_FOCAL_PLANE_X_RES).ToString();
                    }

                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_FOCAL_PLANE_Y_RES))
                    {
                        var unit = lcDirectory.GetFloat(ExifDirectory.TAG_FOCAL_PLANE_UNIT);

                        // TXT_sensheight.Text = lcDirectory.GetDouble(ExifDirectory.TAG_FOCAL_PLANE_Y_RES).ToString();
                    }

                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_FOCAL_LENGTH))
                    {
                        try
                        {
                            var item = lcDirectory.GetFloat(ExifDirectory.TAG_FOCAL_LENGTH);
                            num_focallength.Value = (decimal)item;
                        }
                        catch { }
                    }


                    if (lcDirectory.ContainsTag(ExifDirectory.TAG_DATETIME_ORIGINAL))
                    {
                    }
                }
            }
        }
        // Files :
        private void Importfile_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();

            file.Filter           = "Pdf Files (*.pdf)|*.pdf|Excel Files (*.xls)|*.xls|Word Files (*.docx)|*.docx|All files (*.*)|*.*";
            file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            file.Multiselect      = true; //On peut selectionner multiple fichiers
            if (file.ShowDialog() == true)
            {
                //Si l'utilisatuer selectionne aucun fichier
                if (file.FileNames.Length == 0)
                {
                    cpt_files = 0;   //un compteur qui compte le nombre des fichiers selectionnés
                    files.Clear();
                    AddfilesCard.Visibility   = Visibility.Visible;
                    FilesChipsCard.Visibility = Visibility.Hidden;
                }
                //si il selectionne un ficher
                else if (file.FileNames.Length == 1)
                {
                    AddfilesCard.Visibility   = Visibility.Hidden;
                    FilesChipsCard.Visibility = Visibility.Visible;
                    cpt_files        = 1; //un compteur qui compte le nombre des fichiers selectionnés
                    File1.Visibility = Visibility.Visible;
                    File1.Content    = file.SafeFileNames[0];
                    files.Add(file.FileNames[0]);
                }
                // si il selectionne deux fichiers
                else if (file.FileNames.Length == 2)
                {
                    AddfilesCard.Visibility   = Visibility.Hidden;
                    FilesChipsCard.Visibility = Visibility.Visible;

                    cpt_files        = 2; //un compteur qui compte le nombre des fichiers selectionnés
                    File1.Visibility = Visibility.Visible;
                    File2.Visibility = Visibility.Visible;
                    files.Clear();
                    foreach (string filename in file.SafeFileNames)
                    {
                        files.Add(filename);
                    }
                    File1.Content = files[0];
                    File1.ToolTip = files[0];
                    File2.Content = files[1];
                    File2.ToolTip = files[1];
                }
                // si il selectionne trois fichiers
                else if (file.FileNames.Length == 3)
                {
                    AddfilesCard.Visibility   = Visibility.Hidden;
                    FilesChipsCard.Visibility = Visibility.Visible;

                    cpt_files        = 3; //un compteur qui compte le nombre des fichiers selectionnés
                    File1.Visibility = Visibility.Visible;
                    File2.Visibility = Visibility.Visible;
                    File3.Visibility = Visibility.Visible;
                    files.Clear();
                    foreach (string filename in file.SafeFileNames)
                    {
                        files.Add(filename);
                    }
                    File1.Content = files[0];
                    File1.ToolTip = files[0];
                    File2.Content = files[1];
                    File2.ToolTip = files[1];
                    File3.Content = files[2];
                    File3.ToolTip = files[2];
                }
                // s'il selectionne plus de trois fichiers
                else if (file.FileNames.Length > 3)
                {
                    MessageBox.Show("Veuillez choisir trois fichiers seulement");
                    cpt_files = 0;   //un compteur qui compte le nombre des fichiers selectionnés
                }
            }
        }
Exemple #42
0
        private void OpenNewFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.ShowDialog();
        }
 private void InitializeComponent()
 {
     System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(離線列印Client程式.frmJetExeList));
     panelPrint = new System.Windows.Forms.Panel();
     btnInsert  = new System.Windows.Forms.Button();
     btnRemove  = new System.Windows.Forms.Button();
     ltExes     = new System.Windows.Forms.ListBox();
     fdJetExe   = new System.Windows.Forms.OpenFileDialog();
     btnConfirm = new System.Windows.Forms.Button();
     panelPrint.SuspendLayout();
     SuspendLayout();
     panelPrint.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
     panelPrint.Controls.Add(btnConfirm);
     panelPrint.Controls.Add(ltExes);
     panelPrint.Controls.Add(btnRemove);
     panelPrint.Controls.Add(btnInsert);
     panelPrint.Location = new System.Drawing.Point(6, 7);
     panelPrint.Name     = "panelPrint";
     panelPrint.Size     = new System.Drawing.Size(482, 360);
     panelPrint.TabIndex = 3;
     btnInsert.Font      = new System.Drawing.Font("新細明體", 12f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 136);
     btnInsert.Location  = new System.Drawing.Point(159, 4);
     btnInsert.Name      = "btnInsert";
     btnInsert.Size      = new System.Drawing.Size(75, 29);
     btnInsert.TabIndex  = 0;
     btnInsert.Text      = "新增";
     btnInsert.UseVisualStyleBackColor = true;
     btnInsert.Click   += new System.EventHandler(btnInsert_Click);
     btnRemove.Font     = new System.Drawing.Font("新細明體", 12f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 136);
     btnRemove.Location = new System.Drawing.Point(240, 4);
     btnRemove.Name     = "btnRemove";
     btnRemove.Size     = new System.Drawing.Size(75, 29);
     btnRemove.TabIndex = 1;
     btnRemove.Text     = "刪除";
     btnRemove.UseVisualStyleBackColor = true;
     btnRemove.Click           += new System.EventHandler(btnRemove_Click);
     ltExes.FormattingEnabled   = true;
     ltExes.HorizontalScrollbar = true;
     ltExes.ItemHeight          = 12;
     ltExes.Location            = new System.Drawing.Point(4, 39);
     ltExes.Name          = "ltExes";
     ltExes.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
     ltExes.Size          = new System.Drawing.Size(469, 316);
     ltExes.TabIndex      = 2;
     fdJetExe.Filter      = "執行檔 (*.exe)|*.exe";
     fdJetExe.Title       = "請選擇噴墨執行檔";
     btnConfirm.Font      = new System.Drawing.Font("新細明體", 12f, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 136);
     btnConfirm.Location  = new System.Drawing.Point(398, 4);
     btnConfirm.Name      = "btnConfirm";
     btnConfirm.Size      = new System.Drawing.Size(75, 29);
     btnConfirm.TabIndex  = 3;
     btnConfirm.Text      = "確認";
     btnConfirm.UseVisualStyleBackColor = true;
     btnConfirm.Click        += new System.EventHandler(btnConfirm_Click);
     base.AutoScaleDimensions = new System.Drawing.SizeF(6f, 12f);
     base.AutoScaleMode       = System.Windows.Forms.AutoScaleMode.Font;
     base.ClientSize          = new System.Drawing.Size(493, 370);
     base.Controls.Add(panelPrint);
     base.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
     base.Icon            = (System.Drawing.Icon)resources.GetObject("$this.Icon");
     base.Name            = "frmJetExeList";
     base.StartPosition   = System.Windows.Forms.FormStartPosition.CenterScreen;
     Text       = "噴墨列印執行檔增修";
     base.Load += new System.EventHandler(frmJetExeList_Load);
     panelPrint.ResumeLayout(false);
     ResumeLayout(false);
 }
Exemple #44
0
        /// <summary>
        /// mapping matrix
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Rectify_Click(object sender, EventArgs e)
        {
            XmlDocument       doc      = new XmlDocument();
            XmlReaderSettings settings = new XmlReaderSettings();

            settings.IgnoreComments = true;
            XmlReader reader;

            OpenFileDialog dlg = new OpenFileDialog();

            dlg.Filter = "*.xml|*.xml";
            if (DialogResult.OK == dlg.ShowDialog())
            {
                string str = dlg.FileName.Trim();
                reader = XmlReader.Create(str, settings);
                doc.Load(reader);
            }
            else
            {
                return;
            }

            //root node
            XmlNode xmlNode = doc.SelectSingleNode("opencv_storage");
            //chile node
            XmlNodeList xmlList = xmlNode.ChildNodes;

            foreach (XmlNode xmlnode in xmlList)
            {
                XmlNodeList xn = xmlnode.ChildNodes;
                //intrinsic and distortion param
                if ("matrix_left" == xmlnode.Name)
                {
                    for (int i = 0; i < 9; i++)
                    {
                        intrinsicParam.IntrinsicMatrix[i / 3, i % 3] = Convert.ToDouble(xn.Item(i).InnerText);
                    }
                }
                else if ("distortion_left" == xmlnode.Name)
                {
                    for (int i = 0; i < 5; i++)
                    {
                        intrinsicParam.DistortionCoeffs[i, 0] = Convert.ToDouble(xn.Item(i).InnerText);
                    }
                }
            }

            CvInvoke.cvInitUndistortMap(intrinsicParam.IntrinsicMatrix, intrinsicParam.DistortionCoeffs,
                                        mapx, mapy);

            isCalibrating = true;
            isCalibrated  = true;

            SetText(textBox1, intrinsicParam.IntrinsicMatrix[0, 0].ToString());
            SetText(textBox2, intrinsicParam.IntrinsicMatrix[1, 1].ToString());
            SetText(textBox3, intrinsicParam.IntrinsicMatrix[0, 2].ToString());
            SetText(textBox4, intrinsicParam.IntrinsicMatrix[1, 2].ToString());

            SetText(textBox5, intrinsicParam.DistortionCoeffs[0, 0].ToString());
            SetText(textBox6, intrinsicParam.DistortionCoeffs[1, 0].ToString());
            SetText(textBox7, intrinsicParam.DistortionCoeffs[4, 0].ToString());
            SetText(textBox8, intrinsicParam.DistortionCoeffs[2, 0].ToString());
            SetText(textBox9, intrinsicParam.DistortionCoeffs[3, 0].ToString());
        }
Exemple #45
0
        /// <summary>
        /// take each room data and create a list of enemies that Class Room will store
        /// </summary>
        /// <param name="fs"></param>
        public void createRooms(TextReader reader, Program x)
        {
            try
            {
                int number;

                int trash;
                number = int.Parse(reader.ReadLine()); //get number of rooms
                rooms  = new Room[number];
                reader.ReadLine();                     //drop first room number
                for (int y = 0; y < number; y++)       //create an array for all rooms
                {
                    enemies = new List <Enemy>();
                    string data = reader.ReadLine();
                    while (!int.TryParse(data, out trash))//cycle until the next room is reached
                    {
                        data = data.ToLower();
                        if (data.Equals("minor"))
                        {
                            enemies.Add(new Minor());
                        }
                        else if (data.Equals("normal"))
                        {
                            enemies.Add(new Normal());
                        }
                        else if (data.Equals("shadow"))
                        {
                            enemies.Add(new Shadow());
                        }
                        else if (data.Equals("greater"))
                        {
                            enemies.Add(new Greater());
                        }
                        else if (data.Equals("sniper"))
                        {
                            enemies.Add(new Sniper());
                        }
                        else if (data.Equals("crowman"))
                        {
                            enemies.Add(new Crowman());
                        }
                        else if (data.Equals("ninja"))
                        {
                            enemies.Add(new Ninja());
                        }
                        else
                        {
                            throw new MissingMemberException();
                        }
                        data = reader.ReadLine();
                    }
                    rooms[y] = new Room(enemies, x, this);
                }
                x.last = number;
            }
            catch (MissingMemberException)
            {
                new Popup("The file contained an error, there was an undeclared enemy type.\r\n Please make sure that all enemies are either minor, normal, shadow, greater, sniper, crowman, or ninja").Show();
                System.Threading.Thread.Sleep(5000);              //give user time to click okay
                OpenFileDialog dlg = new OpenFileDialog();        // prompt for file
                dlg.Filter           = "txt files (*.txt)|*.txt"; // just text
                dlg.FilterIndex      = 1;                         // only one option
                dlg.RestoreDirectory = false;                     // let player keep opening same directory
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    using (reader = File.OpenText(dlg.FileName))
                        createRooms(reader, x);
                }
            }
            reader.Close();
        }
Exemple #46
0
        private void button1_Click(object sender, EventArgs e)
        {
            string         FilenameofImage = "";;
            OpenFileDialog fg = new OpenFileDialog();

            if (DialogResult.OK == fg.ShowDialog())
            {
                textBox1.Text   = fg.FileName;
                FilenameofImage = fg.SafeFileName;
                if (File.Exists(textBox1.Text))
                {
                    pictureBox1.Image = Image.FromFile(textBox1.Text);
                    pictureBox1.Refresh();
                }
            }

            byte[] imgLogo = new byte[] { };
            if (File.Exists(textBox1.Text))
            {
                StreamReader strImg = new StreamReader(textBox1.Text);
                imgLogo = new byte[File.ReadAllBytes(textBox1.Text).Length];
                imgLogo = File.ReadAllBytes(textBox1.Text);
                strImg.Close();
            }
            int Count = 0;

            string db = Environment.CurrentDirectory.ToString();

            using (SqlConnection con = new SqlConnection(string.Format(@"Data Source=(LocalDB)\v11.0;AttachDbFilename={0}\AppData.mdf;Integrated Security=True", db)))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("Select TOP 1   [IMAGE] FROM  [IMAGES] Where Type=@Type AND Code=1", con);
                    cmd.Parameters.AddWithValue("@Type", FilenameofImage);
                    SqlDataReader rdr = cmd.ExecuteReader();

                    if (rdr.HasRows)
                    {
                        while (rdr.Read())
                        {
                            byte[] img = (byte[])rdr["IMAGE"];
                            for (int i = 0; i < img.Length; i++)
                            {
                                if (img[i] == imgLogo[i])
                                {
                                    Count++;
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                    if (Count == imgLogo.Length)
                    {
                        rdr.Close();

                        RenderImage(FilenameofImage);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    con.Close();
                }
            }
        }
Exemple #47
0
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            prc_folderpath = "";

            OpenFileDialog tbox = new OpenFileDialog();

            tbox.Multiselect = false;
            tbox.Filter      = "Excel Files(*.xls,*.xlsx,*.xlsm,*.xlsb)|*.xls;*.xlsx;*.xlsm;*.xlsb";
            if (tbox.ShowDialog() == DialogResult.OK)
            {
                prc_folderpath = tbox.FileName;
            }
            if (prc_folderpath == null || prc_folderpath == "")
            {
                return;
            }
            if (MessageBox.Show("是否继续上传 ?", "Info", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
            }
            else
            {
                return;
            }


            try
            {
                InitialBackGroundWorker();
                bgWorker.DoWork += new DoWorkEventHandler(CheckCaseList);

                bgWorker.RunWorkerAsync();
                // 启动消息显示画面
                frmMessageShow = new frmMessageShow(clsShowMessage.MSG_001,
                                                    clsShowMessage.MSG_007,
                                                    clsConstant.Dialog_Status_Disable);
                frmMessageShow.ShowDialog();
                // 数据读取成功后在画面显示
                if (blnBackGroundWorkIsOK)
                {
                    this.dataGridView1.DataSource = null;

                    this.dataGridView1.AutoGenerateColumns = false;
                    if (Orderinfolist_Server != null)
                    {
                        sortableOrderList         = new SortableBindingList <clsOrderinfo>(Orderinfolist_Server);
                        bindingSource1.DataSource = new SortableBindingList <clsOrderinfo>(Orderinfolist_Server);

                        this.dataGridView1.DataSource = bindingSource1;

                        this.toolStripLabel1.Text = "已上传条目: " + Orderinfolist_Server.Count;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("12320" + ex);
                return;

                throw ex;
            }
        }
Exemple #48
0
        private void openObjFlowxmlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog()
            {
                Title            = "Open ObjFlow.xml",
                InitialDirectory = @"C:\Users\User\Desktop",
                Filter           = "xml file|*.xml"
            };

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

            System.IO.FileStream fs1 = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);                                                  //ファイルを開く
            System.Xml.Serialization.XmlSerializer s1 = new System.Xml.Serialization.XmlSerializer(typeof(MK8_ObjFlow.xml_Reader.ObjFlow_Xml.ObjFlow_Read_ROOT)); //ObjFlow_ROOT.cs
            MK8_ObjFlow.xml_Reader.ObjFlow_Xml.ObjFlow_Read_ROOT BYAML_XML_Model = (MK8_ObjFlow.xml_Reader.ObjFlow_Xml.ObjFlow_Read_ROOT)s1.Deserialize(fs1);     //MK8_ObjFlow.xml_Reader.ObjFlow_Xml.ObjFlow_ROOTクラスの内容をデシリアライズ

            foreach (MK8_ObjFlow.xml_Reader.ObjFlow_Xml.Value_Array BYAML_XML_UMDL in BYAML_XML_Model.Value_Arrays)                                               //foreachで繰り返し要素のあるXMLを読み込む
            {
                //dataGridViewに表示
                dataGridView1.Rows.Add(BYAML_XML_UMDL.AiReact,
                                       BYAML_XML_UMDL.CalcCut,
                                       BYAML_XML_UMDL.Clip,
                                       BYAML_XML_UMDL.ClipRadius,
                                       BYAML_XML_UMDL.ColOffsetY,
                                       BYAML_XML_UMDL.ColShape,
                                       BYAML_XML_UMDL.DemoCameraCheck,
                                       BYAML_XML_UMDL.LightSetting,
                                       BYAML_XML_UMDL.Lod1,
                                       BYAML_XML_UMDL.Lod2,
                                       BYAML_XML_UMDL.Lod_NoDisp,
                                       BYAML_XML_UMDL.MgrId,
                                       BYAML_XML_UMDL.ModelDraw,
                                       BYAML_XML_UMDL.ModelEffNo,
                                       BYAML_XML_UMDL.MoveBeforeSync,
                                       BYAML_XML_UMDL.NotCreate,
                                       BYAML_XML_UMDL.ObjId,
                                       BYAML_XML_UMDL.Offset,
                                       BYAML_XML_UMDL.Origin,
                                       BYAML_XML_UMDL.PackunEat,
                                       BYAML_XML_UMDL.PathType,
                                       BYAML_XML_UMDL.PylonReact,
                                       BYAML_XML_UMDL.VR);

                dataGridView2.Rows.Add(BYAML_XML_UMDL.ColSize.X_Val,
                                       BYAML_XML_UMDL.ColSize.Y_Val,
                                       BYAML_XML_UMDL.ColSize.Z_Val,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[0].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[1].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[2].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[3].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[4].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[5].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[6].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[7].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[8].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[9].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[10].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[11].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[12].ItemVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[0].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[1].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[2].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[3].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[4].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[5].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[6].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[7].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[8].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[9].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[10].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[11].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[12].ItemObjVal,
                                       BYAML_XML_UMDL.Karts.Kart_Value_Ary[0].KartVal,
                                       BYAML_XML_UMDL.Karts.Kart_Value_Ary[1].KartVal,
                                       BYAML_XML_UMDL.Karts.Kart_Value_Ary[2].KartVal,
                                       BYAML_XML_UMDL.Karts.Kart_Value_Ary[3].KartVal,
                                       BYAML_XML_UMDL.KartObjs.KartObj_Value_Ary[0].KartObjVal,
                                       BYAML_XML_UMDL.KartObjs.KartObj_Value_Ary[1].KartObjVal,
                                       BYAML_XML_UMDL.KartObjs.KartObj_Value_Ary[2].KartObjVal,
                                       BYAML_XML_UMDL.KartObjs.KartObj_Value_Ary[3].KartObjVal,
                                       BYAML_XML_UMDL.Label.Label_String,
                                       BYAML_XML_UMDL.ResNames.ResName_Value_Ary[0].ResNameStr);
            }
            fs1.Close();
        }
Exemple #49
0
        private void BTN_SpedFiscal_Click(object sender, EventArgs e)
        { // pegando um arquivo so
            switch (Rad_Seleciona1.Checked)
            {
            // caso esteja selecionado para importar um arquivo
            case true:


                OpenFileDialog SelecionarSPED = new OpenFileDialog();
                SelecionarSPED.DefaultExt = "txt";
                SelecionarSPED.Filter     = "arquivo de texto (*.txt;)|*.txt*.*";
                SelecionarSPED.ShowDialog();
                // recebe o diretorio e o nome do arquivo selecionado
                String nomearquivo = SelecionarSPED.FileName;
                string NomeArquivo = SelecionarSPED.SafeFileName;
                Stream entrada     = File.Open(nomearquivo, FileMode.Open);

                StreamReader leitor       = new StreamReader(entrada);
                string       linha        = leitor.ReadLine();
                string       p_query_CNPJ = "";
                while (linha != null)
                {
                    string Registro         = "C190";
                    string p_query_registro = "";
                    string p_query_CFOP     = "";
                    string p_query_V_ICMS   = "";
                    string p_query          = "'";
                    string liquota          = "";
                    string operacao         = "";
                    string situacao         = "";
                    string ICMS             = "";
                    //string p_query_CNPJ = "";
                    string   inicio        = "0000";
                    int      tamanhoString = 0;
                    String[] CFOP          = new String[5] {
                        "5102", "6102", "1102", "1202", "2102"
                    };
                    int contador = 0;
                    int y        = 0;
                    for (int x = 0; x < CFOP.Length; x++)
                    {
                        // procura a linha que comece com o registro e o CFOP cadastrado

                        if (linha.Substring(1, 4) == Registro && linha.Substring(10, 4) == CFOP[x].ToString())
                        {
                            // enquanto a linha nao terminar passa pro proximo caracter
                            for (y = 0; contador < 9; y++)
                            {
                                //contador de barras
                                if (linha[y].ToString() == "|")
                                {
                                    contador += 1;
                                }
                                // quando encontrar o campo do registro do CFOP e do ICMS separa o valor

                                if (contador == 1)
                                {
                                    if (linha[y].ToString() == "|")
                                    {
                                    }
                                    else
                                    {
                                        // se nao pega o caracter e adiciona na query
                                        p_query_registro += linha.Substring(y, 1);
                                    }
                                }
                                // pegar a situacao
                                if (contador == 2)
                                {
                                    if (linha[y].ToString() == "|")
                                    {
                                    }
                                    else
                                    {
                                        // se nao pega o caracter e adiciona na query
                                        situacao += linha.Substring(y, 1);
                                    }
                                }
                                if (contador == 3)
                                {
                                    if (linha[y].ToString() == "|")
                                    {
                                    }
                                    else
                                    {
                                        // se nao pega o caracter e adiciona na query
                                        p_query_CFOP += linha.Substring(y, 1);
                                    }
                                }
                                // pegar a liquota
                                if (contador == 4)
                                {
                                    if (linha[y].ToString() == "|")
                                    {
                                    }
                                    else
                                    {
                                        liquota += linha.Substring(y, 1);
                                    }
                                }
                                if (contador == 8)
                                {
                                    if (linha[y].ToString() == "|")
                                    {
                                    }
                                    else
                                    {
                                        // se nao pega o caracter e adiciona na query
                                        ICMS += linha.Substring(y, 1);
                                    }
                                }

                                tamanhoString++;

                                if (contador == 6)
                                {
                                    p_query += "'";
                                    contador++;
                                }


                                if (contador == 9)
                                {
                                    if (linha[y].ToString() == "|")
                                    {
                                    }
                                    else
                                    {
                                        // se nao pega o caracter e adiciona na query
                                        p_query_V_ICMS += linha.Substring(y, 1);
                                    }
                                }



                                tamanhoString += 1;
                            }
                        }


                        // pegar registro
                        if (p_query_CFOP == "5102" || p_query_CFOP == "6102")
                        {
                            operacao = "-";
                        }
                        else
                        {
                            operacao = "+";
                        }



                        //pegar cnpj

                        if (linha.Substring(1, 4) == inicio)
                        {
                            for (int tes = 0; tes < linha.Length; tes++)
                            {
                                if (linha[tes].ToString() == "|")
                                {
                                    contador += 1;
                                }

                                if (contador == 7)
                                {
                                    if (linha[tes].ToString() == "|")
                                    {
                                    }
                                    else
                                    {
                                        p_query_CNPJ += linha.Substring(tes, 1);
                                    }
                                }
                            }
                        }
                    }


                    String        strConexao = "Data Source=RAFAEL-PC;Initial Catalog=teste;Integrated Security=True";
                    Conexao       conexao    = new Conexao(strConexao);
                    SqlConnection conn       = new SqlConnection(@"Data Source=RAFAEL-PC;Initial Catalog=teste;Integrated Security=True");
                    try
                    {
                        if (p_query_CFOP != "" && ICMS != "" && liquota != "0" && situacao != "060")
                        {
                            // pega a data do arquivo
                            string p_query_data = NomeArquivo.Substring(28, 8);

                            //prepara o valor do icms pro banco
                            decimal valor = Convert.ToDecimal(ICMS);
                            // cria o comando sql
                            SqlCommand comando = new SqlCommand("P_InsertSped", conn);
                            // abre a conexao
                            conn.Open();
                            //prepara a query
                            comando.Parameters.AddWithValue("@Registro", p_query_registro);
                            comando.Parameters.AddWithValue("@Cfop", p_query_CFOP);
                            comando.Parameters.AddWithValue("@CNPJ", p_query_CNPJ);
                            comando.Parameters.AddWithValue("@operacao", operacao);
                            comando.Parameters.AddWithValue("@V_ICMS", valor);
                            comando.Parameters.AddWithValue("@Data", p_query_data);
                            comando.CommandType = CommandType.StoredProcedure;
                            // executa a query
                            comando.ExecuteNonQuery();
                            // fecha a conexao
                            conn.Close();
                        }
                        if (p_query_CFOP != "" && p_query_V_ICMS != "" && liquota != "0" && situacao == "060")
                        {
                            string p_query_data = NomeArquivo.Substring(28, 8);

                            //prepara o valor do icms pro banco
                            decimal valor = Convert.ToDecimal(p_query_V_ICMS);
                            // cria o comando sql
                            SqlCommand comando = new SqlCommand("P_InsertSped", conn);
                            // abre a conexao
                            conn.Open();
                            //prepara a query
                            comando.Parameters.AddWithValue("@Registro", p_query_registro);
                            comando.Parameters.AddWithValue("@Cfop", p_query_CFOP);
                            comando.Parameters.AddWithValue("@CNPJ", p_query_CNPJ);
                            comando.Parameters.AddWithValue("@operacao", operacao);
                            comando.Parameters.AddWithValue("@V_ICMS", valor);
                            comando.Parameters.AddWithValue("@Data", p_query_data);
                            comando.CommandType = CommandType.StoredProcedure;
                            // executa a query
                            comando.ExecuteNonQuery();
                            // fecha a conexao
                            conn.Close();
                        }
                        else
                        {
                            linha = leitor.ReadLine();
                        }
                    }
                    catch (Exception erro)
                    {
                        MessageBox.Show(erro.Message);
                    }
                }

                leitor.Close();
                entrada.Close();



                break;

            // caso esteja selecionado para importar uma basta
            case false:

                FolderBrowserDialog SelecionarPastaSPED = new FolderBrowserDialog();
                string sCaminhos;


                // seleciona a pasta
                SelecionarPastaSPED.ShowDialog();
                // salva o diretorio da pasta
                sCaminhos = SelecionarPastaSPED.SelectedPath;



                //pega a pasta

                DirectoryInfo pasta = new DirectoryInfo(sCaminhos);



                //iCountArqTxt = MetodosDeExtensao.ContagemTipoArquivo(sCaminhos, ".TXT");

                // prepara o endereco do diretorio
                String diretorio = "" + pasta + "";

                // pega os arquivos
                string[] arquivos = Directory.GetFiles(diretorio);

                for (int percorrer = 0; percorrer < arquivos.Length; percorrer++)
                {
                    Stream       arquivo          = File.Open(arquivos[percorrer], FileMode.Open);
                    StreamReader ponteiro         = new StreamReader(arquivo);
                    string       NomeArquivoPasta = arquivos[percorrer];
                    string       Proxima          = ponteiro.ReadLine();
                    while (Proxima != null)
                    {
                        string Registro = "C190";
                        string p_query  = "'";
                        // string p_query_CNPJ = "";
                        string   inicio        = "0000";
                        int      tamanhoString = 0;
                        String[] CFOP          = new String[5] {
                            "5102", "6102", "1102", "1202", "2102"
                        };
                        int contador = 0;
                        int y        = 0;
                        for (int x = 0; x < CFOP.Length; x++)
                        {
                            // procura a linha que comece com o registro e o CFOP cadastrado
                            if (Proxima.Substring(1, 4) == Registro && Proxima.Substring(10, 4) == CFOP[x].ToString())
                            {
                                for (int i = 0; i < Proxima.Length; i++)
                                {
                                    // enquanto a linha nao terminar passa pro proximo caracter
                                    for (y = 0; y < Proxima.Length; y++)
                                    {
                                        //contador de barras
                                        if (Proxima[y].ToString() == "|")
                                        {
                                            contador += 1;
                                        }

                                        tamanhoString++;
                                        // na primeira passada coloca as aspas duplas
                                        if (contador == 1 && y == 0)
                                        {
                                            p_query += "";
                                            y       += 1;
                                        }
                                        if (contador == 6)
                                        {
                                            p_query += "'";
                                            contador++;
                                        }
                                        // quando encontrar o campo do registro do CFOP e do ICMS separa o valor
                                        if (contador == 1 || contador == 3 || contador == 5)
                                        {
                                            // se o caracter da linha for =  | troca por ,
                                            if (Proxima[y].ToString() == "|")
                                            {
                                                p_query += "', '";
                                            }
                                            else
                                            {
                                                // se nao pega o caracter e adiciona na query
                                                p_query += Proxima.Substring(y, 1);
                                            }
                                        }
                                    }


                                    tamanhoString += 1;
                                }
                            }
                            // pegar cnpj
                            if (Proxima.Substring(1, 4) == inicio)
                            {
                                for (int tes = 0; tes < Proxima.Length; tes++)
                                {
                                    if (Proxima[tes].ToString() == "|")
                                    {
                                        contador += 1;
                                    }

                                    if (contador == 7)
                                    {
                                        if (Proxima[tes].ToString() == "|")
                                        {
                                        }
                                        else
                                        {
                                            //  p_query_CNPJ += Proxima.Substring(tes, 1);
                                        }
                                        // pega a data do arquivo
                                        string DataArquivo = NomeArquivoPasta.Substring(28, 8);
                                    }
                                }
                            }
                        }
                        linha = ponteiro.ReadLine();
                    }
                    ponteiro.Close();
                    arquivo.Close();
                }
                break;
            }
        }
Exemple #50
0
        private void BUT_shptopoly_Click(object sender, EventArgs e)
        {
            using (var fd = new OpenFileDialog())
            {
                fd.Filter = "Shape file|*.shp";
                var result = fd.ShowDialog();
                var file = fd.FileName;

                var pStart = new ProjectionInfo();
                var pESRIEnd = KnownCoordinateSystems.Geographic.World.WGS1984;
                var reproject = false;

                if (File.Exists(file))
                {
                    var prjfile = Path.GetDirectoryName(file) + Path.DirectorySeparatorChar +
                                  Path.GetFileNameWithoutExtension(file) + ".prj";
                    if (File.Exists(prjfile))
                    {
                        using (
                            var re =
                                File.OpenText(Path.GetDirectoryName(file) + Path.DirectorySeparatorChar +
                                              Path.GetFileNameWithoutExtension(file) + ".prj"))
                        {
                            pStart.ParseEsriString(re.ReadLine());

                            reproject = true;
                        }
                    }

                    var fs = FeatureSet.Open(file);

                    fs.FillAttributes();

                    var rows = fs.NumRows();

                    var dtOriginal = fs.DataTable;
                    for (var row = 0; row < dtOriginal.Rows.Count; row++)
                    {
                        var original = dtOriginal.Rows[row].ItemArray;
                    }

                    foreach (DataColumn col in dtOriginal.Columns)
                    {
                        Console.WriteLine(col.ColumnName + " " + col.DataType);
                    }

                    var a = 1;

                    var path = Path.GetDirectoryName(file);

                    foreach (var feature in fs.Features)
                    {
                        var sb = new StringBuilder();

                        sb.Append("#Shap to Poly - Mission Planner\r\n");
                        foreach (var point in feature.Coordinates)
                        {
                            if (reproject)
                            {
                                double[] xyarray = { point.X, point.Y };
                                double[] zarray = { point.Z };

                                Reproject.ReprojectPoints(xyarray, zarray, pStart, pESRIEnd, 0, 1);

                                point.X = xyarray[0];
                                point.Y = xyarray[1];
                                point.Z = zarray[0];
                            }

                            sb.Append(point.Y.ToString(CultureInfo.InvariantCulture) + "\t" +
                                      point.X.ToString(CultureInfo.InvariantCulture) + "\r\n");
                        }

                        log.Info("writting poly to " + path + Path.DirectorySeparatorChar + "poly-" + a + ".poly");
                        File.WriteAllText(path + Path.DirectorySeparatorChar + "poly-" + a + ".poly", sb.ToString());

                        a++;
                    }
                }
            }
        }
Exemple #51
0
        // 从文件加载
        private void btnLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            if (!string.IsNullOrEmpty(_defaultPath))
            {
                ofd.InitialDirectory = _defaultPath;
            }
            else
            {
                ofd.InitialDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
            }
            ofd.Filter = "Xml files (*.xml)|*.xml|All files (*.*)|*.*";

            var dialogRet = ofd.ShowDialog(this);

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

            string configPath = ofd.FileName;//Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "sync.xml");

            _defaultPath = Path.GetDirectoryName(configPath);
            if (File.Exists(configPath))
            {
                #region 配置文件存在时,从配置文件加载数据
                lvTables.Items.Clear();

                SyncTask task;
                try
                {
                    string xmlStr;
                    // 兼容旧版本,需要替换旧版本的命名空间后再反序列化
                    using (var memoryStream = new StreamReader(configPath, Encoding.UTF8))
                    {
                        xmlStr = memoryStream.ReadToEnd();
                    }
                    xmlStr = xmlStr.Replace("/Check64dll.", "/Beinet.cn.Tools.");
                    task   = Utility.XmlDeserializeFromStr <SyncTask>(xmlStr);
                    if (task != null && task.Encrypted)
                    {
                        if (!string.IsNullOrEmpty(task.SourceConstr))
                        {
                            task.SourceConstr = Utility.TripleDES_Decrypt(task.SourceConstr, Encoding.UTF8);
                        }
                        if (!string.IsNullOrEmpty(task.TargetConstr))
                        {
                            task.TargetConstr = Utility.TripleDES_Decrypt(task.TargetConstr, Encoding.UTF8);
                        }
                    }
                }
                catch (Exception exp)
                {
                    task = null;
                    MessageBox.Show("打开文件出错:" + exp.Message);
                }
                if (task != null)
                {
                    txtDbSource.Text       = task.SourceConstr;
                    txtDbTarget.Text       = task.TargetConstr;
                    chkErrContinue.Checked = task.ErrContinue;
                    chkWithNolock.Checked  = task.AddNoLock;
                    chkUseTruncate.Checked = task.UseTruncate;
                    if (task.Items != null)
                    {
                        bool haverow = false;
                        foreach (SyncItem item in task.Items)
                        {
                            string[] values = new string[COL_COUNT];
                            values[COL_SOURCE]     = item.Source;
                            values[COL_TARGET]     = item.Target;
                            values[COL_TRUNCATE]   = item.TruncateOld ? "true" : "false";
                            values[COL_IDENTIFIER] = item.UseIdentifier ? "true" : "false";
                            if (item.IsSqlSource)
                            {
                                values[COL_SOURCEBACK] = item.Target;
                            }

                            lvTables.Items.Add(new ListViewItem(values)
                            {
                                Checked = true
                            });
                            haverow = true;
                        }
                        if (haverow)
                        {
                            btnSyncBegin.Enabled  = true;
                            btnAddNewSql.Enabled  = true;
                            btnDelRow.Enabled     = true;
                            btnSaveConfig.Enabled = true;
                            chkAll.Checked        = true;
                        }
                    }
                }
                lstTarget.Items.Add("请点击按钮:获取表结构");

                #endregion
            }
        }
Exemple #52
0
 private void InitializeComponent()
 {
     this.components          = new System.ComponentModel.Container();
     this.titleLabel          = new System.Windows.Forms.Label();
     this.copyrightLabel      = new System.Windows.Forms.Label();
     this.closeButton         = new System.Windows.Forms.Button();
     this.minimizeButton      = new System.Windows.Forms.Button();
     this.helpButton          = new System.Windows.Forms.Button();
     this.mapContextMenu      = new System.Windows.Forms.ContextMenuStrip(this.components);
     this.addDeviceButton     = new System.Windows.Forms.ToolStripMenuItem();
     this.editDeviceButton    = new System.Windows.Forms.ToolStripMenuItem();
     this.deleteDeviceButton  = new System.Windows.Forms.ToolStripMenuItem();
     this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
     this.importButton        = new System.Windows.Forms.ToolStripMenuItem();
     this.exportButton        = new System.Windows.Forms.ToolStripMenuItem();
     this.statusLabel         = new System.Windows.Forms.Label();
     this.exportDialog        = new System.Windows.Forms.SaveFileDialog();
     this.importDialog        = new System.Windows.Forms.OpenFileDialog();
     this.mapContextMenu.SuspendLayout();
     this.SuspendLayout();
     //
     // titleLabel
     //
     this.titleLabel.AutoSize = true;
     this.titleLabel.Font     = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.titleLabel.Location = new System.Drawing.Point(10, 6);
     this.titleLabel.Margin   = new System.Windows.Forms.Padding(2, 0, 2, 0);
     this.titleLabel.Name     = "titleLabel";
     this.titleLabel.Size     = new System.Drawing.Size(151, 20);
     this.titleLabel.TabIndex = 0;
     this.titleLabel.Text     = "Ping Monitor V1.2";
     //
     // copyrightLabel
     //
     this.copyrightLabel.AutoSize = true;
     this.copyrightLabel.Font     = new System.Drawing.Font("Microsoft Sans Serif", 7F);
     this.copyrightLabel.Location = new System.Drawing.Point(165, 13);
     this.copyrightLabel.Margin   = new System.Windows.Forms.Padding(2, 0, 2, 0);
     this.copyrightLabel.Name     = "copyrightLabel";
     this.copyrightLabel.Size     = new System.Drawing.Size(128, 13);
     this.copyrightLabel.TabIndex = 1;
     this.copyrightLabel.Text     = "(© Markus Zechner, 2019)";
     //
     // closeButton
     //
     this.closeButton.Anchor    = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
     this.closeButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.closeButton.Font      = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.closeButton.Location  = new System.Drawing.Point(1883, 12);
     this.closeButton.Name      = "closeButton";
     this.closeButton.Size      = new System.Drawing.Size(25, 25);
     this.closeButton.TabIndex  = 2;
     this.closeButton.Text      = "X";
     this.closeButton.UseVisualStyleBackColor = true;
     this.closeButton.Click += new System.EventHandler(this.onClose);
     //
     // minimizeButton
     //
     this.minimizeButton.Anchor    = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
     this.minimizeButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.minimizeButton.Font      = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.minimizeButton.Location  = new System.Drawing.Point(1852, 12);
     this.minimizeButton.Name      = "minimizeButton";
     this.minimizeButton.Size      = new System.Drawing.Size(25, 25);
     this.minimizeButton.TabIndex  = 3;
     this.minimizeButton.Text      = "_";
     this.minimizeButton.UseVisualStyleBackColor = true;
     this.minimizeButton.Click += new System.EventHandler(this.onMinimize);
     //
     // helpButton
     //
     this.helpButton.Anchor    = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
     this.helpButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.helpButton.Font      = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.helpButton.Location  = new System.Drawing.Point(1821, 12);
     this.helpButton.Name      = "helpButton";
     this.helpButton.Size      = new System.Drawing.Size(25, 25);
     this.helpButton.TabIndex  = 4;
     this.helpButton.Text      = "?";
     this.helpButton.UseVisualStyleBackColor = true;
     this.helpButton.Click += new System.EventHandler(this.onHelp);
     //
     // mapContextMenu
     //
     this.mapContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
         this.addDeviceButton,
         this.editDeviceButton,
         this.deleteDeviceButton,
         this.toolStripSeparator1,
         this.importButton,
         this.exportButton
     });
     this.mapContextMenu.Name = "mapContextMenu";
     this.mapContextMenu.Size = new System.Drawing.Size(170, 120);
     //
     // addDeviceButton
     //
     this.addDeviceButton.Name   = "addDeviceButton";
     this.addDeviceButton.Size   = new System.Drawing.Size(169, 22);
     this.addDeviceButton.Text   = "Add Device...";
     this.addDeviceButton.Click += new System.EventHandler(this.onAddDevice);
     //
     // editDeviceButton
     //
     this.editDeviceButton.Enabled = false;
     this.editDeviceButton.Name    = "editDeviceButton";
     this.editDeviceButton.Size    = new System.Drawing.Size(169, 22);
     this.editDeviceButton.Text    = "Edit...";
     this.editDeviceButton.Click  += new System.EventHandler(this.onEditDevice);
     //
     // deleteDeviceButton
     //
     this.deleteDeviceButton.Enabled = false;
     this.deleteDeviceButton.Name    = "deleteDeviceButton";
     this.deleteDeviceButton.Size    = new System.Drawing.Size(169, 22);
     this.deleteDeviceButton.Text    = "Delete";
     this.deleteDeviceButton.Click  += new System.EventHandler(this.onDeleteDevice);
     //
     // toolStripSeparator1
     //
     this.toolStripSeparator1.Name = "toolStripSeparator1";
     this.toolStripSeparator1.Size = new System.Drawing.Size(166, 6);
     //
     // importButton
     //
     this.importButton.Name   = "importButton";
     this.importButton.Size   = new System.Drawing.Size(169, 22);
     this.importButton.Text   = "Import from File...";
     this.importButton.Click += new System.EventHandler(this.onImport);
     //
     // exportButton
     //
     this.exportButton.Enabled = false;
     this.exportButton.Name    = "exportButton";
     this.exportButton.Size    = new System.Drawing.Size(169, 22);
     this.exportButton.Text    = "Export to File...";
     this.exportButton.Click  += new System.EventHandler(this.onExport);
     //
     // statusLabel
     //
     this.statusLabel.Anchor   = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
     this.statusLabel.AutoSize = true;
     this.statusLabel.Font     = new System.Drawing.Font("Microsoft Sans Serif", 7F);
     this.statusLabel.Location = new System.Drawing.Point(1672, 19);
     this.statusLabel.Margin   = new System.Windows.Forms.Padding(2, 0, 2, 0);
     this.statusLabel.Name     = "statusLabel";
     this.statusLabel.Size     = new System.Drawing.Size(144, 13);
     this.statusLabel.TabIndex = 5;
     this.statusLabel.Text     = "Waiting for Threads to close...";
     this.statusLabel.Visible  = false;
     //
     // exportDialog
     //
     this.exportDialog.DefaultExt = "pmc";
     this.exportDialog.FileName   = "config.pmc";
     this.exportDialog.Filter     = "PingMonitor Configuration Files|*.pmc";
     this.exportDialog.Title      = "Export Configuration";
     //
     // importDialog
     //
     this.importDialog.DefaultExt = "pmc";
     this.importDialog.Filter     = "PingMonitor Configuration Files|*.pmc";
     this.importDialog.Title      = "Import Configuration";
     //
     // MainForm
     //
     this.AutoScaleDimensions = new System.Drawing.SizeF(5F, 9F);
     this.AutoScaleMode       = System.Windows.Forms.AutoScaleMode.Font;
     this.BackColor           = System.Drawing.Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20)))));
     this.ClientSize          = new System.Drawing.Size(1920, 1061);
     this.Controls.Add(this.statusLabel);
     this.Controls.Add(this.helpButton);
     this.Controls.Add(this.minimizeButton);
     this.Controls.Add(this.closeButton);
     this.Controls.Add(this.copyrightLabel);
     this.Controls.Add(this.titleLabel);
     this.Font            = new System.Drawing.Font("Microsoft Sans Serif", 6F);
     this.ForeColor       = System.Drawing.Color.White;
     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
     this.Margin          = new System.Windows.Forms.Padding(2);
     this.Name            = "MainForm";
     this.StartPosition   = System.Windows.Forms.FormStartPosition.CenterScreen;
     this.Text            = "Ping Monitor";
     this.Shown          += new System.EventHandler(this.onShow);
     this.Paint          += new System.Windows.Forms.PaintEventHandler(this.onPaint);
     this.DoubleClick    += new System.EventHandler(this.onDoubleClick);
     this.MouseClick     += new System.Windows.Forms.MouseEventHandler(this.onClick);
     this.MouseDown      += new System.Windows.Forms.MouseEventHandler(this.onMouseDown);
     this.MouseMove      += new System.Windows.Forms.MouseEventHandler(this.onMouseMove);
     this.MouseUp        += new System.Windows.Forms.MouseEventHandler(this.onMouseUp);
     this.mapContextMenu.ResumeLayout(false);
     this.ResumeLayout(false);
     this.PerformLayout();
 }
Exemple #53
0
        public override void Perform(Pixmap pixmap)
        {
            var opd = new OpenFileDialog()
            {
                CheckFileExists = true,
                DefaultExt      = ".xml",
                Title           = "Import XML atlas"
            };

            if (opd.ShowDialog() == DialogResult.OK)
            {
                var doc         = XDocument.Load(opd.FileName);
                var spriteElems = doc.Descendants().Where(e => e.Name.LocalName == "sprite");

                pixmap.Atlas = new List <Duality.Rect>();

                Dictionary <string, Dictionary <int, int> > anims = new Dictionary <string, Dictionary <int, int> >();
                Match match;
                foreach (var elem in spriteElems)
                {
                    string sprName;
                    int    index = pixmap.Atlas.Count;
                    pixmap.Atlas.Add(new Rect(
                                         float.Parse(elem.Attribute("x").Value),
                                         float.Parse(elem.Attribute("y").Value),
                                         float.Parse(elem.Attribute("w").Value),
                                         float.Parse(elem.Attribute("h").Value)
                                         ));

                    var name = elem.Attribute("n").Value;
                    if ((match = AnimRegex.Match(name)).Success)
                    {
                        sprName = match.Groups[1].Value;
                        int animIndex = int.Parse(match.Groups[2].Value);
                        if (!anims.ContainsKey(sprName))
                        {
                            anims[sprName] = new Dictionary <int, int>();
                        }
                        anims[sprName][animIndex] = index;
                    }
                    else
                    {
                        if (!anims.ContainsKey(name))
                        {
                            anims[name] = new Dictionary <int, int>();
                        }
                        anims[name][0] = index;
                    }
                }

                var atlas = new Resources.SpriteAtlas();
                atlas.Pixmap  = pixmap;
                atlas.Sprites = new Dictionary <string, Resources.SpriteAtlas.Item>();
                foreach (var a in anims)
                {
                    atlas.Sprites[a.Key] = new Resources.SpriteAtlas.Item {
                        Indexes = a.Value.OrderBy(v => v.Key).Select(v => v.Value).ToArray()
                    };
                }
                var path = Path.GetDirectoryName(pixmap.Path);
                atlas.Save($"{path}/{Path.GetFileNameWithoutExtension(pixmap.Name)}.SpriteAtlas.res");
                pixmap.Save();
            }
        }
        static void Main(string[] args)
        {
            config = JsonConvert.DeserializeObject <Config>(File.ReadAllText(Application.StartupPath + Path.DirectorySeparatorChar + @"config.json"));
            byte[] il2cppBytes   = null;
            byte[] metadataBytes = null;
            string stringVersion = null;
            int    mode          = 0;

            if (args.Length == 1)
            {
                if (args[0] == "-h" || args[0] == "--help" || args[0] == "/?" || args[0] == "/h")
                {
                    ShowHelp();
                    return;
                }
            }
            if (args.Length > 4)
            {
                ShowHelp();
                return;
            }
            if (args.Length > 3)
            {
                mode = int.Parse(args[3]);
            }
            if (args.Length > 2)
            {
                stringVersion = args[2];
            }
            if (args.Length > 1)
            {
                var file1 = File.ReadAllBytes(args[0]);
                var file2 = File.ReadAllBytes(args[1]);
                if (BitConverter.ToUInt32(file1, 0) == 0xFAB11BAF)
                {
                    il2cppBytes   = file2;
                    metadataBytes = file1;
                }
                else if (BitConverter.ToUInt32(file2, 0) == 0xFAB11BAF)
                {
                    il2cppBytes   = file1;
                    metadataBytes = file2;
                }
            }
            if (il2cppBytes == null)
            {
                var ofd = new OpenFileDialog();
                ofd.Filter = "Il2Cpp binary file|*.*";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    il2cppBytes = File.ReadAllBytes(ofd.FileName);
                    ofd.Filter  = "global-metadata|global-metadata.dat";
                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        metadataBytes = File.ReadAllBytes(ofd.FileName);
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    return;
                }
            }
            //try
            {
                if (Init(il2cppBytes, metadataBytes, stringVersion, mode, out var metadata, out var il2Cpp, args))
                {
                    Dump(metadata, il2Cpp);
                }
            }
            //catch (Exception e)
            //{
            //    Console.WriteLine(e);
            //}
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey(true);
        }
        private void button5_Click(object sender, EventArgs e)
        {
            var filePath1 = string.Empty;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "E:\\Facultate\\CN\\Tema2\\Tema2";
                openFileDialog.Filter           = "txt files (.txt)|.txt|All files (.)|*.*";
                openFileDialog.FilterIndex      = 2;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    filePath1 = openFileDialog.FileName;
                }
            }

            string sA = System.IO.File.ReadAllText(filePath1);

            int n = 0;

            while (sA[n] != '\n')
            {
                n++;
            }
            double[,] A  = new double[n / 2, n / 2];
            double[,] _A = new double[n / 2, n / 2];

            int i = 0, j = 0;
            int max = 0;

            foreach (var row in sA.Split('\n'))
            {
                j = 0;
                int nr = 0;
                foreach (var col in row.Trim().Split(' '))
                {
                    if (col.Trim().Contains('.'))
                    {
                        nr++;
                    }
                    A[i, j]  = double.Parse(col.Trim(), System.Globalization.CultureInfo.InvariantCulture);
                    _A[i, j] = (double)A[i, j];
                    j++;
                }
                if (nr > max)
                {
                    max = nr;
                }
                i++;
            }

            if (max != 0)
            {
                n = n - max;
            }

            n = n / 2;
            Console.WriteLine(n.ToString());



            double[,] L = new double[n, n];
            double[,] U = new double[n, n];

            double[] L_vector = new double[n * (n + 1) / 2];
            double[] U_vector = new double[n * (n + 1) / 2];

            int contor  = 0;
            int contor2 = 0;

            for (i = 0; i < n; i++)
            {
                for (int k = i; k < n; k++)
                {
                    double sum = 0;
                    for (j = 0; j < i; j++)
                    {
                        sum += (L[i, j] * U[j, k]);
                    }
                    U[i, k]          = A[i, k] - sum;
                    U_vector[contor] = A[i, k] - sum;
                    contor++;
                }

                for (int k = i; k < n; k++)
                {
                    if (i == k)
                    {
                        L[i, i] = 1;
                    }
                    else
                    {
                        double sum = 0;
                        for (j = 0; j < i; j++)
                        {
                            sum += (L[k, j] * U[j, i]);
                        }
                        L[k, i]           = (A[k, i] - sum) / U[i, i];
                        L_vector[contor2] = (A[k, i] - sum) / U[i, i];
                        contor2++;
                    }
                }
            }

            /*Console.WriteLine("A:");
             * for (i = 0; i < n; i++)
             * {
             *  for (j = 0; j < n; j++)
             *  {
             *      Console.Write(A[i, j].ToString() + " ");
             *
             *  }
             *  Console.WriteLine();
             * }*/
            label1.Text = "Descompunerea LU";


            label2.Text = "Matricea U\n";
            //Console.WriteLine("U:");

            for (i = 0; i < n * (n + 1) / 2; i++)
            {
                //for (j = 0; j < n; j++)
                // {
                label2.Text += U_vector[i].ToString() + " ";
                // Console.Write(U[i, j].ToString() + " ");
                //}
            }
            label2.Text += '\n';
            Console.WriteLine();

            label3.Text = "Matricea L\n";
            //Console.WriteLine("L:");

            for (i = 0; i < n * (n + 1) / 2; i++)
            {
                // for (j = 0; j < n; j++)
                //{
                label3.Text += L_vector[i].ToString() + " ";
                // Console.Write(L[i, j].ToString() + " ");
                // }
                label3.Text += '\n';
                Console.WriteLine();
            }


            var filePath2 = string.Empty;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "D:\\Facultate Git\\FacultateAn3Sem2\\CN\\Tema2";
                openFileDialog.Filter           = "txt files (.txt)|.txt|All files (.)|*.*";
                openFileDialog.FilterIndex      = 2;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    filePath1 = openFileDialog.FileName;
                }
            }

            string sb = System.IO.File.ReadAllText(filePath1);
            int    m;

            m = n;


            double[,] b      = new double[m, 1];
            double[,] b_init = new double[m, 1];
            int l = 0;

            foreach (var element in sb.Split('\n'))
            {
                b[l, 0] = (double)int.Parse(element);
                l++;
            }
            for (i = 0; i < m; i++)
            {
                Console.WriteLine(b[i, 0]);
            }

            for (i = 0; i < m; i++)
            {
                b_init[i, 0] = b[i, 0];
            }



            for (i = 1; i < n; i++)
            {
                double sum = 0;
                for (j = 0; j < n; j++)
                {
                    if (i > j)
                    {
                        sum += L_vector[i - 1 + j] * b[j, 0];
                    }
                    if (i == j)
                    {
                        //y[j, 0] = (b[j, 0] - sum);
                        b[j, 0] = (b[j, 0] - sum);
                    }
                }
            }
            label2.Text = "Matricea Y\n";
            Console.WriteLine("Y:");
            for (i = 0; i < m; i++)
            {
                label2.Text += b[i, 0].ToString() + '\n';
            }
            //Console.WriteLine(b[i, 0]);

            double[,] x = new double[m, 1];

            x[m - 1, 0] = b[m - 1, 0] / A[n - 1, n - 1];


            for (i = n - 2; i >= 0; i--)
            {
                double sum = 0;
                for (j = n - 1; j >= 0; j--)
                {
                    if (i < j)
                    {
                        sum += U_vector[(i + j) % 3] * x[j, 0];
                    }
                    else
                    {
                        x[j, 0] = (b[j, 0] - sum) / A[i, j];
                    }
                }
            }

            for (i = 0; i < n; i++)
            {
                Console.WriteLine(x[i, 0]);
            }

            //Matrix<double> L_check = DenseMatrix.OfArray(L);
            //Matrix<double> U_check = DenseMatrix.OfArray(L);

            //var C_check = L_check.Multiply(U_check);
            //Console.WriteLine("C:");
            //for (i = 0; i < n; i++)
            //{
            //    for (j = 0; j < n; j++)
            //    {
            //        Console.Write(C_check[i, j].ToString() + " ");
            //    }
            //    Console.WriteLine();
            //}
        }
 /// <summary>
 /// Required method for Designer support - do not modify
 /// the contents of this method with the code editor.
 /// </summary>
 private void InitializeComponent()
 {
     System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(FrmPreferences));
     this.fontDialog1     = new System.Windows.Forms.FontDialog();
     this.label1          = new System.Windows.Forms.Label();
     this.txtFontDisplay  = new System.Windows.Forms.TextBox();
     this.btnFontPick     = new System.Windows.Forms.Button();
     this.btnCancel       = new System.Windows.Forms.Button();
     this.btnOK           = new System.Windows.Forms.Button();
     this.tabControl1     = new System.Windows.Forms.TabControl();
     this.tpGeneral       = new System.Windows.Forms.TabPage();
     this.label5          = new System.Windows.Forms.Label();
     this.btnInputFont    = new System.Windows.Forms.Button();
     this.txtInputFont    = new System.Windows.Forms.TextBox();
     this.btnPlay         = new System.Windows.Forms.Button();
     this.btnBellSound    = new System.Windows.Forms.Button();
     this.label4          = new System.Windows.Forms.Label();
     this.txtBellSound    = new System.Windows.Forms.TextBox();
     this.label3          = new System.Windows.Forms.Label();
     this.txtHistSize     = new System.Windows.Forms.TextBox();
     this.txtCommandSep   = new System.Windows.Forms.TextBox();
     this.label2          = new System.Windows.Forms.Label();
     this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
     this.errorProvider1  = new System.Windows.Forms.ErrorProvider();
     this.tabControl1.SuspendLayout();
     this.tpGeneral.SuspendLayout();
     this.SuspendLayout();
     //
     // label1
     //
     this.label1.Location  = new System.Drawing.Point(8, 16);
     this.label1.Name      = "label1";
     this.label1.Size      = new System.Drawing.Size(384, 23);
     this.label1.TabIndex  = 0;
     this.label1.Text      = "Window Font: (Make sure it\'s a monospaced font like Courier New)";
     this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
     //
     // txtFontDisplay
     //
     this.txtFontDisplay.Location = new System.Drawing.Point(48, 40);
     this.txtFontDisplay.Name     = "txtFontDisplay";
     this.txtFontDisplay.ReadOnly = true;
     this.txtFontDisplay.Size     = new System.Drawing.Size(440, 20);
     this.txtFontDisplay.TabIndex = 0;
     this.txtFontDisplay.TabStop  = false;
     this.txtFontDisplay.Text     = "";
     //
     // btnFontPick
     //
     this.btnFontPick.Location = new System.Drawing.Point(496, 40);
     this.btnFontPick.Name     = "btnFontPick";
     this.btnFontPick.Size     = new System.Drawing.Size(32, 23);
     this.btnFontPick.TabIndex = 0;
     this.btnFontPick.Text     = "...";
     this.btnFontPick.Click   += new System.EventHandler(this.btnFontPick_Click);
     //
     // btnCancel
     //
     this.btnCancel.Location = new System.Drawing.Point(416, 288);
     this.btnCancel.Name     = "btnCancel";
     this.btnCancel.TabIndex = 8;
     this.btnCancel.Text     = "&Cancel";
     this.btnCancel.Click   += new System.EventHandler(this.btnCancel_Click);
     //
     // btnOK
     //
     this.btnOK.Location = new System.Drawing.Point(88, 288);
     this.btnOK.Name     = "btnOK";
     this.btnOK.TabIndex = 7;
     this.btnOK.Text     = "&OK";
     this.btnOK.Click   += new System.EventHandler(this.btnOK_Click);
     //
     // tabControl1
     //
     this.tabControl1.Controls.Add(this.tpGeneral);
     this.tabControl1.Location      = new System.Drawing.Point(8, 8);
     this.tabControl1.Name          = "tabControl1";
     this.tabControl1.SelectedIndex = 0;
     this.tabControl1.Size          = new System.Drawing.Size(544, 272);
     this.tabControl1.TabIndex      = 5;
     //
     // tpGeneral
     //
     this.tpGeneral.Controls.Add(this.label5);
     this.tpGeneral.Controls.Add(this.btnInputFont);
     this.tpGeneral.Controls.Add(this.txtInputFont);
     this.tpGeneral.Controls.Add(this.btnPlay);
     this.tpGeneral.Controls.Add(this.btnBellSound);
     this.tpGeneral.Controls.Add(this.label4);
     this.tpGeneral.Controls.Add(this.txtBellSound);
     this.tpGeneral.Controls.Add(this.label3);
     this.tpGeneral.Controls.Add(this.txtHistSize);
     this.tpGeneral.Controls.Add(this.txtCommandSep);
     this.tpGeneral.Controls.Add(this.label2);
     this.tpGeneral.Controls.Add(this.label1);
     this.tpGeneral.Controls.Add(this.txtFontDisplay);
     this.tpGeneral.Controls.Add(this.btnFontPick);
     this.tpGeneral.Location = new System.Drawing.Point(4, 22);
     this.tpGeneral.Name     = "tpGeneral";
     this.tpGeneral.Size     = new System.Drawing.Size(536, 246);
     this.tpGeneral.TabIndex = 0;
     this.tpGeneral.Text     = "General";
     //
     // label5
     //
     this.label5.Location = new System.Drawing.Point(8, 72);
     this.label5.Name     = "label5";
     this.label5.TabIndex = 12;
     this.label5.Text     = "Input Area Font:";
     //
     // btnInputFont
     //
     this.btnInputFont.Location = new System.Drawing.Point(496, 96);
     this.btnInputFont.Name     = "btnInputFont";
     this.btnInputFont.Size     = new System.Drawing.Size(32, 23);
     this.btnInputFont.TabIndex = 1;
     this.btnInputFont.Text     = "...";
     this.btnInputFont.Click   += new System.EventHandler(this.btnInputFont_Click);
     //
     // txtInputFont
     //
     this.txtInputFont.Location = new System.Drawing.Point(48, 96);
     this.txtInputFont.Name     = "txtInputFont";
     this.txtInputFont.ReadOnly = true;
     this.txtInputFont.Size     = new System.Drawing.Size(440, 20);
     this.txtInputFont.TabIndex = 0;
     this.txtInputFont.TabStop  = false;
     this.txtInputFont.Text     = "";
     //
     // btnPlay
     //
     this.btnPlay.Image    = ((System.Drawing.Image)(resources.GetObject("btnPlay.Image")));
     this.btnPlay.Location = new System.Drawing.Point(496, 208);
     this.btnPlay.Name     = "btnPlay";
     this.btnPlay.Size     = new System.Drawing.Size(32, 23);
     this.btnPlay.TabIndex = 6;
     this.btnPlay.Click   += new System.EventHandler(this.btnPlay_Click);
     //
     // btnBellSound
     //
     this.btnBellSound.Location = new System.Drawing.Point(464, 208);
     this.btnBellSound.Name     = "btnBellSound";
     this.btnBellSound.Size     = new System.Drawing.Size(32, 23);
     this.btnBellSound.TabIndex = 5;
     this.btnBellSound.Text     = "...";
     this.btnBellSound.Click   += new System.EventHandler(this.btnBellSound_Click);
     //
     // label4
     //
     this.label4.Location = new System.Drawing.Point(72, 208);
     this.label4.Name     = "label4";
     this.label4.TabIndex = 8;
     this.label4.Text     = "Bell Sound:";
     //
     // txtBellSound
     //
     this.txtBellSound.Location = new System.Drawing.Point(184, 208);
     this.txtBellSound.Name     = "txtBellSound";
     this.txtBellSound.Size     = new System.Drawing.Size(272, 20);
     this.txtBellSound.TabIndex = 4;
     this.txtBellSound.Text     = "";
     //
     // label3
     //
     this.label3.Location = new System.Drawing.Point(16, 176);
     this.label3.Name     = "label3";
     this.label3.Size     = new System.Drawing.Size(152, 23);
     this.label3.TabIndex = 6;
     this.label3.Text     = "Command History Size:";
     //
     // txtHistSize
     //
     this.txtHistSize.Location    = new System.Drawing.Point(184, 176);
     this.txtHistSize.Name        = "txtHistSize";
     this.txtHistSize.Size        = new System.Drawing.Size(48, 20);
     this.txtHistSize.TabIndex    = 3;
     this.txtHistSize.Text        = "";
     this.txtHistSize.Validating += new System.ComponentModel.CancelEventHandler(this.txtHistSize_Validating);
     //
     // txtCommandSep
     //
     this.txtCommandSep.Location  = new System.Drawing.Point(184, 128);
     this.txtCommandSep.MaxLength = 1;
     this.txtCommandSep.Name      = "txtCommandSep";
     this.txtCommandSep.Size      = new System.Drawing.Size(24, 20);
     this.txtCommandSep.TabIndex  = 2;
     this.txtCommandSep.Text      = "";
     //
     // label2
     //
     this.label2.Location = new System.Drawing.Point(8, 128);
     this.label2.Name     = "label2";
     this.label2.Size     = new System.Drawing.Size(168, 23);
     this.label2.TabIndex = 3;
     this.label2.Text     = "Command Seperator Character:";
     //
     // openFileDialog1
     //
     this.openFileDialog1.Filter = "Wav files (*.wav)|*.wav|All files (*.*) | *.*";
     //
     // errorProvider1
     //
     this.errorProvider1.ContainerControl = this;
     //
     // FrmPreferences
     //
     this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
     this.ClientSize        = new System.Drawing.Size(560, 317);
     this.Controls.Add(this.tabControl1);
     this.Controls.Add(this.btnOK);
     this.Controls.Add(this.btnCancel);
     this.Name  = "FrmPreferences";
     this.Text  = "Preferences";
     this.Load += new System.EventHandler(this.FrmPreferences_Load);
     this.tabControl1.ResumeLayout(false);
     this.tpGeneral.ResumeLayout(false);
     this.ResumeLayout(false);
 }
        private void button2_Click_1(object sender, EventArgs e)
        {
            var filePath1 = string.Empty;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "E:\\Facultate\\CN\\Tema2\\Tema2";
                openFileDialog.Filter           = "txt files (.txt)|.txt|All files (.)|*.*";
                openFileDialog.FilterIndex      = 2;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    filePath1 = openFileDialog.FileName;
                }
            }

            string sA = System.IO.File.ReadAllText(filePath1);

            int n = 0;

            while (sA[n] != '\n')
            {
                n++;
            }
            double[,] A  = new double[n / 2, n / 2];
            double[,] _A = new double[n / 2, n / 2];

            int i = 0, j = 0;
            int max = 0;

            foreach (var row in sA.Split('\n'))
            {
                j = 0;
                int nr = 0;
                foreach (var col in row.Trim().Split(' '))
                {
                    if (col.Trim().Contains('.'))
                    {
                        nr++;
                    }
                    A[i, j]  = double.Parse(col.Trim(), System.Globalization.CultureInfo.InvariantCulture);
                    _A[i, j] = (double)A[i, j];
                    j++;
                }
                if (nr > max)
                {
                    max = nr;
                }
                i++;
            }
            if (max != 0)
            {
                n = n - max;
            }
            n = n / 2;


            double[,] L = new double[n, n];
            double[,] U = new double[n, n];

            for (i = 0; i < n; i++)
            {
                for (int k = i; k < n; k++)
                {
                    double sum = 0;
                    for (j = 0; j < i; j++)
                    {
                        sum += (L[i, j] * U[j, k]);
                    }
                    U[i, k] = (double)A[i, k] - sum;
                }

                for (int k = i; k < n; k++)
                {
                    if (i == k)
                    {
                        L[i, i] = 1;
                    }
                    else
                    {
                        double sum = 0;
                        for (j = 0; j < i; j++)
                        {
                            sum += (L[k, j] * U[j, i]);
                        }
                        L[k, i] = ((double)A[k, i] - sum) / U[i, i];
                    }
                }
            }

            double determinantU = 1;

            for (i = 0; i < n; i++)
            {
                determinantU *= U[i, i];
            }
            label1.Text = "";
            label2.Text = "";
            label3.Text = "";


            label1.Text = "Determinanatul matricei cu ajutorul descompunerii Lu";
            label2.Text = determinantU.ToString();
            Console.WriteLine(determinantU.ToString());
        }
Exemple #58
0
        public Windows()
        {
            Button bp = new Button("Show borderless window");

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

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

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

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

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

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

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

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

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

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

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

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

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

                w.Show();
            };

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

            b = new Button("Show dialog and make this window not sensitive");
            PackStart(b);
            b.Clicked += delegate
            {
                var dialog = new Dialog();
                dialog.Content = new Label("Hello World");
                dialog.Run();
                dialog.Shown  += (sender, args) => this.ParentWindow.Sensitive = false;
                dialog.Closed += (sender, args) => this.ParentWindow.Sensitive = true;
            };
        }
Exemple #59
0
        private void loadPSX_Click_1(object sender, EventArgs e)
        {
            //Filters file to look for a FF7 ISO, however there can be great variety
            //in the actual name of the disc itself or the extension. So for validation,
            //the tool checks
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            //openFileDialog1.Filter = "ff7 iso (.bin)|*.bin|All Files (*.*)|*.*";

            //openFileDialog1.Filter = "ISO|*.iso|BIN|*.bin|IMG|*.img";

            openFileDialog1.FilterIndex = 1;
            openFileDialog1.Title       = "Open an FF7 ISO/.BIN";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string fileCheck = openFileDialog1.FileName;

                //Enforces that opened file is ff7.exe or ff_en.exe
                if (fileCheck.Contains(".bin") || fileCheck.Contains(".iso") || fileCheck.Contains(".img"))
                {
                    try
                    {
                        //Sets the columns, only the actual values are made visible
                        //for modification as the 2nd 'modifier' byte will be adjusted
                        //automatically by the tool based on the 1st byte defined by
                        //the user.
                        BinaryReader br = new BinaryReader(new MemoryStream(File.ReadAllBytes(openFileDialog1.FileName)));

                        DataTable dataTable = new DataTable();
                        dataTable.Columns.Add("STR", typeof(sbyte));
                        dataTable.Columns.Add("STR2", typeof(sbyte));
                        dataTable.Columns.Add("VIT", typeof(sbyte));
                        dataTable.Columns.Add("VIT2", typeof(sbyte));
                        dataTable.Columns.Add("MAG", typeof(sbyte));
                        dataTable.Columns.Add("MAG2", typeof(sbyte));
                        dataTable.Columns.Add("SPR", typeof(sbyte));
                        dataTable.Columns.Add("SPR2", typeof(sbyte));
                        dataTable.Columns.Add("DEX", typeof(sbyte));
                        dataTable.Columns.Add("DEX2", typeof(sbyte));
                        dataTable.Columns.Add("LCK", typeof(sbyte));
                        dataTable.Columns.Add("LCK2", typeof(sbyte));
                        dataTable.Columns.Add("HP%", typeof(sbyte));
                        dataTable.Columns.Add("HP%2", typeof(sbyte));
                        dataTable.Columns.Add("MP%", typeof(sbyte));
                        dataTable.Columns.Add("MP%2", typeof(sbyte));

                        //Reads file from this offset then casts it to a signedbyte array
                        br.BaseStream.Position = 0x4FD88;
                        byte[]  byteArray = br.ReadBytes(0x140);
                        sbyte[] array     = Array.ConvertAll(byteArray, b => (sbyte)b);

                        //Adds the rows/cell values from the byte array
                        int i = 20;
                        int j = 0;
                        while (i != 0)
                        {
                            dataTable.Rows.Add(
                                array[j], array[j + 1], array[j + 2], array[j + 3],
                                array[j + 4], array[j + 5], array[j + 6], array[j + 7],
                                array[j + 8], array[j + 9], array[j + 10], array[j + 11],
                                array[j + 12], array[j + 13], array[j + 14], array[j + 15]);
                            i = i - 1;
                            j = j + 16;
                        }
                        dataGridView1.DataSource = dataTable;

                        //Hides the extra byte modifier used for +/- values
                        //These are adjusted by tool automatically when patching.
                        dataGridView1.Columns[1].Visible  = false;
                        dataGridView1.Columns[3].Visible  = false;
                        dataGridView1.Columns[5].Visible  = false;
                        dataGridView1.Columns[7].Visible  = false;
                        dataGridView1.Columns[9].Visible  = false;
                        dataGridView1.Columns[11].Visible = false;
                        dataGridView1.Columns[13].Visible = false;
                        dataGridView1.Columns[15].Visible = false;

                        foreach (DataGridViewColumn column in dataGridView1.Columns)
                        {
                            column.SortMode = DataGridViewColumnSortMode.NotSortable;
                        }

                        //Sets column width for better visibility
                        int r = 0;
                        while (r < 16)
                        {
                            DataGridViewColumn column = dataGridView1.Columns[r];
                            column.Width = 60;
                            r++;
                            r++;
                        }

                        //Sets the row value identifier
                        foreach (DataGridViewRow s in dataGridView1.Rows)
                        {
                            dataGridView1.Rows[s.Index].HeaderCell.Value =
                                ("0" + s.Index).ToString();
                        }
                        //Tiers are shown in hexadecimal within the WallMarket tool so row-names
                        //are converted to 'hex' (cosmetically) here for ease of reference between tools.
                        dataGridView1.Rows[10].HeaderCell.Value = ("0A").ToString();
                        dataGridView1.Rows[11].HeaderCell.Value = ("0B").ToString();
                        dataGridView1.Rows[12].HeaderCell.Value = ("0C").ToString();
                        dataGridView1.Rows[13].HeaderCell.Value = ("0D").ToString();
                        dataGridView1.Rows[14].HeaderCell.Value = ("0E").ToString();
                        dataGridView1.Rows[15].HeaderCell.Value = ("0F").ToString();
                        dataGridView1.Rows[16].HeaderCell.Value = ("10").ToString();
                        dataGridView1.Rows[17].HeaderCell.Value = ("11").ToString();
                        dataGridView1.Rows[18].HeaderCell.Value = ("12").ToString();
                        dataGridView1.Rows[19].HeaderCell.Value = ("13").ToString();
                        dataGridView1.RowHeadersWidth           = 60;

                        //Target File Path
                        lblFileName.Text = openFileDialog1.FileName;
                    }
                    catch
                    {
                        MessageBox.Show("An error has occurred; please check that a valid ff7.exe was loaded", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("Invalid File; please select a FF7 IMG, BIN, or ISO", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            var filePath1 = string.Empty;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "D:\\Facultate Git\\FacultateAn3Sem2\\CN\\Tema2";
                openFileDialog.Filter           = "txt files (.txt)|.txt|All files (.)|*.*";
                openFileDialog.FilterIndex      = 2;
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    filePath1 = openFileDialog.FileName;
                }
            }

            string sA = System.IO.File.ReadAllText(filePath1);

            int n = 0;

            while (sA[n] != '\n')
            {
                n++;
            }

            double[,] A  = new double[n / 2, n / 2];
            double[,] _A = new double[n / 2, n / 2];

            int i = 0, j = 0;
            int max = 0;

            foreach (var row in sA.Split('\n'))
            {
                j = 0;
                int nr = 0;
                foreach (var col in row.Trim().Split(' '))
                {
                    if (col.Trim().Contains('.'))
                    {
                        nr++;
                    }
                    A[i, j]  = double.Parse(col.Trim(), System.Globalization.CultureInfo.InvariantCulture);
                    _A[i, j] = A[i, j];
                    j++;
                }
                if (nr > max)
                {
                    max = nr;
                }
                i++;
            }
            if (max != 0)
            {
                n = n - max;
            }
            n = n / 2;


            double[,] A_init = new double[n, n];

            for (i = 0; i < n; i++)
            {
                for (j = 0; j < n; j++)
                {
                    A_init[i, j] = A[i, j];
                }
            }



            double[,] L = new double[n, n];
            double[,] U = new double[n, n];



            for (i = 0; i < n; i++)
            {
                for (int k = i; k < n; k++)
                {
                    double sum = 0;
                    for (j = 0; j < i; j++)
                    {
                        sum += (L[i, j] * U[j, k]);
                    }
                    U[i, k] = A[i, k] - sum;
                    A[i, k] = A_init[i, k] - sum;
                }

                for (int k = i; k < n; k++)
                {
                    if (i == k)
                    {
                        L[i, i] = 1;
                    }
                    if (i != k)
                    {
                        double sum = 0;
                        for (j = 0; j < i; j++)
                        {
                            sum += (L[k, j] * U[j, i]);
                        }
                        L[k, i] = (A[k, i] - sum) / U[i, i];
                        A[k, i] = (A_init[k, i] - sum) / U[i, i];
                    }
                }
            }


            /*for (i = 0; i < n; i++)
             * {
             *  for (j = 0; j < n; j++)
             *      Console.Write(A[i, j].ToString() + " ");
             *  Console.WriteLine();
             * }*/

            double[,] matriceRezultat = new double[n, n];
            double[] e_j = new double[n];

            label1.Text = "";
            label2.Text = "";
            label3.Text = "";
            label4.Text = "";
            label5.Text = "";
            label6.Text = "";

            double[,] matrice_finala_inversa = new double[n, n];

            for (j = 0; j < n; j++)
            {
                //intializare vector e_j
                for (i = 0; i < e_j.Length; i++)
                {
                    if (i == j)
                    {
                        e_j[i] = 1;
                    }
                    else
                    {
                        e_j[i] = 0;
                    }
                }
                //calcul coloana invers

                for (int k = 1; k < n; k++)
                {
                    double sum = 0;
                    for (int o = 0; o < n; o++)
                    {
                        if (k > o)
                        {
                            sum += A[k, o] * e_j[o];
                        }
                        if (k == o)
                        {
                            e_j[o] = (e_j[o] - sum);
                        }
                    }
                }
                //Console.WriteLine("ceva" + e_j.Length.ToString());

                //for (int f = 0; f < e_j.Length; f++)
                //Console.WriteLine(e_j[f].ToString() + " ");

                double[,] x = new double[n, 1];
                x[n - 1, 0] = e_j[n - 1] / A[n - 1, n - 1];

                for (int k = n - 2; k >= 0; k--)
                {
                    double sum = 0;
                    for (int o = n - 1; o >= 0; o--)
                    {
                        if (k < o)
                        {
                            sum += A[k, o] * x[o, 0];
                        }
                        if (k == o)
                        {
                            x[o, 0] = (e_j[o] - sum) / A[k, o];
                        }
                    }
                }



                label1.Text = "inversul calculat al matricei cu aujtorul descompunerii LU\n";
                for (int f = 0; f < e_j.Length; f++)
                {
                    matrice_finala_inversa[f, j] = x[f, 0];
                    label2.Text += x[f, 0].ToString() + " ";
                }
                //Console.Write(x[f,0] + " ");
                label2.Text += '\n';
                Console.WriteLine();
            }

            //==================================
            Matrix <double> A_check = DenseMatrix.OfArray(A_init);

            A_check           = A_check.Inverse();
            double[,] A_final = new double[n, n];
            for (i = 0; i < n; i++)
            {
                for (j = 0; j < n; j++)
                {
                    A_final[i, j] = matrice_finala_inversa[i, j] - A_check[i, j];
                }
            }


            var rezultat = Norma_1(A_final, n);

            label5.Text = rezultat.ToString();
        }