private void OnClickFindBtn2(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog(); ofd.Filter = "Text Files(*.txt)|*.txt|All Files(*.*)|*.*"; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { textBox2.Text = ofd.SafeFileName; try { System.IO.StreamReader sr = new System.IO.StreamReader(ofd.OpenFile()); string content = sr.ReadToEnd(); sr.Close(); selectTextBeforeValue.Text = content; content = System.Text.RegularExpressions.Regex.Replace(content, "a", "QQQ"); System.IO.StreamWriter writer = new System.IO.StreamWriter(ofd.FileName); writer.Write(content); writer.Close(); sr = new System.IO.StreamReader(ofd.OpenFile()); content = sr.ReadToEnd(); sr.Close(); selectTextAfterValue.Text = content; } catch (Exception ex) { Console.WriteLine("=-=-=-=Exception : " + ex); } } }
private void OnClickFindBtn2(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog(); ofd.Filter = "Text Files(*.txt)|*.txt|All Files(*.*)|*.*"; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { textBox2.Text = ofd.SafeFileName; try { System.IO.StreamReader sr = new System.IO.StreamReader(ofd.OpenFile()); string content = sr.ReadToEnd(); sr.Close(); selectTextBeforeValue.Text = content; content = System.Text.RegularExpressions.Regex.Replace(content, "a", "QQQ"); System.IO.StreamWriter writer = new System.IO.StreamWriter(ofd.FileName); writer.Write(content); writer.Close(); sr = new System.IO.StreamReader(ofd.OpenFile()); content = sr.ReadToEnd(); sr.Close(); selectTextAfterValue.Text = content; } catch(Exception ex) { Console.WriteLine("=-=-=-=Exception : " + ex); } } }
static void Main(string[] args) { var x = new System.Windows.Forms.OpenFileDialog(); x.ShowDialog(); while (x.FileNames.Length == 0) { } bin = x.OpenFile(); byte[] buf = new byte[1024 * 25]; bin.Read(buf, 0, buf.Length); File.WriteAllBytes(@"c:\ArduinoBin\bin1.bin", buf); bin.Read(buf, 0, buf.Length); File.WriteAllBytes(@"c:\ArduinoBin\bin2.bin", buf); bin.Read(buf, 0, buf.Length); File.WriteAllBytes(@"c:\ArduinoBin\bin3.bin", buf); bin.Read(buf, 0, buf.Length); File.WriteAllBytes(@"c:\ArduinoBin\bin4.bin", buf); bin.Read(buf, 0, buf.Length); File.WriteAllBytes(@"c:\ArduinoBin\bin5.bin", buf); bin.Read(buf, 0, buf.Length); File.WriteAllBytes(@"c:\ArduinoBin\bin6.bin", buf); bin.Read(buf, 0, buf.Length); File.WriteAllBytes(@"c:\ArduinoBin\bin7.bin", buf); bin.Read(buf, 0, buf.Length); File.WriteAllBytes(@"c:\ArduinoBin\bin8.bin", buf); bin.Read(buf, 0, buf.Length); File.WriteAllBytes(@"c:\ArduinoBin\bin9.bin", buf); bin.Read(buf, 0, buf.Length); File.WriteAllBytes(@"c:\ArduinoBin\bin10.bin", buf); bin.Read(buf, 0, buf.Length); File.WriteAllBytes(@"c:\ArduinoBin\bin11.bin", buf); }
private void LoadScript_Click(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); dlg.AddExtension = true; dlg.DefaultExt = ".bql"; dlg.Title = "Specify the script file..."; dlg.ValidateNames = true; dlg.FileOk += delegate { Stream file = null; try { file = dlg.OpenFile(); var reader = new StreamReader(file); var script = reader.ReadToEnd(); ScriptInput.Text = script; } catch (Exception) { MessageBox.Show("Loading script from file failed. Check if the file exist and is readable.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } finally { if (file != null) { file.Close(); } } }; dlg.ShowDialog(); }
private void LoadBtn_Click(object sender, RoutedEventArgs e) { Stream fileStream; StreamReader fileReader; string shapeText = string.Empty; System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog(); dialog.Filter = "Paint files(*.paint)|*.paint"; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { fileStream = dialog.OpenFile(); fileReader = new StreamReader(fileStream); shapeText = fileReader.ReadToEnd(); if (shapeText != "") { string[] shapesText = shapeText.Split('\n'); shapes.Clear(); shapes = TextToShape(shapesText); newShape = false; } else { shapes.Clear(); newShape = true; } vertices.Clear(); buffer.Clear(); Redraw(); } }
private void btnUpload_Click(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog open = new System.Windows.Forms.OpenFileDialog(); open.Multiselect = false; open.Filter = "Image files (*.bmp, *.jpg, *png, *.gif, *.tiff)|*.bmp;*.jpg*;*.png;*.gif; *.tiff"; open.AddExtension = true; if (open.ShowDialog() == System.Windows.Forms.DialogResult.OK) { UploadImage(open.FileName, open.OpenFile()); } }
private void MenuItem_Click(object sender, RoutedEventArgs e) { var item = sender as MenuItem; if (item.Name.Equals("menu_load")) { System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog(); openFileDialog.Title = "选择图片"; openFileDialog.Filter = "JPEG FIles(*.jpg)|*.jpg|PNG files(*.png)|*.png|BMP Files(*.bmp)|*.bmp"; openFileDialog.CheckFileExists = true; openFileDialog.CheckPathExists = true; Stream stream = null; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { if ((stream = openFileDialog.OpenFile()) != null) { using (stream) { string file = openFileDialog.FileName; imageName = file; brush = new ImageBrush(); image = new Bitmap(file); brush.ImageSource = new BitmapImage(new Uri(file, UriKind.Relative)); canvas_ink.Height = image.Height; canvas_ink.Width = image.Width; canvas_ink.Background = brush; canvas_ink.Children.Clear(); markedPoints.Clear(); markedRegions.Clear(); startPoint.X = -1; startPoint.Y = -1; } } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } } else if (item.Name.Equals("menu_exit")) { this.Close(); } //e.Handled = true; }
/// <summary> /// Método del boton subir imagen del producto que abre el explorador de archivos para obtener una imagen jpg o png. /// Si la imagen ocupa menos de 1 MB transforma la imagen del tipo System.Drawing a byte[] (soportado en WPF) y asigna la imagen /// al producto mostrando la ruta en la interfaz; si la imagen es mayor de 1MB muestra un mensaje indicandolo. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SubirImagen(object sender, RoutedEventArgs e) { System.Drawing.Image image = null; // Abrir explorador de archivos System.Windows.Forms.OpenFileDialog dialogoBuscarArchivo = new System.Windows.Forms.OpenFileDialog(); BitmapDecoder bitdecoder; // Filtar imagen por jpg o png dialogoBuscarArchivo.Filter = "Image files (*.jpg, *.png) | *.jpg; *.png"; dialogoBuscarArchivo.FilterIndex = 1; dialogoBuscarArchivo.Title = (string)Application.Current.FindResource("SubirImagen"); dialogoBuscarArchivo.Multiselect = false; if (dialogoBuscarArchivo.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //Tamaño de la imagen no puede ser mayor de 1MB var size = new FileInfo(dialogoBuscarArchivo.FileName).Length; if (size < 1023000) { // Transformar la imagen a System.Drawing using (Stream stream = dialogoBuscarArchivo.OpenFile()) { string ruta = dialogoBuscarArchivo.FileName; imagen.Text = ruta; //nombre ruta en el textbox image = System.Drawing.Image.FromFile(ruta); bitdecoder = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad); } } else // imagen mayor a 1MB { string mensaje = (string)Application.Current.FindResource("imagenMax"); string cabecera = (string)Application.Current.FindResource("informacion"); MessageBox.Show(mensaje, cabecera, MessageBoxButton.OK, MessageBoxImage.Information); } // Si se elige una imagen if (image != null) { // Transformar la imagen a byte[] y asignarla al producto using (var ms = new MemoryStream()) { image.Save(ms, image.RawFormat); producto.Imagen = ms.ToArray(); } } } }
// ****************************** #region Open File image private void Open_Image() { System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog() { Title = "Select Photos", Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif", CheckFileExists = true, CheckPathExists = true }; Stream myStream = null; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { if ((myStream = openFileDialog1.OpenFile()) != null) { using (myStream) { Imgeloc = openFileDialog1.FileName.ToString(); string file = openFileDialog1.FileName; ib = new ImageBrush() { ImageSource = new BitmapImage(new Uri(file, UriKind.Relative)) }; piCanv.Background = ib; piCanv.Children.Clear(); FileStream fs = new FileStream(Imgeloc, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); //check wher is the picture location string CanvasName = piCanv.Name; int num = Convert.ToInt32(CanvasName.Remove(0, 1)); Product pid = products.Where <Product>(X => X.ID == num).Single <Product>(); int index = products.IndexOf(pid); /////////////////////////////// products[index].Img = br.ReadBytes((int)fs.Length); Saveimg(products, index); } } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } }
private void OpenMenuItem_Click(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog(); dialog.DefaultExt = ".bvh"; dialog.Filter = "BVHファイル(*.bvh)|*.bvh"; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { BVH bvh = new BVH(); bvh.Load(dialog.OpenFile()); bvhFrom.BVH = bvh; bvhTo.BVH = bvh.Convert(); menuItemUseAll.IsChecked = false; } }
private void ShowFileDialog(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog() { CheckFileExists = true, CheckPathExists = true, Multiselect = false, Title = "Select SMS ROM", }; ofd.InitialDirectory = Environment.CurrentDirectory + "\\Test ROMs"; ofd.ShowDialog(); if (ofd.FileName.Length > 0) { System.IO.BinaryReader br = new System.IO.BinaryReader(ofd.OpenFile()); byte[] data = br.ReadBytes((int)ofd.OpenFile().Length); StopCPU(); Memory.Load(data); } }
//***************************************************************************** private void simpleButton1_Click(object sender, EventArgs e) { OrderOperations isl; Stream myStream; System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); openFileDialog1.Filter = "csv files (*.csv)|*.csv|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 1; openFileDialog1.RestoreDirectory = true; try { isl = new OrderOperations(this); isl.Grid_Initialize_Basket(ref gridControl1, ref gridView1); (gridControl1.DataSource as DataTable).Clear(); //* tabloyu temizler. if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if ((myStream = openFileDialog1.OpenFile()) != null) { StreamReader sr = new StreamReader(myStream); string line = sr.ReadLine(); while (line != null) { int pos = line.IndexOf(";", 0); string menkul = line.Substring(0, pos).Trim(); line = line.Substring(pos + 1, line.Length - (pos + 1)); pos = line.IndexOf(";", 0); string lot = line.Substring(0, pos).Trim(); string buysell = line.Substring(pos + 1, line.Length - (pos + 1)).Trim(); Gride_Yaz(menkul, buysell, lot); line = sr.ReadLine(); } myStream.Close(); } } isl = null; } catch (Exception ex) { } }
/// <summary> /// 单个上传(对话框) /// </summary> /// <param name="beginCallBack"></param> /// <param name="compleateCallBack"></param> protected void Resource_Upload_Single(Action beginCallBack, Action <string, int, string> compleateCallBack) { try { if (this.currentBreadLine != null && this.currentBreadLine.Folder != null) { int ItemID = this.currentBreadLine.Folder.ID; //使用打开对话框 System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog(); //声明一个缓冲区 byte[] documentStream = null; //文件名称 string documentName = null; //点击确定 if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //this.ShowTip(); if (beginCallBack != null) { beginCallBack(); } //获取指定名称 documentName = dialog.SafeFileName; string fileName = System.IO.Path.GetFileName(documentName); //获取文件流 Stream stream = dialog.OpenFile(); //创建一个缓冲区 documentStream = new byte[stream.Length]; //将流写入指定缓冲区 stream.Read(documentStream, 0, documentStream.Length); Resource_UploadHelper(compleateCallBack, ItemID, documentStream, fileName); } } } catch (Exception ex) { LogManage.WriteLog(this.GetType(), ex); } finally { } }
private void import_Click(object sender, RoutedEventArgs e) { using (System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog()) { openFileDialog.Filter = "All files (*.*)|*.*"; if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { var fileStream = openFileDialog.OpenFile(); using (StreamReader reader = new StreamReader(fileStream)) { var x = JsonConvert.DeserializeObject <List <videoitem> >(reader.ReadToEnd()); videoitems = new ObservableCollection <videoitem>(x); data.ItemsSource = (new ObservableCollection <videoitem>(x)); } } } }
private void mnuOpenXaml_Click(object sender, RoutedEventArgs e) { try { var dlg = new System.Windows.Forms.OpenFileDialog(); if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { IO.Stream fstream = dlg.OpenFile(); var cv = (Canvas)markup.XamlReader.Load(fstream); cv.Name = ShapeFactory.MakeCtrlId(); mainCanvas.Children.Add(cv); } } catch (Exception ex) { log.Log(mko.Log.RC.CreateError(ex.Message)); } }
private async Task SetCredentailLocationMethod(object token) { System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog(); dialog.InitialDirectory = Properties.Settings.Default.CredentialFilepath; dialog.ShowDialog(); try { using (FileStream stream = (FileStream)dialog.OpenFile()) { // The file token.json stores the user's access and refresh tokens, and is created automatically when the authorization flow completes for the first time. await Task.Factory.StartNew(() => WebAuthorizeGoogleDrive(stream)); } } catch (Exception) { CredentialDirectory = "Error parsing file for credentials, please choose a credentials.json file."; } }
public void LoadMap() { /* Temporaily ask the player for a maze to load if maze doesn't exist */ // Create a stream for loading the file Stream loadStream; // Create a dialog for asking for save location System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog(); dialog.Filter = "maze files (*.maz)|*.maz"; dialog.InitialDirectory = Directory.GetCurrentDirectory() + "\\DefaultMazes\\"; // Ask the user for a file to load if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK && (loadStream = dialog.OpenFile()) != null) { maze = new Maze(loadStream, GraphicsDevice.Viewport); stateGame = GameState.Play; } }
private void WCFOpeningReportInDesigner(object sender, Stimulsoft.Report.Events.StiWCFOpeningReportEventArgs e) { if (!Equals(sender, DesignerControl)) { return; } //Открываем файл using (System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog()) { openDialog.Filter = "MRT-отчет|*.mrt"; if (openDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { _reportUn = null; tbReportName.Text = ""; var s = openDialog.OpenFile(); var report = new StiReport(); report.Load(s); var dc = DesignerControl; if (dc == null) { return; } dc.Report = report; tbReportName.Text = Path.GetFileNameWithoutExtension(openDialog.FileName) + " (из файла)"; } catch (Exception ex) { Manager.UI.ShowMessage("Отчет не загружен:\n" + ex.Message); var dc = DesignerControl; if (dc == null) { return; } dc.Report = new StiReport(); } } } }
public Player loadPlayer() { Player temp = null; System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); Stream myStream; dlg.Filter = "He Dies At The End (.hdate) | *.hdate"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK == true) { if ((myStream = dlg.OpenFile()) != null) { IFormatter formatter = new BinaryFormatter(); temp = (Player)formatter.Deserialize(myStream); myStream.Close(); } } return(temp); }
private void OpenQueryMenuItem_Click(object sender, RoutedEventArgs e) { var dlg = new System.Windows.Forms.OpenFileDialog(); dlg.Filter = "yml files (*.yml)|*.yml|All files (*.*)|*.*"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { using (var reader = new StreamReader(dlg.OpenFile())) { DataContext = SearchQuerySerializer.FromYaml(reader); } } catch (Exception ex) { MessageBox.Show("Error opening query: " + ex.Message, "Open Query Error", MessageBoxButton.OK, MessageBoxImage.Error); } } }
private void ReadFile() { try { var fileDialog = new System.Windows.Forms.OpenFileDialog(); var result = fileDialog.ShowDialog(); switch (result) { case System.Windows.Forms.DialogResult.OK: if (fileDialog.FileName.Contains(".csv")) { if (int.TryParse(Day.Text, out var day) && int.TryParse(Hours.Text, out var hours)) { var timeSet = ReadCSVFile.GetTimesPerDay(fileDialog.OpenFile(), day - 1, hours - 1); var times = new List <TimeObject>(); var project = (Project)Projects.SelectedItem; var module = (Projectmodule)Modules.SelectedItem; var worktype = (Projectworktype)WorkTypes.SelectedItem; times.AddRange(timeSet.Select(time => new TimeObject { personid = _primaryInformation != null ? _primaryInformation.Me.personid.ToString() : _userData.PersonId, time = Math.Round(time.Value, 2).ToString(CultureInfo.InvariantCulture), billable = "t", date = DateTime.Parse(time.Key).ToString("yyyy-MM-dd"), projectid = int.Parse(project.id).ToString(), moduleid = int.Parse(module.moduleid).ToString(), worktypeid = int.Parse(worktype.worktypeid).ToString() })); _userTimes = new UserTimes(_timeTaskService, times); Submit.IsEnabled = true; } } break; } } catch (Exception e) { MessageBox.Show(e.Message); } }
private void RestoreAllDataClick(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); openFileDialog1.InitialDirectory = Path.GetTempPath(); openFileDialog1.Filter = "archive files (*.zip)|*.7z|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { using (ZipArchive archive = new ZipArchive(openFileDialog1.OpenFile())) { // TODO: What does restore mean? Right now, just extracts to temp. // would have to do some somersaults to switch DB and change app context to stored config. foreach (ZipArchiveEntry entry in archive.Entries) { entry.ExtractToFile(Path.Combine(Path.GetTempPath(), entry.FullName), true); } } } }
public void LoadSettingsProfile() { var dialog = new System.Windows.Forms.OpenFileDialog() { DefaultExt = "xml", Filter = "xml files (*.xml)|*.xml", InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "config.xml"), }; if (dialog.ShowDialog() != DialogBoxResult.OK) { return; } try { var serializer = new XmlSerializer(typeof(List <SettingsProfileEntry>)); List <SettingsProfileEntry> list; using (Stream input = dialog.OpenFile()) list = (List <SettingsProfileEntry>)serializer.Deserialize(input); foreach (SettingsProfileEntry entry in list) { if (!_viewModelRegistryKeys.ContainsKey(entry.KeyName) || entry.Value == _viewModelRegistryKeys[entry.KeyName].KeyValue) { continue; } _viewModelRegistryKeys[entry.KeyName] = new Stereo3DRegistryKey(entry.KeyName, entry.Value); OnPropertyChanged(entry.KeyName); } } catch (Exception) { MessageBox.Show("Your profile could not be loaded.", "Profile Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
private void OnClick_LoadScript(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); dlg.AddExtension = true; dlg.DefaultExt = ".bql"; dlg.Title = "Specify the script file"; dlg.Filter = "Building Query Language|*.bql"; dlg.FilterIndex = 0; dlg.ValidateNames = true; dlg.FileOk += delegate(object s, System.ComponentModel.CancelEventArgs eArg) { Stream file = null; string dataFormat = "Text"; try { file = dlg.OpenFile(); TextRange txtRange = new TextRange(ScriptText.Document.ContentStart, ScriptText.Document.ContentEnd); if (txtRange.CanLoad(dataFormat)) { txtRange.Load(file, dataFormat); } this.Title = "BQL Console - " + System.IO.Path.GetFileName(dlg.FileName); } catch (Exception ex) { System.Windows.MessageBox.Show(string.Format("Loading script from file failed : {0}.", ex.Message), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } finally { if (file != null) { file.Close(); } } }; dlg.ShowDialog(); ScriptText.RefreshKeyColour(); }
// Open file image #region Open File image private void butopen_Click(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); openFileDialog1.Title = "Select Photos"; openFileDialog1.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"; openFileDialog1.CheckFileExists = true; openFileDialog1.CheckPathExists = true; Stream myStream = null; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { if ((myStream = openFileDialog1.OpenFile()) != null) { using (myStream) { string file = openFileDialog1.FileName; ib = new ImageBrush(); ib.ImageSource = new BitmapImage(new Uri(file, UriKind.Relative)); myCanvas.Background = ib; myCanvas.Children.Clear(); } } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } }
private void BtnLoad_Click(object sender, RoutedEventArgs e) { using (System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog { FileName = "pipeline", Filter = Properties.strings.FileFilter, InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), DefaultExt = "json", }) { if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { using Stream fileStream = ofd.OpenFile(); using var streamReader = new StreamReader(fileStream); GraphicalPipeLineDefinition?pdef = JsonConvert.DeserializeObject <GraphicalPipeLineDefinition>(streamReader.ReadToEnd()); if (pdef != null) { this.Pipeline.FromDefinition(pdef); } } } }
private Stream EscolherArquivo() { //Cria uma tela de seleção de arquivo var fileDialog = new System.Windows.Forms.OpenFileDialog(); fileDialog.Filter = "JPG Files (*.jpg)|*.jpg|JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|GIF Files (*.gif)|*.gif"; //Mostra a tela e guarda a resposta no resultado var result = fileDialog.ShowDialog(); switch (result) { //Se o resultado foi: escolheu um arquivo, retorna o arquivo case System.Windows.Forms.DialogResult.OK: this.NomeArquivo = fileDialog.FileName; return fileDialog.OpenFile(); //Se o resultado foi: Cancelou ou qualquer outro(fechou), retorna nulo case System.Windows.Forms.DialogResult.Cancel: default: this.NomeArquivo = string.Empty; return null; } }
public string OpenDBDialog(string defaultPath) { Stream FileOpened; System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); openFileDialog1.Title = "Укажите путь к файлу Базы Данных"; openFileDialog1.InitialDirectory = defaultPath; openFileDialog1.Filter = "DataBase files (*.mdb)|*.mdb| All files (*.*)|*.*"; openFileDialog1.FilterIndex = 1; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { CloseDB(); if ((FileOpened = openFileDialog1.OpenFile()) != null) { FileOpened.Close(); try { if (!OpenDB(openFileDialog1.FileName)) { throw new Exception("Не удалось подключится к базе данных " + openFileDialog1.FileName); } return(openFileDialog1.FileName); } catch (Exception ex) { ErrorWork.ErrorProcess(ex); }; } ; } ; return(""); }
internal void ParseSCPD(String XML, int startLine) { bool loadSchema = false; string schemaUrn = ""; if (XML == "") { return; } string evented = "no"; string multicast = "no"; StringReader MyString = new StringReader(XML); XmlTextReader XMLDoc = new XmlTextReader(MyString); XMLDoc.Read(); XMLDoc.MoveToContent(); if (XMLDoc.LocalName == "scpd") { try { if (XMLDoc.HasAttributes) { // May be UPnP/1.1 SCPD for (int i = 0; i < XMLDoc.AttributeCount; i++) { XMLDoc.MoveToAttribute(i); if (XMLDoc.Prefix == "xmlns") { loadSchema = true; schemaUrn = XMLDoc.Value; } // ToDo: Try to load the schema from the network first // if (XMLDoc.LocalName=="schemaLocation") // { // if (XMLDoc.Value=="http://www.vendor.org/Schemas/Sample.xsd") // { // schemaUrn = XMLDoc.LookupNamespace(XMLDoc.Prefix); // } // } } XMLDoc.MoveToElement(); if (loadSchema) { // Prompt Application for local Schema Location System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog(); fd.Multiselect = false; fd.Title = schemaUrn; if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FileStream fs = (FileStream)fd.OpenFile(); System.Text.UTF8Encoding U = new System.Text.UTF8Encoding(); byte[] buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); UPnPComplexType[] complexTypes = UPnPComplexType.Parse(U.GetString(buffer)); fs.Close(); foreach (UPnPComplexType complexType in complexTypes) { this.AddComplexType(complexType); } } } } XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "scpd") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "actionList" && !XMLDoc.IsEmptyElement) { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "actionList") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "action") { int embeddedLine = XMLDoc.LineNumber; //ParseActionXml("<action>\r\n" + XMLDoc.ReadInnerXml() + "</action>", embeddedLine); ParseActionXml(XMLDoc.ReadOuterXml(), embeddedLine-1); } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "actionList") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { if (XMLDoc.LocalName == "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "serviceStateTable") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "stateVariable") { evented = "no"; multicast = "no"; XMLDoc.MoveToAttribute("sendEvents"); if (XMLDoc.LocalName == "sendEvents") { evented = XMLDoc.GetAttribute("sendEvents"); } XMLDoc.MoveToAttribute("multicast"); if (XMLDoc.LocalName == "multicast") { multicast = XMLDoc.GetAttribute("multicast"); } XMLDoc.MoveToContent(); ParseStateVarXml(evented, multicast, XMLDoc, startLine); } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { XMLDoc.Skip(); } } if (!XMLDoc.IsStartElement()) { XMLDoc.Read(); XMLDoc.MoveToContent(); } } // End of While } catch (XMLParsingException ex) { throw ex; } catch (Exception ex) { throw new XMLParsingException("Invalid SCPD XML", startLine + XMLDoc.LineNumber, XMLDoc.LinePosition, ex); } // Add Associations foreach (UPnPAction A in this.Actions) { foreach (UPnPArgument G in A.Arguments) { if (G.RelatedStateVar == null) { throw (new InvalidRelatedStateVariableException("Action: " + A.Name + " Arg: " + G.Name + " Contains invalid reference: " + G.StateVarName)); } G.RelatedStateVar.AddAssociation(A.Name, G.Name); } } } // End of If }
/// <summary> /// Parses a service xml into the UPnPservice instance. The instance will have been created by /// parsing the Service element from the Device xml, see <see cref="UPnPService.Parse">Parse method</see> /// </summary> /// <param name="XML">the xml containing the service description</param> internal void ParseSCPD(String XML) { bool loadSchema = false; string schemaUrn = ""; if (XML == "") { return; } string evented = "no"; string multicast = "no"; StringReader MyString = new StringReader(XML); XmlTextReader XMLDoc = new XmlTextReader(MyString); XMLDoc.Read(); XMLDoc.MoveToContent(); if (XMLDoc.LocalName == "scpd") { if (XMLDoc.HasAttributes) { // May be UPnP/1.1 SCPD for (int i = 0; i < XMLDoc.AttributeCount; i++) { XMLDoc.MoveToAttribute(i); if (XMLDoc.Prefix == "xmlns") { loadSchema = true; schemaUrn = XMLDoc.Value; } // ToDo: Try to load the schema from the network first // if (XMLDoc.LocalName=="schemaLocation") // { // if (XMLDoc.Value=="http://www.vendor.org/Schemas/Sample.xsd") // { // schemaUrn = XMLDoc.LookupNamespace(XMLDoc.Prefix); // } // } } XMLDoc.MoveToElement(); if (loadSchema) { // Prompt Application for local Schema Location System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog(); fd.Multiselect = false; fd.Title = schemaUrn; if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FileStream fs = (FileStream)fd.OpenFile(); System.Text.UTF8Encoding U = new System.Text.UTF8Encoding(); byte[] buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); UPnPComplexType[] complexTypes = UPnPComplexType.Parse(U.GetString(buffer)); fs.Close(); foreach (UPnPComplexType complexType in complexTypes) { this.AddComplexType(complexType); } } } } XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "scpd") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "actionList" && !XMLDoc.IsEmptyElement) { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "actionList") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "action") { string actionxml = "Failed to read the Action element from the source xml."; try { //TODO: DONE Resilience case 4 & 2 - if action fails itself (or underlying arguments), don't add it. //Wrap in try-catch actionxml = "<action>\r\n" + XMLDoc.ReadInnerXml() + "</action>"; ParseActionXml(actionxml); } catch (Exception e) { OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Invalid Action XML"); OpenSource.Utilities.EventLogger.Log(e, "XML content: \r\n" + actionxml); OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Warning, "Dropping failed Action and commencing parsing remainder of device"); } } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "actionList") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { if (XMLDoc.LocalName == "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "serviceStateTable") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "stateVariable") { // TODO: DONE Resilience case 1 - wrap block in try-catch, with error logging try { evented = "no"; multicast = "no"; XMLDoc.MoveToAttribute("sendEvents"); if (XMLDoc.LocalName == "sendEvents") { evented = XMLDoc.GetAttribute("sendEvents"); } XMLDoc.MoveToAttribute("multicast"); if (XMLDoc.LocalName == "multicast") { multicast = XMLDoc.GetAttribute("multicast"); } XMLDoc.MoveToContent(); ParseStateVarXml(evented, multicast, XMLDoc); } catch (Exception e) { OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Invalid StateVariable XML"); OpenSource.Utilities.EventLogger.Log(e); OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Warning, "Dropping failed StateVariable and commencing parsing remainder of device"); } } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { XMLDoc.Skip(); } } if (!XMLDoc.IsStartElement()) { XMLDoc.Read(); XMLDoc.MoveToContent(); } } // End of While // TODO: DONE Resilience case 3 - log error, and mark faulty Action // Add Associations System.Collections.ArrayList skiplist = new System.Collections.ArrayList(); foreach (UPnPAction A in this.Actions) { try { foreach (UPnPArgument G in A.Arguments) { if (G.RelatedStateVar == null) { throw (new InvalidRelatedStateVariableException("Action: " + A.Name + " Arg: " + G.Name + " Contains invalid reference: " + G.StateVarName)); } G.RelatedStateVar.AddAssociation(A.Name, G.Name); } } catch (Exception e) { // adding it failed, so add to skiplist skiplist.Add(A); OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Error, "Invalid Action; could not create Argument-Statevariable association for action: " + A.Name); OpenSource.Utilities.EventLogger.Log(e); OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.Warning, "Dropping failed StateVariable and arguments, commencing parsing remainder of actions"); } } // Ditch the faulty ones // TODO: DONE Resilience case 3 - remove faulty Action and its Arguments and their relations foreach (UPnPAction A in skiplist) { // remove previously added associations foreach (UPnPArgument G in A.Arguments) { if (G.RelatedStateVar != null) { G.RelatedStateVar.RemoveAssociation(A.Name, G.Name); } } // remove action itself RemoteMethods.Remove(A.Name); } } // End of If }
private void addDocFileButton_Click(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog fileBrowser = new System.Windows.Forms.OpenFileDialog(); fileBrowser.Filter = "Documents (*.doc;*.docx)|*.doc;*.docx|All files (*.*)|*.*"; if (fileBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK) { Stream docStream = null; try { if ((docStream = fileBrowser.OpenFile()) != null) { using (docStream) { } // don't use the stream } } catch (SystemException ex) { addDocLocationLabel.Content = ""; Logger.log(TraceEventType.Critical, 9, "File exception\r\n" + ex.GetType() + ":" + ex.Message + "\r\n" + ex.StackTrace); statusLabel.Content = "Error: Could not read file. Original error: " + ex.Message; return; } // check if have merge doc if (!checkWord()) { addDocLocationLabel.Content = ""; return; } statusLabel.Content = "Click Yes in word..."; //ghetto to make the label update Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(delegate { })); Word.Document doc = wordApp.Application.Documents.Open(fileBrowser.FileName, ReadOnly: true, Visible: false); //Console.WriteLine(doc.MailMerge.State); //Console.WriteLine(doc.MailMerge.DataSource.ConnectString); //Console.WriteLine(doc.MailMerge.DataSource.QueryString); if (doc.MailMerge.State == Word.WdMailMergeState.wdMainAndDataSource) { addDocLocationLabel.Content = fileBrowser.FileName; statusLabel.Content = "Ready."; //Console.WriteLine("" + doc.MailMerge.DataSource.DataFields[1].Value + doc.MailMerge.DataSource.DataFields[2].Value + //doc.MailMerge.DataSource.DataFields[3].Value); } else { addDocLocationLabel.Content = ""; statusLabel.Content = "Selected document does not have merge data."; } ((Word._Document)doc).Close(SaveChanges: false); Marshal.FinalReleaseComObject(doc); } else { addDocLocationLabel.Content = ""; } }
private void mnuFileLoad_Click(object sender, EventArgs e) { this.gameTimer.IsEnabled = false; MessageBoxResult res = MessageBox.Show("You will lose all progress on your current game.\nIs that ok?", "Load previous game", MessageBoxButton.YesNo); if (res == MessageBoxResult.Yes) { fallingPattern = null; patterns.Clear(); initializeBoard(); myGameCanvas.Children.Clear(); Stream sr; var folderBrowserDialog = new System.Windows.Forms.OpenFileDialog(); System.Windows.Forms.DialogResult result = folderBrowserDialog.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { sr = folderBrowserDialog.OpenFile(); List <int> board = new List <int>(); try { using (StreamReader stream = new StreamReader(sr)) { string txt = ""; this.playerName = stream.ReadLine(); string boolean = stream.ReadLine(); if (boolean.Equals("True")) { this.classic = true; } else { this.classic = false; } this.curScore = Int32.Parse(stream.ReadLine()); this.score.Content = "" + curScore; this.totalCompletedRows = Int32.Parse(stream.ReadLine()); while ((txt = stream.ReadLine()) != null) { if (!txt.Equals("")) { board.Add(Int32.Parse(txt)); } } } int count = 0; string str = ""; for (int x = 0; x < 18; x++) { for (int y = 0; y < 10; y++) { gameBoard[x, y] = board[count]; str += board[count] + " "; count++; } str += "\n"; } Pattern patt; Boolean Empty = false; for (int a = 17; a > -1; a--) { if (!Empty) { Empty = true; for (int b = 0; b < 10; b++) { if (gameBoard[a, b] != 0 && CanCreate(gameBoard[a, b])) { Empty = false; patt = new Pattern(this, gameBoard[a, b], false); patterns.Add(patt); } if (gameBoard[a, b] != 0) { Empty = false; } } } } } catch (Exception err) { MessageBox.Show("Unable to Load File."); } } initializeBoard(); foreach (Pattern item in patterns) { item.paintPattern(); } this.gameTimer.IsEnabled = true; SpawnFirst(); } else { this.gameTimer.IsEnabled = true; } }
public MainMenu(MinerGame game) : base(game) { MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2 - 300, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), START, (menu) => { // Following line protects new menu from instantly reading previous key as pressed. DifficultyMenu newMenu = new DifficultyMenu(this.Game, this) { OldKeyState = this.CurrentKeyState }; MenuManager.GetInstance().CurrentMenu = newMenu; })); MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2 - 150, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), LOAD_GAME, (menu) => { System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog(); if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { this.Game.Content.Unload(); using (Stream stream = openFile.OpenFile()) { XmlSerializer xml = new XmlSerializer(typeof(GameState)); this.Game.GameState = (GameState)xml.Deserialize(stream); this.Game.GameState.Miner.Suit = new Nanosuit(); stream.Close(); } this.Game.GameState.Miner.game = this.Game; foreach (var item in this.Game.GameState.Enemies) { item.game = this.Game; } foreach (var item in this.Game.GameState.Bullets) { item.game = this.Game; } this.Game.Content.Load<SpriteFont>("general"); this.Game.Content.Load<Texture2D>(Kosmojopek.ASSET_NAME); this.Game.Content.Load<Texture2D>(Ufolowca.ASSET_NAME); this.Game.Content.Load<Texture2D>(WladcaLaserowejDzidy.ASSET_NAME); //this.Content.Load<Texture2D>(PoteznySultan.ASSET_NAME); this.Game.Content.Load<Texture2D>(Miner.ASSET_NAME); //this.Content.Load<Texture2D>(CosmicMatter.ASSET_NAME); this.Game.Content.Load<Texture2D>(DoubleJump.ASSET_NAME); this.Game.Content.Load<Texture2D>(Field.ASSET_NAME); this.Game.Content.Load<Texture2D>(Fuel.ASSET_NAME); this.Game.Content.Load<Texture2D>(Indestructibility.ASSET_NAME); this.Game.Content.Load<Texture2D>(Key.ASSET_NAME); this.Game.Content.Load<Texture2D>(KeyLocalizer.ASSET_NAME); this.Game.Content.Load<Texture2D>(Laser.ASSET_NAME); this.Game.Content.Load<Texture2D>(MoreEnemies.ASSET_NAME); this.Game.Content.Load<Texture2D>(SolidRock.ASSET_NAME); this.Game.Content.Load<Texture2D>(SpaceGate.ASSET_NAME); this.Game.Content.Load<Texture2D>(TitanRock.ASSET_NAME); this.Game.Content.Load<Texture2D>(Bullet.ASSET_NAME); this.Game.GameState.Miner.LoadContent(); foreach (var item in this.Game.GameState.Enemies) { item.LoadContent(); } foreach (var item in this.Game.GameState.Bullets) { item.LoadContent(); } foreach (var item in this.Game.GameState.Map.Fields) { foreach (var field in item) { field.game = this.Game; field.LoadContent(); } } GameScene newScene = new GameScene(this.Game) { OldKeyState = this.CurrentKeyState }; MenuManager.GetInstance().CurrentMenu = newScene; } catch (Exception exc) { System.Windows.Forms.MessageBox.Show(ERROR_READING_FILE + exc.Message); } } })); MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), HIGH_SCORES, (menu) => { // Following line protects new menu from instantly reading previous key as pressed. HighScoreMenu newMenu = new HighScoreMenu(this.Game, this) { OldKeyState = this.CurrentKeyState }; MenuManager.GetInstance().CurrentMenu = newMenu; })); MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2 + 150, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), SETTINGS, (menu) => { SettingsMenu newMenu = new SettingsMenu(this.Game, this) { OldKeyState = this.CurrentKeyState }; MenuManager.GetInstance().CurrentMenu = newMenu; })); MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2 + 300, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), EXIT, (menu) => { menu.Game.ExitGame(); })); MenuItems[currentlySelected].Selected = true; }
private void RestoreAllDataClick(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); openFileDialog1.InitialDirectory = Path.GetTempPath(); openFileDialog1.Filter = "archive files (*.zip)|*.7z|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { using (ZipArchive archive = new ZipArchive(openFileDialog1.OpenFile())) { // TODO: What does restore mean? Right now, just extracts to temp. // would have to do some somersaults to switch DB and change app context to stored config. foreach (ZipArchiveEntry entry in archive.Entries) { entry.ExtractToFile(Path.Combine(Path.GetTempPath(), entry.FullName),true); } } } }
protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) { Exit(); } x += -1 * Utility.UserInput.getXAxis(); y += -1 * Utility.UserInput.getYAxis(); transform = Matrix.CreateTranslation(x, y, 0); var MouseX = Mouse.GetState().X; var MouseY = Mouse.GetState().Y; var mousePosition = new Vector2(MouseX, MouseY); cursor.Update(Mouse.GetState().Position.ToVector2()); Console.WriteLine(paused); if (delay < gameTime.TotalGameTime.TotalSeconds) { if (Keyboard.GetState().IsKeyDown(Keys.Back)) { if (paused) { paused = false; } else { paused = true; } delay = gameTime.TotalGameTime.TotalSeconds + .25; } Console.WriteLine(paused); if (!paused) { if (Keyboard.GetState().IsKeyDown(Keys.LeftShift)) { expansionSpeed = 5; } if (Keyboard.GetState().IsKeyUp(Keys.LeftShift)) { expansionSpeed = 1; } if (Keyboard.GetState().IsKeyDown(Keys.W)) { var width = cursor._Texture.Width + (1 * expansionSpeed); var height = cursor._Texture.Height; var texture = TextureGen.CreateTexture(width, height, cursor._Color); cursor.Update(texture); } if (Keyboard.GetState().IsKeyDown(Keys.Q)) { Console.WriteLine(cursor._Texture.Width); if (cursor._Texture.Width > 5) { var width = cursor._Texture.Width - (1 * expansionSpeed); var height = cursor._Texture.Height; var texture = TextureGen.CreateTexture(width, height, cursor._Color); cursor.Update(texture); } } if (Keyboard.GetState().IsKeyDown(Keys.P)) { var width = cursor._Texture.Width; var height = cursor._Texture.Height + (1 * expansionSpeed); var texture = TextureGen.CreateTexture(width, height, cursor._Color); cursor.Update(texture); } if (Keyboard.GetState().IsKeyDown(Keys.O)) { if (cursor._Texture.Height > 5) { var width = cursor._Texture.Width; var height = cursor._Texture.Height - (1 * expansionSpeed); var texture = TextureGen.CreateTexture(width, height, cursor._Color); cursor.Update(texture); } } if (Mouse.GetState().LeftButton == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Enter)) { level.AddTile(cursor); delay = gameTime.TotalGameTime.TotalSeconds + .25; } if (Mouse.GetState().RightButton == ButtonState.Pressed) { List <Tile> Delete = new List <Tile>(); foreach (var block in level.GetList()) { if (cursor._Rectangle.Intersects(block._Rectangle)) { Delete.Add(block); } } foreach (var block in Delete) { level.Delete(block); } Delete.Clear(); delay = gameTime.TotalGameTime.TotalSeconds + .25; } if (Keyboard.GetState().IsKeyDown(Keys.T)) { if (tCount <= 0) { tCount = Tiles.Length - 1; } else { tCount--; } cursor = Tiles[tCount]; delay = gameTime.TotalGameTime.TotalSeconds + .25; } if (Keyboard.GetState().IsKeyDown(Keys.L)) { System.Windows.Forms.OpenFileDialog oDialogue = new System.Windows.Forms.OpenFileDialog(); oDialogue.Filter = "Data Files (*.dat) | *.dat "; oDialogue.RestoreDirectory = true; if (oDialogue.ShowDialog() == System.Windows.Forms.DialogResult.OK) { var stream = oDialogue.OpenFile(); var data = SerializerUtility.DataManagementXML.Load(stream); if (data.Count > 0) { level = LevelGenerator.GenerateLevel(data[0], GraphicsDevice); } } } if (Keyboard.GetState().IsKeyDown(Keys.S)) { System.Windows.Forms.SaveFileDialog sDialogue = new System.Windows.Forms.SaveFileDialog(); sDialogue.Filter = "Data Files (*.dat) | *.dat "; sDialogue.RestoreDirectory = true; if (sDialogue.ShowDialog() == System.Windows.Forms.DialogResult.OK) { var fileStream = sDialogue.OpenFile(); SerializerUtility.DataManagementXML.Save(fileStream, level.GenerateBlueprint()); } } if (Keyboard.GetState().IsKeyDown(Keys.Delete)) { level.Delete(); } } } base.Update(gameTime); }
private void btnDirectoryExplorer_Click(object sender, RoutedEventArgs e) { //using (var ofdlicense = new System.Windows.Forms.FolderBrowserDialog()) //{ // if (ofdlicense.ShowDialog() == System.Windows.Forms.DialogResult.OK) // { // txtLocation.Text = ofdlicense.SelectedPath; // // folderDialog.SelectedPath -- your result // } //} // ListBoxValidation.Items.Clear(); Stream myStream = null; try { var ofdlicense = new System.Windows.Forms.OpenFileDialog(); ////Dim LicStreamReader As StreamReader ////OfDLicense.InitialDirectory = "c:\" ofdlicense.Filter = "License (*.lic)|*.lic"; ofdlicense.FilterIndex = 1; ofdlicense.InitialDirectory = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (ofdlicense.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtLocation.Text = ofdlicense.SafeFileName; myStream = ofdlicense.OpenFile(); if (myStream.Length <= 0) { return; } if (File.Exists("lic.lic")) { try { File.Delete("lic.lic"); } catch (Exception) { Logger.Log.Logger.LogData("License File (lic.lic) is used by other process", LogLevel.Error); } } File.Copy(ofdlicense.FileName, "lic.lic"); this.ulicense = License.Load(myStream); //this.TextBoxCustomerRo.Text = this.ulicense.Customer.Name; //this.TextBoxEMailRo.Text = this.ulicense.Customer.Email; //this.TextBoxUsersRo.Text = this.ulicense.Quantity.ToString(CultureInfo.InvariantCulture); //this.TextBoxAttributeNameRo.Text = "Software"; //this.TextBoxAttributeValueRo.Text = this.ulicense.AdditionalAttributes.Get(this.TextBoxAttributeNameRo.Text); //this.CheckBoxSalesRo.IsChecked = this.ulicense.ProductFeatures.Get("Sales") == "True"; //this.CheckBoxBillingRo.IsChecked = this.ulicense.ProductFeatures.Get("Billing") == "True"; //this.TextBoxLicenseType.Text = this.ulicense.Type.ToString(); string publickey = txtpublickey.Text; string path = Environment.CurrentDirectory + "//PublicKey.txt"; if (File.Exists(path)) { try { File.Delete(path); } catch (Exception) { Logger.Log.Logger.LogData("Public key File (PublicKey.txt) is used by other process", LogLevel.Error); } } File.AppendAllLines(path, new[] { publickey }); LicenseHelper lf = new LicenseHelper(); var str = lf.ValidateLicense(this.ulicense, publickey); lblvalidity.Content = str; if (str == "Activated: License is Valid") { DialogResult = true; } else { DialogResult = false; } } } catch (Exception ex) { DialogResult = false; Log.Logger.LogData("Cannot read file from disk. Original error: " + ex.Message, LogLevel.Error); } finally { //// Check this again, since we need to make sure we didn't throw an exception on open. if (myStream != null) { myStream.Close(); } } }
private void ImportClick(object sender, RoutedEventArgs e) { importFileDialog = new System.Windows.Forms.OpenFileDialog(); importFileDialog.Multiselect = false; importFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal); importFileDialog.Filter = "XML Files (*.xml)|*.xml|All Files (*.*)|*.*"; importFileDialog.FilterIndex = 0; importFileDialog.RestoreDirectory = false; if (importFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { XmlDocument tmpXml = new XmlDocument(); tmpXml.Load(importFileDialog.OpenFile()); XmlNodeList tmpCards = tmpXml.SelectNodes(@"//card"); XmlNodeList tmpTranslations; List<string> tmpTranslationsList; string tmpWord; string[] separatedTranslations; foreach (XmlNode tmpCard in tmpCards) { tmpWord = tmpCard.SelectSingleNode(@"word").InnerText.ToLower().Trim(); tmpTranslations = tmpCard.SelectNodes(@"meanings/meaning/translations/word"); tmpTranslationsList = new List<string>(); foreach (XmlNode tmpTranslation in tmpTranslations) { separatedTranslations = tmpTranslation.InnerText.ToLower().Split(','); foreach (string tmpTranslationWord in separatedTranslations) tmpTranslationsList.Add(tmpTranslationWord.Trim()); } if (!cards.ContainsKey(tmpWord)) { cards.Add(tmpWord, new Card() { Mode = CardMode.Untouched, Word = tmpWord, Translations = tmpTranslationsList, Shown = 0, Tested = 0 }); cardsForDataGrid.Add(cards[tmpWord].Data); } else { cardsForDataGrid.Remove(cards[tmpWord].Data); cards[tmpWord].Translations = cards[tmpWord].Translations.Concat(tmpTranslationsList).Distinct().ToList(); cards[tmpWord].Mode = CardMode.Untouched; cardsForDataGrid.Add(cards[tmpWord].Data); } } CardGrid.ItemsSource = null; CardGrid.ItemsSource = cardsForDataGrid; } }
public Player loadPlayer() { Player temp = null; System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); Stream myStream; dlg.Filter = "He Dies At The End (.hdate) | *.hdate"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK == true) { if ((myStream = dlg.OpenFile()) != null) { IFormatter formatter = new BinaryFormatter(); temp = (Player)formatter.Deserialize(myStream); myStream.Close(); } } return temp; }
private void ImportProxysExec() { Stream myStream = null; System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { if ((myStream = openFileDialog1.OpenFile()) != null) { using (myStream) { StreamReader reader = new StreamReader(myStream); string line; //option.Proxys.Clear(); while ((line = reader.ReadLine()) != null) { option.Proxys.Add(new ProxyServer(line, true)); } } } } catch (Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); } } }
/// <summary> /// Método que importa almacenes desde un fichero CSV. Abre el explorador de archivos para obtener el fichero /// a importar y controla que sea un fichero de almacenes, esten todos los campos, no haya almacenes repetidos y /// no esten ciertos campos vacios o con formatos erroneos. /// </summary> private void AccionImportar() { // abrir el explorador de archivos System.Windows.Forms.OpenFileDialog dialogoBuscarArchivo = new System.Windows.Forms.OpenFileDialog(); // filtrar for ficheros csv dialogoBuscarArchivo.Filter = "CSV Files|*.csv"; dialogoBuscarArchivo.Title = (string)Application.Current.FindResource("abrirFicheroCSV"); dialogoBuscarArchivo.FilterIndex = 1; dialogoBuscarArchivo.Multiselect = false; if (dialogoBuscarArchivo.ShowDialog() == System.Windows.Forms.DialogResult.OK) { using (Stream stream = dialogoBuscarArchivo.OpenFile()) // abrir el fichero { string ruta = dialogoBuscarArchivo.FileName; StreamReader file = new StreamReader(ruta); string line; // Fichero debe comenzar en la primera linea con 'Almacenes' string m = (string)Application.Current.FindResource("Almacenes"); if (file.ReadLine().StartsWith(m)) { int error = 0; // controlar errores int numLinea = 0; // controlar el numero de linea List <Almacen> arrayAlmacenes = new List <Almacen>(); // almacenes a añadir while ((line = file.ReadLine()) != null) // leer cada linea del fichero { String[] l = line.Split(';'); // obtener campos numLinea++; Almacen a; MySQLDB.Instance.ConnectDB("IdAlmacenes"); String[] almacenes = MySQLDB.Instance.almacenes; // obtener id de los almacenes en la BD try { // Campos no esten vacios y tengan el formato correcto if (!l[0].Equals("") && l[0].Length <= 5 && !l[0].Trim().Equals("") && !l[1].Equals("") && l[1].Length <= 20 && !l[1].Trim().Equals("") && !l[2].Equals("") && l[2].Length <= 40 && !l[2].Trim().Equals("")) { // comprobar que el id del almacen no exista ya en la BD int count = 0; for (int i = 0; i < almacenes.Count(); i++) { if (l[0].Trim().Equals(almacenes[i])) { count++; } } if (count == 0) // si no existe { a = new Almacen(l[0].Trim(), l[1], l[2]); // creamos almacen arrayAlmacenes.Add(a); // añadimos a la lista } else { error++; break; } } else { error++; break; } } catch (Exception e) { error++; FicheroLog.Instance.EscribirFichero(e.Message); break; } } if (error > 0) // si hay errores se deja de leer el archivo y se muestra el mensaje con la linea del error { mensajeBox = (string)Application.Current.FindResource("errorImportar"); string mensajeBox1 = (string)Application.Current.FindResource("errorImportar2"); string mensajeBox2 = (string)Application.Current.FindResource("almacenCSV"); MessageBox.Show(mensajeBox + " " + numLinea + "\n\n" + mensajeBox1 + "\n\n" + mensajeBox2 , cabeceraInfo, MessageBoxButton.OK, MessageBoxImage.Information); } else // si no hay errores por cada almacen en la lista lo añadimos a la BD { foreach (Almacen a in arrayAlmacenes) { if (MySQLDB.Instance.InsertarAlmacen(a)) { listaAlmacenes.Add(a); } } mensajeBox = (string)Application.Current.FindResource("importarCSVCorrecto"); MessageBox.Show(mensajeBox, cabeceraInfo, MessageBoxButton.OK, MessageBoxImage.Information); UIGlobal.PageAlmacen.datagrid.Items.Refresh(); } } else // si el fichero no corresponde a almacenes, debe comenzar con 'Almacenes' { mensajeBox = (string)Application.Current.FindResource("importarCSVIncorrecto"); string mensajeBox2 = (string)Application.Current.FindResource("Almacenes"); MessageBox.Show(mensajeBox + " '" + mensajeBox2 + "'", cabeceraInfo, MessageBoxButton.OK, MessageBoxImage.Information); } //cerrar fichero file.Close(); } } }
private void MenuItem_Click(object sender, RoutedEventArgs e) { var item = sender as MenuItem; if(item.Name.Equals("menu_load")) { System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog(); openFileDialog.Title = "选择图片"; openFileDialog.Filter = "JPEG FIles(*.jpg)|*.jpg|PNG files(*.png)|*.png|BMP Files(*.bmp)|*.bmp"; openFileDialog.CheckFileExists = true; openFileDialog.CheckPathExists = true; Stream stream = null; if(openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { if((stream = openFileDialog.OpenFile()) != null) { using (stream) { string file = openFileDialog.FileName; imageName = file; brush = new ImageBrush(); image = new Bitmap(file); brush.ImageSource = new BitmapImage(new Uri(file, UriKind.Relative)); canvas_ink.Height = image.Height; canvas_ink.Width = image.Width; canvas_ink.Background = brush; canvas_ink.Children.Clear(); markedPoints.Clear(); markedRegions.Clear(); startPoint.X = -1; startPoint.Y = -1; } } } catch(Exception ex) { MessageBox.Show("Error: Could not read file from disk. Original error: "+ex.Message); } } } else if(item.Name.Equals("menu_exit")) { this.Close(); } //e.Handled = true; }
public MainWindow() { Log.writeToLog("Starting DatasetReviewer " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); do { bool r; do { System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); dlg.Title = "Open Header file to be displayed..."; dlg.DefaultExt = ".hdr"; // Default file extension dlg.Filter = "HDR Files (.hdr)|*.hdr"; // Filter files by extension bool result = dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK; if (!result) Environment.Exit(0); directory = System.IO.Path.GetDirectoryName(dlg.FileName); //will use to find other files in dataset headerFileName = System.IO.Path.GetFileNameWithoutExtension(dlg.FileName); try { head = (new HeaderFileReader(dlg.OpenFile())).read(); } catch (Exception e) { r = false; //loop around again ErrorWindow ew = new ErrorWindow(); ew.Message = "Error reading Header file: " + e.Message; continue; } ED = head.Events; try { bdf = new BDFEDFFileStream.BDFEDFFileReader( new FileStream(System.IO.Path.Combine(directory, head.BDFFile), FileMode.Open, FileAccess.Read)); } catch (Exception e) { r = false; //loop around again ErrorWindow ew = new ErrorWindow(); ew.Message = "Error reading BDF file header: " + e.Message; ew.ShowDialog(); continue; } BDFLength = (double)bdf.NumberOfRecords * bdf.RecordDurationDouble; Window1 w = new Window1(this); r = (bool)w.ShowDialog(); } while (r == false); Log.writeToLog(" on dataset " + headerFileName); if (includeANAs) { foreach (EventDictionaryEntry ede in ED.Values) // add ANA channels that are referenced by extrinsic Events { if (ede.IsCovered && ede.IsExtrinsic) { int chan = bdf.ChannelNumberFromLabel(ede.channelName); if (!channelList.Contains(chan)) //don't enter duplicate channelList.Add(chan); } } } } while (channelList.Count == 0); InitializeComponent(); //initialize the individual channel graphs foreach (int i in channelList) { ChannelGraph pg = new ChannelGraph(this, i); GraphCanvas.Children.Add(pg); } Title = headerFileName; //set window title BDFFileInfo.Content = bdf.ToString(); HDRFileInfo.Content = head.ToString(); Event.EventFactory.Instance(head.Events); // set up the factory EventFileReader efr = null; try { efr = new EventFileReader( new FileStream(System.IO.Path.Combine(directory, head.EventFile), FileMode.Open, FileAccess.Read)); // open Event file bool z = false; foreach (Event.InputEvent ie in efr)// read in all Events into dictionary { if (ie.IsNaked) events.Add(ie); else if (events.Count(e => e.GC == ie.GC) == 0) //quietly skip duplicates { if (!z) //use first found covered Event to synchronize clocks z = bdf.setZeroTime(ie); events.Add(ie); } } efr.Close(); //now events is Dictionary of Events in the dataset; lookup by GC } catch (Exception e) { ErrorWindow ew = new ErrorWindow(); ew.Message = "Error reading Event file : " + e.Message + ". Exiting DatasetReviewer."; ew.ShowDialog(); Log.writeToLog(Environment.NewLine + e.StackTrace); Environment.Exit(0); } try { ElectrodeInputFileStream eif = new ElectrodeInputFileStream( new FileStream(System.IO.Path.Combine(directory, head.ElectrodeFile), FileMode.Open, FileAccess.Read)); //open Electrode file electrodes = eif.etrPositions; //read 'em in } catch (Exception e) { ErrorWindow ew = new ErrorWindow(); ew.Message = "Error reading Electrode file : " + e.Message + ". Exitting DatasetReviewer."; ew.ShowDialog(); Log.writeToLog(Environment.NewLine + e.StackTrace); Environment.Exit(0); } EventMarkers.Width = BDFLength; eventTB = new TextBlock(new Run("Events")); Canvas.SetBottom(eventTB, ScrollBarSize + 13D); //initialize gridline array for (int i = 0; i < 18; i++) { Line l = new Line(); Grid.SetRow(l, 0); Grid.SetColumn(l, 0); Grid.SetColumnSpan(l, 2); l.Y1 = 0D; l.HorizontalAlignment = HorizontalAlignment.Left; l.VerticalAlignment = VerticalAlignment.Stretch; l.IsHitTestVisible = false; l.Stroke = Brushes.LightBlue; l.Visibility = Visibility.Hidden; Panel.SetZIndex(l, int.MinValue); MainFrame.Children.Add(l); gridlines[i] = l; } //Initialize timer timer.AutoReset = true; timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); //Initialize channel information popup Color c1 = Color.FromArgb(0xFF, 0xF8, 0xF8, 0xF8); Color c2 = Color.FromArgb(0xFF, 0xC8, 0xC8, 0xC8); popupTB.Background = new LinearGradientBrush(c1, c2, 45D); popupTB.Foreground = Brushes.Black; popupTB.Padding = new Thickness(4D); Border b = new Border(); b.BorderThickness = new Thickness(1); b.CornerRadius = new CornerRadius(4); b.BorderBrush = Brushes.Tomato; b.Margin = new Thickness(0, 0, 24, 24); //allows drop shadow to show up b.Effect = new DropShadowEffect(); b.Child = popupTB; channelPopup.Placement = PlacementMode.MousePoint; channelPopup.AllowsTransparency = true; channelPopup.Child = b; //Initialize Event information popup eventPopupTB.Background = new LinearGradientBrush(c1, c2, 45D); eventPopupTB.Foreground = Brushes.Black; eventPopupTB.Padding = new Thickness(4D); b = new Border(); b.BorderThickness = new Thickness(1); b.CornerRadius = new CornerRadius(4); b.BorderBrush = Brushes.Tomato; b.Margin = new Thickness(0, 0, 24, 24); //allows drop shadow to show up b.Effect = new DropShadowEffect(); b.Child = eventPopupTB; eventPopup.Placement = PlacementMode.MousePoint; eventPopup.AllowsTransparency = true; eventPopup.Child = b; //Initialize FOV slider FOV.Maximum = Math.Log10(BDFLength); FOV.Value = 1D; FOVMax.Text = BDFLength.ToString("0"); //Initialize Event selector bool first = true; foreach (EventDictionaryEntry e in head.Events.Values) { MenuItem mi = (MenuItem)EventSelector.FindResource("EventMenuItem"); mi.Header = e.Name; if (first) { mi.IsChecked = true; first = false; } EventSelector.Items.Add(mi); } noteFilePath = System.IO.Path.Combine(directory,System.IO.Path.ChangeExtension(head.BDFFile,".notes.txt")); //from here on the program is GUI-event driven }
private void CommandBinding_Executed_2(object sender, ExecutedRoutedEventArgs e) { System.Windows.Forms.OpenFileDialog dialogName = new System.Windows.Forms.OpenFileDialog(); dialogName.Filter = "Program Files (*.zac)|*.zac"; if (dialogName.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { Stream myStream = null; if ((myStream = dialogName.OpenFile()) != null) { LoadGame(saveControl.open(myStream).GameGrid); } } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); } } }
private void LoadScript_Click(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); dlg.AddExtension = true; dlg.DefaultExt = ".bql"; dlg.Title = "Specify the script file..."; dlg.ValidateNames = true; dlg.FileOk += delegate(object s, System.ComponentModel.CancelEventArgs eArg) { Stream file = null; try { file = dlg.OpenFile(); var reader = new StreamReader(file); var script = reader.ReadToEnd(); ScriptInput.Text = script; } catch (Exception) { System.Windows.MessageBox.Show("Loading script from file failed. Check if the file exist and is readable.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } finally { if (file != null) file.Close(); } }; dlg.ShowDialog(); }
internal void ParseSCPD(String XML) { OpenSource.Utilities.EventLogger.Log (this, System.Diagnostics.EventLogEntryType.SuccessAudit,"Embarking on an xml journey"); bool loadSchema = false; string schemaUrn = ""; if (XML == "") { return; } string evented = "no"; string multicast = "no"; StringReader MyString = new StringReader(XML); XmlTextReader XMLDoc = new XmlTextReader(MyString); XMLDoc.Read(); XMLDoc.MoveToContent(); if (XMLDoc.LocalName == "scpd") { if (XMLDoc.HasAttributes) { // May be UPnP/1.1 SCPD for (int i = 0; i < XMLDoc.AttributeCount; i++) { XMLDoc.MoveToAttribute(i); if (XMLDoc.Prefix == "xmlns") { loadSchema = true; schemaUrn = XMLDoc.Value; } // ToDo: Try to load the schema from the network first // if (XMLDoc.LocalName=="schemaLocation") // { // if (XMLDoc.Value=="http://www.vendor.org/Schemas/Sample.xsd") // { // schemaUrn = XMLDoc.LookupNamespace(XMLDoc.Prefix); // } // } } XMLDoc.MoveToElement(); if (loadSchema) { // Prompt Application for local Schema Location System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog(); fd.Multiselect = false; fd.Title = schemaUrn; if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { FileStream fs = (FileStream)fd.OpenFile(); System.Text.UTF8Encoding U = new System.Text.UTF8Encoding(); byte[] buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); UPnPComplexType[] complexTypes = UPnPComplexType.Parse(U.GetString(buffer)); fs.Close(); foreach (UPnPComplexType complexType in complexTypes) { this.AddComplexType(complexType); } } } } // TODO This parsing is hideous. We should use a proper parser! XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "scpd") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "actionList" && !XMLDoc.IsEmptyElement) { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "actionList") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "action") { OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.SuccessAudit, "Found an action, lets parse it!"); ParseActionXml("<action>\r\n" + XMLDoc.ReadInnerXml() + "</action>"); } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "actionList") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { if (XMLDoc.LocalName == "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); while ((XMLDoc.LocalName != "serviceStateTable") && (XMLDoc.EOF == false)) { if (XMLDoc.LocalName == "stateVariable") { evented = "no"; multicast = "no"; XMLDoc.MoveToAttribute("sendEvents"); if (XMLDoc.LocalName == "sendEvents") { evented = XMLDoc.GetAttribute("sendEvents"); } XMLDoc.MoveToAttribute("multicast"); if (XMLDoc.LocalName == "multicast") { multicast = XMLDoc.GetAttribute("multicast"); } XMLDoc.MoveToContent(); ParseStateVarXml(evented, multicast, XMLDoc); } if (!XMLDoc.IsStartElement()) { if (XMLDoc.LocalName != "serviceStateTable") { XMLDoc.Read(); XMLDoc.MoveToContent(); } } } } else { XMLDoc.Skip(); } } if (!XMLDoc.IsStartElement()) { XMLDoc.Read(); XMLDoc.MoveToContent(); } } // End of While // Add Associations foreach (UPnPAction A in this.Actions) { foreach (UPnPArgument G in A.Arguments) { if (G.RelatedStateVar == null) { OpenSource.Utilities.EventLogger.Log(this, System.Diagnostics.EventLogEntryType.FailureAudit, "About to throw an exception"); throw (new InvalidRelatedStateVariableException("Action: " + A.Name + " Arg: " + G.Name + " Contains invalid reference: " + G.StateVarName)); } G.RelatedStateVar.AddAssociation(A.Name, G.Name); } } } // End of If }
private void OnClick_LoadScript(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); dlg.AddExtension = true; dlg.DefaultExt = ".bql"; dlg.Title = "Specify the script file"; dlg.Filter = "Building Query Language|*.bql"; dlg.FilterIndex = 0; dlg.ValidateNames = true; dlg.FileOk += delegate(object s, System.ComponentModel.CancelEventArgs eArg) { Stream file = null; string dataFormat = "Text"; try { file = dlg.OpenFile(); TextRange txtRange = new TextRange(ScriptText.Document.ContentStart, ScriptText.Document.ContentEnd); if (txtRange.CanLoad(dataFormat)) { txtRange.Load(file, dataFormat); } this.Title = "BQL Console - " + System.IO.Path.GetFileName(dlg.FileName); } catch (Exception ex) { System.Windows.MessageBox.Show(string.Format("Loading script from file failed : {0}.", ex.Message), "Error", MessageBoxButton.OK, MessageBoxImage.Error); } finally { if (file != null) file.Close(); } }; dlg.ShowDialog(); ScriptText.RefreshKeyColour(); }
public PauseMenu(MinerGame game, MenuScene previous) : base(game, previous) { int start = -400; int pos = start; MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2 + pos, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), RESUME, (menu) => { this.GoBack(); })); pos += MENU_ITEM_HEIGHT + GAP; MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2 + pos, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), SAVE_GAME, (menu) => { using (FileStream fs = new FileStream("save1.xml", FileMode.Create)) { XmlSerializer xml = new XmlSerializer(typeof(GameState)); xml.Serialize(fs, this.Game.GameState); } })); pos += MENU_ITEM_HEIGHT + GAP; MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2 + pos, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), LOAD_GAME, (menu) => { System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog(); if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK) { try { this.Game.Content.Unload(); using (Stream stream = openFile.OpenFile()) { XmlSerializer xml = new XmlSerializer(typeof(GameState)); this.Game.GameState = (GameState)xml.Deserialize(stream); this.Game.GameState.Miner.Suit = new Nanosuit(); stream.Close(); } this.Game.GameState.Miner.game = this.Game; foreach (var item in this.Game.GameState.Enemies) { item.game = this.Game; } foreach (var item in this.Game.GameState.Bullets) { item.game = this.Game; } this.Game.Content.Load<SpriteFont>("general"); this.Game.Content.Load<Texture2D>(Kosmojopek.ASSET_NAME); this.Game.Content.Load<Texture2D>(Ufolowca.ASSET_NAME); this.Game.Content.Load<Texture2D>(WladcaLaserowejDzidy.ASSET_NAME); //this.Content.Load<Texture2D>(PoteznySultan.ASSET_NAME); this.Game.Content.Load<Texture2D>(Miner.ASSET_NAME); //this.Content.Load<Texture2D>(CosmicMatter.ASSET_NAME); this.Game.Content.Load<Texture2D>(DoubleJump.ASSET_NAME); this.Game.Content.Load<Texture2D>(Field.ASSET_NAME); this.Game.Content.Load<Texture2D>(Fuel.ASSET_NAME); this.Game.Content.Load<Texture2D>(Indestructibility.ASSET_NAME); this.Game.Content.Load<Texture2D>(Key.ASSET_NAME); this.Game.Content.Load<Texture2D>(KeyLocalizer.ASSET_NAME); this.Game.Content.Load<Texture2D>(Laser.ASSET_NAME); this.Game.Content.Load<Texture2D>(MoreEnemies.ASSET_NAME); this.Game.Content.Load<Texture2D>(SolidRock.ASSET_NAME); this.Game.Content.Load<Texture2D>(SpaceGate.ASSET_NAME); this.Game.Content.Load<Texture2D>(TitanRock.ASSET_NAME); this.Game.Content.Load<Texture2D>(Bullet.ASSET_NAME); this.Game.GameState.Miner.LoadContent(); foreach (var item in this.Game.GameState.Enemies) { item.LoadContent(); } foreach (var item in this.Game.GameState.Bullets) { item.LoadContent(); } foreach (var item in this.Game.GameState.Map.Fields) { foreach (var field in item) { field.game = this.Game; field.LoadContent(); } } GameScene newScene = new GameScene(this.Game) { OldKeyState = this.CurrentKeyState }; MenuManager.GetInstance().CurrentMenu = newScene; } catch (Exception exc) { System.Windows.Forms.MessageBox.Show(ERROR_READING_FILE + exc.Message); } } })); pos += MENU_ITEM_HEIGHT + GAP; MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2 + pos, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), INSTRUCTIONS, (menu) => { })); pos += MENU_ITEM_HEIGHT + GAP; MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2 + pos, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), SETTINGS, (menu) => { SettingsMenu newMenu = new SettingsMenu(this.Game, this) { OldKeyState = this.CurrentKeyState }; MenuManager.GetInstance().CurrentMenu = newMenu; })); pos += MENU_ITEM_HEIGHT + GAP; MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2 + pos, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), EXIT_MAIN_MENU, (menu) => { MainMenu newMenu = new MainMenu(this.Game) { OldKeyState = this.CurrentKeyState }; MenuManager.GetInstance().CurrentMenu = newMenu; })); pos += MENU_ITEM_HEIGHT + GAP; MenuItems.Add(new MenuItem(this, new Rectangle(Game.GraphicsDevice.Viewport.Width / 2 - MENU_ITEM_WIDTH / 2, Game.GraphicsDevice.Viewport.Height / 2 + pos, MENU_ITEM_WIDTH, MENU_ITEM_HEIGHT), EXIT_GAME, (menu) => { menu.Game.ExitGame(); })); MenuItems[currentlySelected].Selected = true; }
public void LoadMap() { System.Windows.Forms.OpenFileDialog openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); openFileDialog1.Filter = "RPG Map Files (.rpgmf)|*.rpgmf"; openFileDialog1.FilterIndex = 1; openFileDialog1.Multiselect = false; System.Windows.Forms.DialogResult userClickedOK = openFileDialog1.ShowDialog(); if (userClickedOK == System.Windows.Forms.DialogResult.OK) { // Open the selected file to read. System.IO.Stream fileStream = openFileDialog1.OpenFile(); using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream)) { // Read the first line from the file and write it the textbox. map.LoadMap(reader, openFileDialog1.FileName, toolmap); } fileStream.Close(); } }