public MainWindow() : base(Gtk.WindowType.Toplevel) { Build (); mySqlConnection.Open(); MySqlCommand mySqlCommand=mySqlConnection.CreateCommand(); mySqlCommand.CommandText= "select * from categoria"; MySqlDataReader mysqlDataReader= mySqlCommand.ExecuteReader(); int fieldcount=mysqlDataReader.FieldCount; creaColumnas(fieldcount,mysqlDataReader); ListStore listStore=new ListStore(creaTipos(fieldcount)); rellenar(fieldcount,listStore,mysqlDataReader); mysqlDataReader.Close(); removeAction.Sensitive=false; treeView.Model=listStore; TreeIter iter; treeView.Selection.Changed+=delegate{ bool isSelected=treeView.Selection.GetSelected(out iter); if(isSelected) removeAction.Sensitive=true; else removeAction.Sensitive=false; }; removeAction.Activated +=delegate{ string nombre=listStore.GetValue(iter,1).ToString(); MessageDialog md2 = new MessageDialog (this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo,"¿Seguro que quieres borrarlo? \n Borrar: "+nombre); ResponseType result = (ResponseType)md2.Run (); string op=listStore.GetValue(iter,0).ToString(); if (result == ResponseType.Yes){ MySqlCommand delete=mySqlConnection.CreateCommand(); delete.CommandText= "Delete from categoria where id="+op+""; delete.ExecuteNonQuery(); md2.Destroy(); for (int i=0;i<fieldcount;i++){//elimina columnas treeView.RemoveColumn(treeView.GetColumn(0)); } listStore.Clear();//vacia el modelo //volvemos a mostrar treview actualizado actualizar(mySqlCommand,listStore); } else{ md2.Destroy(); } }; }
protected void OnBtnGenerateClicked(object sender, EventArgs e) { try { BarcodeLib.Barcode codeBar = new BarcodeLib.Barcode (); codeBar.Alignment = BarcodeLib.AlignmentPositions.CENTER; codeBar.IncludeLabel = true; codeBar.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER; BarcodeLib.TYPE bCodeType = (BarcodeLib.TYPE)Enum.Parse (typeof(BarcodeLib.TYPE), cmbBarCodeType.ActiveText.ToString ()); System.Drawing.Image imgTmpCodeBar = codeBar.Encode (bCodeType, txtData.Text.Trim (), System.Drawing.Color.Black, System.Drawing.Color.White, 300, 300); MemoryStream memoryStream = new MemoryStream(); imgTmpCodeBar.Save(memoryStream, ImageFormat.Png); Gdk.Pixbuf pb = new Gdk.Pixbuf (memoryStream.ToArray()); imgCodeBar.Pixbuf = pb; } catch (Exception err) { MessageDialog dlg = new MessageDialog (this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, string.Format ("Ocurrió un error \n {0}", err.Message)); dlg.Run (); dlg.Destroy (); dlg.Dispose (); dlg = null; } }
protected void OnDeleteActionActivated(object sender, EventArgs e) { MessageDialog messageDialog = new MessageDialog ( this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, "¿Quieres eliminar el registro?" ); messageDialog.Title = Title; ResponseType response = (ResponseType) messageDialog.Run (); messageDialog.Destroy (); if (response != ResponseType.Yes) return; TreeIter treeIter; treeView.Selection.GetSelected (out treeIter); object id = listStore.GetValue (treeIter, 0); string deleteSql = string.Format ("delete from categoria where id={0}", id); IDbCommand dbCommand = dbConnection.CreateCommand (); dbCommand.CommandText = deleteSql; dbCommand.ExecuteNonQuery (); }
public MainWindow() : base(Gtk.WindowType.Toplevel) { this.Resize (600, 100); this.Title = "metafang"; _main = new VBox (); HBox title = new HBox (); title.PackStart (new Label ("Login to your Metasploit RPC instance to begin"), true, true, 0); _main.PackStart (title, true, true, 0); HBox loginInfo = new HBox (); loginInfo.PackStart (new Label ("Host:"), false, false, 20); Entry hostEntry = new Entry (); loginInfo.PackStart (hostEntry, false, false, 0); loginInfo.PackStart (new Label ("User:"******"Pass:"******"Login"); login.Clicked += (object sender, EventArgs e) => { try { //Console.WriteLine ("Creating session"); _session = new MetasploitSession (userEntry.Text, passEntry.Text, hostEntry.Text); //Console.WriteLine ("Creating manager and getting current list of payloads"); _manager = new MetasploitManager (_session); _payloads = _manager.GetPayloads (); BuildWorkspace (); } catch { MessageDialog md = new MessageDialog (this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, "Authentication failed. Please ensure your credentials and API URL are correct."); md.Run (); md.Destroy (); } }; HBox loginBox = new HBox (); loginBox.PackStart (login, false, false, 300); _main.PackStart (loginBox, true, true, 0); _main.ShowAll (); this.Add (_main); }
protected virtual void OnBtnokClicked(object sender, System.EventArgs e) { if(txturl.Text==String.Empty||txtname.Text==String.Empty) { MessageDialog md = new MessageDialog (this, DialogFlags.DestroyWithParent,MessageType.Error, ButtonsType.Close, "Fields must not be empty"); int result = md.Run (); md.Destroy(); } else { if(!txturl.Text.Contains("http://")) { MessageDialog md = new MessageDialog(this,DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, "Please Introduce a valid URL"); int result=md.Run(); md.Destroy(); } else { url=txturl.Text; path=txtpath.CurrentFolder+"/"+txtname.Text; Thread down = new Thread(downloadStart); down.Start(); } } }
protected virtual void OnBtnAnularClicked(object sender, System.EventArgs e) { MessageDialog Mensaje = null; string Tiquete = "", REF = "", c = ""; REF = txtEfectivo.Text; c = "UPDATE `cafeteria_transacciones` SET `precio_grabado`= 0.00, `cancelado` = 1 WHERE ID_ticket = '"+REF+"'"; if (MySQL.consultar(c)) { if( MySQL.Reader.RecordsAffected > 0 ) { Console.WriteLine("RA:" + MySQL.Reader.RecordsAffected); Tiquete += Imprimidor.Imprimir("CANCELACION CAFETERIA",1); Tiquete += Imprimidor.Imprimir("REF: "+REF,1); Imprimidor.Tiquete(Tiquete, "666"); Mensaje = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "Tiquete anulado"); Mensaje.Title="Éxito"; Mensaje.Run(); Mensaje.Destroy(); txtEfectivo.Text = ""; return; } } Mensaje = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "Tiquete no pudo ser anulado."); Mensaje.Title="Error"; Mensaje.Run(); Mensaje.Destroy(); txtEfectivo.GrabFocus(); return; }
protected void btnEnter_Click(object sender, EventArgs e) { TeenvioAPI api = new TeenvioAPI (txtUser.Text, txtPlan.Text, txtPassword.Text); try{ api.getServerVersion (); MainWindow win = new MainWindow(); win.Show(); win.setAPI(api); this.Destroy(); }catch(TeenvioException ex){ MessageDialog msg = new MessageDialog (this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, ex.Message); msg.Title = "Error"; ResponseType response = (ResponseType) msg.Run(); if (response == ResponseType.Close || response == ResponseType.DeleteEvent) { msg.Destroy(); } }catch(Exception ex){ MessageDialog msg = new MessageDialog (this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, ex.Message); msg.Title = "Error"; ResponseType response = (ResponseType) msg.Run(); if (response == ResponseType.Close || response == ResponseType.DeleteEvent) { msg.Destroy(); } } }
protected void OnButtonLoginClicked(object sender, EventArgs e) { try{ string connectionString = "Server=localhost;" + "Database=dbprueba;" + "User ID=" + entryUser.Text.ToString () + ";" + "Password="******"\t\tConnection Error\t\t\nCannot connect to database"); messageDialog.Title = "SQL DataBase Error"; messageDialog.Run (); messageDialog.Destroy (); entryUser.Text = ""; entryPwd.Text = ""; } catch{ Console.WriteLine ("\nError 404 Not Found"); Application.Quit (); } }
protected void clicked(object sender, EventArgs e) { double pes; double cam; double res; if (double.TryParse (pesos.Text, out pes) && double.TryParse (camb.Text, out cam)) { if(pes == 0 || cam == 0){ MessageDialog cero; cero = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Conversion invalida entre cero"); cero.Run(); cero.Destroy(); } else{ res = pes / cam; dol.Text = Convert.ToString (res); } } else if(pesos.Text == "" || camb.Text == ""){ MessageDialog d; d = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Campos vacios, ingrese numeros"); d.Run(); d.Destroy(); }else { MessageDialog dia; dia = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Ingrese solo numeros"); dia.Run(); dia.Destroy(); } }
protected virtual void OnExecButtonClicked(object sender, System.EventArgs e) { resultString = new StringBuilder(); try{ parser.Execute(); // Parse selected file } catch(Exception exc){ string errorText = "Ouch! Something bad happened and an exception" + " was thrown. The error message was: " + Environment.NewLine + exc.Message + Environment.NewLine + Environment.NewLine + "Make sure your input file is formatted correctly and try again."; MessageDialog md = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, errorText); ResponseType res = (ResponseType)md.Run(); if(res == ResponseType.Ok){ md.Destroy(); Application.Quit(); } } // Append each line foreach(string str in parser.GetResults()){ resultString.Append(str + Environment.NewLine); } resultString.Append(Environment.NewLine); // Enable View and Save buttons TextView.Buffer.Text = "File parsed. Press View to view results or Save to save results."; //TextView.Buffer.Text = "File parsed. Press Save to save the results."; ViewButton.Sensitive = true; SaveButton.Sensitive = true; }
protected void OnButton1Clicked(object sender, EventArgs e) { int aciertos = 0; if (this.radb1.Active) { aciertos += 1; } if (this.chPortu.Active) { aciertos += 1; } if (this.chReino.Active) { aciertos += 1; } if (this.chMace.Active) { aciertos += 1; } if (this.spinb1.Text == "31") { aciertos += 1; } if (this.calendar1.GetDate ().ToShortDateString () == "07/05/1945") { aciertos +=1; } MessageDialog ve=new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "Código: " + this.entry1.Text + "\nNombre: " + this.entry2.Text + "\n" + Convert.ToString(aciertos) + " aciertos."); ve.Run(); ve.Destroy(); aciertos=0; }
//LOGIN protected void OnLoginButtonClicked(object sender, EventArgs e) { try{ string connectionString = "Server=localhost;" + "Database=dbprueba;" + "User ID=" + userEntry.Text.ToString () + ";" + "Password="******"\t\tConnection Error\t\t\nCannot connect to database"); msgDialog.Title = "SQL DataBase Error"; msgDialog.Run (); msgDialog.Destroy (); pwdEntry.Text = ""; } catch{ Console.WriteLine ("\nError 404 Not Found"); Application.Quit (); } }
public MainWindow() : base(Gtk.WindowType.Toplevel) { try { CheckForUpdatesProgress cfup = new CheckForUpdatesProgress(Assembly.GetExecutingAssembly().GetName().Version); cfup.Show(); if (cfup.CheckForUpdates() == false) cfup.Destroy(); } catch { MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Communication could not be established to our servers: you must be online to use the LunaLua Module Manager.\n\nPress ok so we can self destruct."); md.Icon = Image.LoadFromResource("Gtktester.Icons.PNG.256.png").Pixbuf; md.WindowPosition = WindowPosition.Center; md.Run(); md.Destroy(); this.Destroy(); Environment.Exit(-5); } Build (); if (Program.ProgramSettings.StartMaximized) this.Maximize(); this.hpaned2.Position = 170; this.hpaned1.Position = 170; OnWindowLoad(); this.notebook1.CurrentPage = 0; }
private void ShowError(string errorMessage) { MessageDialog errorMsg = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, errorMessage); errorMsg.Title = "Error"; if ((ResponseType) errorMsg.Run() == ResponseType.Close) { errorMsg.Destroy(); } }
protected void click(object sender, System.EventArgs e) { //throw new System.NotImplementedException (); //label1.Text="Hola Mundo"; MessageDialog dialogo; dialogo = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "MENSAJE DE ERROR"); dialogo.Run(); dialogo.Destroy(); }
public void StartGame(Config config) { game = new Game (this.createBoard (config.Width, config.Height)); game.GameWon += delegate(object sender, EventArgs e) { MessageDialog dialog = new MessageDialog ( this, DialogFlags.Modal, MessageType.Info, ButtonsType.None, "Úroveň dokončena! Abyste zvládli víc nepřátel, dostanete další život." ); dialog.AddButton ("Další kolo", ResponseType.Accept); dialog.AddButton ("Konec hry", ResponseType.Cancel); dialog.Response += delegate(object o, ResponseArgs args) { if (args.ResponseId == ResponseType.Accept) { NextLevel (config); } else { Application.Quit (); } }; dialog.Run (); dialog.Destroy (); }; game.GameLost += delegate(object sender, EventArgs e) { MessageDialog dialog = new MessageDialog ( this, DialogFlags.Modal, MessageType.Info, ButtonsType.None, "Konec hry" ); dialog.AddButton ("Nová hra", ResponseType.Accept); dialog.AddButton ("Konec", ResponseType.Close); dialog.Response += delegate(object o, ResponseArgs args) { if (args.ResponseId == ResponseType.Accept) { MainClass.ShowLauncher (); this.Destroy (); } else { Application.Quit (); } }; dialog.Run (); dialog.Destroy (); }; game.FilledAreaChanged += delegate(object sender, int value) { fillCounter.Text = String.Format ("Zaplněno: {0}%", value); }; game.LivesChanged += delegate(object sender, int value) { lifeCounter.Text = String.Format ("Životy: {0}", value); }; game.RemainingTimeChanged += delegate(object sender, int value) { remainingTimeCounter.Text = string.Format ("Zbývající čas: {0} sekund", value); }; game.Start (config); level = 1; updateLevelCounter (); }
protected void clicou(object sender, EventArgs e) { //throw new NotImplementedException (); String texto = txtInput.Text; MessageDialog dialog = new MessageDialog(this, DialogFlags.Modal, MessageType.Other, ButtonsType.YesNo, texto); ResponseType tp = (Gtk.ResponseType)dialog.Run(); //dialog.Run (); dialog.Destroy(); }
protected void ErrorAlert(string message) { var md = new MessageDialog (this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Ok, message); md.Run (); md.Destroy (); }
/// <summary> /// Raises the login button clicked event. /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='e'> /// E. /// </param> protected void OnLoginButtonClicked(object sender, EventArgs e) { MessageDialog md = new MessageDialog (this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, "Visit http://splunk.net"); md.Run (); md.Destroy(); }
protected void FinishedAlert() { var md = new MessageDialog (this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, "Scraping finished!"); md.Run (); md.Destroy (); }
protected virtual void MesAlterado(object sender, System.EventArgs e) { var mes = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName (this.calendar1.Date.Month); var md = new MessageDialog (null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, mes); md.Run (); md.Destroy(); }
public static void ShowMessage(String messageString) { Window parentWindow = new Window ("提示"); MessageDialog messageDialog = new MessageDialog (parentWindow, DialogFlags.Modal, MessageType.Info, ButtonsType.Close, messageString); messageDialog.Run (); messageDialog.Destroy (); parentWindow.Dispose (); }
protected void OnButton17Clicked(object sender, System.EventArgs e) { dlgDatabaseConfiguration d = new dlgDatabaseConfiguration(); d.Response += delegate { MessageDialog md = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Close, "Test succeeded"); md.Run(); md.Destroy(); }; d.Run(); d.Destroy(); }
private void DisplayError(String errorMessage) { MessageDialog errorDialog = new MessageDialog( this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, errorMessage ); errorDialog.Run(); errorDialog.Destroy(); }
// Muestra un modal de confirmacion y devuelve true si la respuesta del usuario es yes o false si ha sido otra public bool confirm(String text){ MessageDialog messageDialog = new MessageDialog( this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, text ); messageDialog.Title = "¿Estás seguro?"; ResponseType response = (ResponseType)messageDialog.Run (); messageDialog.Destroy (); return response == ResponseType.Yes; }
// dialogo confirmar eliminar (recibe ventana) public static bool ConfirmDelete(Window window) { MessageDialog messageDialog = new MessageDialog ( window, DialogFlags.DestroyWithParent, MessageType.Question, ButtonsType.YesNo, "¿Quieres eliminar el elemento seleccionado?" ); messageDialog.Title = window.Title; ResponseType response = (ResponseType)messageDialog.Run(); messageDialog.Destroy(); return response == ResponseType.Yes; }
public MainWindow() : base(Gtk.WindowType.Toplevel) { Build (); setupui (); //Check for Launcher Updates if (MainClass.CheckForUpdates () == true) { MessageDialog md = new MessageDialog (this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, "A new update has been released. We will install it for you. The launcher will close. When you run it again, you will be on the updated version." + Environment.NewLine + Environment.NewLine + "Version: " + MainClass.NewVersion + " '" + MainClass.NewCodename + "' "); md.Run (); md.Destroy (); MainClass.RunUpdate (); } }
protected virtual void OnAboutClicked(object sender, System.EventArgs e) { string aboutText = "ORU File Parser aka The Anders Program " + "v " + asm.GetName().Version.ToString() + Environment.NewLine + "(C) Anders Lindén 2008 - 2009. Licenced to Örebro University" + Environment.NewLine + "For questions and support, send a mail to: " + "*****@*****.**"; MessageDialog md = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, aboutText); ResponseType res = (ResponseType)md.Run(); if(res == ResponseType.Ok) md.Destroy(); }
protected void OnBtnMasterClicked(object sender, EventArgs e) { MessageDialog md = new MessageDialog (this, DialogFlags.DestroyWithParent, MessageType.Question, ButtonsType.YesNo, "Power Everything Off?"); var myResponse = md.Run (); md.Destroy (); if (Convert.ToInt16 (myResponse) == -8) { tbPump.Active = false; tbPump.Label = "Turn On"; tbAux.Active = false; tbAux.Label = "Turn On"; tbHeater.Active = false; tbHeater.Label = "Turn On"; tbLight.Active = false; tbLight.Label = "Turn On"; } }
private void DoUpdateEvents() { if (CheckIfCurExe()) { DownloadUpdate(); } else { MessageDialog md = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "ERROR:\nCould not find your LuaModuleManager.exe."); md.Run(); md.Destroy(); this.Destroy(); Application.Quit(); Environment.Exit(-1); } }
protected void OnButton40Clicked(object sender, EventArgs e) { //TODO -- Done this function, TODO for serveraction, clientaction and database code page. // 1. Query all of the GPU resource of this agent // 2. If any of these gpu resource has been assigned. // 3. a) if no, remove record of agentinfo, fabricinfo, resourceinfo by agentid // b) if yes, promot a message to let customer know need to remove all of the assignment before delete the agent. TreeIter iter; TreeModel model; TreeSelection selection = treeview1.Selection; if (!selection.GetSelected(out model, out iter)) { MessageDialog msg = new MessageDialog(null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "No Agent Selected"); msg.Response += (o, args) => { if (args.ResponseId == ResponseType.Ok) { msg.Destroy(); } }; msg.ShowAll(); } else { TcpClient client = new TcpClient(ServerIP, Int32.Parse(TcpPort)); object content = model.GetValue(iter, 1).ToString(); Type contentType = content.GetType(); Protocol checkResShareStatus = new Protocol(client, ConstValues.PROTOCOL_FN_CHECK_RESOURCE_IF_ASSIGNED, contentType, content); checkResShareStatus.Start(); client.Close(); if ((String)checkResShareStatus.ResultObject == "True") { //has some gpu resource already assigned to other clients MessageDialog msg = new MessageDialog(null, DialogFlags.Modal, MessageType.Warning, ButtonsType.Ok, "Some of GPU resource have been assigned already.\nPlease revoke these assignation before remove this agent."); msg.Response += (o, args) => { if (args.ResponseId == ResponseType.Ok) { msg.Destroy(); } }; msg.ShowAll(); } else { // since there is no assignation existed, this agent could be remove now. TcpClient client2 = new TcpClient(ServerIP, Int32.Parse(TcpPort)); object content2 = model.GetValue(iter, 1).ToString(); Type contentType2 = content2.GetType(); Protocol removeAgent = new Protocol(client2, ConstValues.PROTOCOL_FN_REMOVE_AGENT, contentType2, content2); removeAgent.Start(); client2.Close(); if ((String)removeAgent.ReceivedContent == "True") { MessageDialog msg = new MessageDialog(null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "Agent has been removed"); msg.Response += (o, args) => { if (args.ResponseId == ResponseType.Ok) { msg.Destroy(); } }; msg.ShowAll(); } else { MessageDialog msg = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Removing Agent failed. \nTry again later."); msg.Response += (o, args) => { if (args.ResponseId == ResponseType.Ok) { msg.Destroy(); } }; msg.ShowAll(); } } } }
protected void OnPagesSwitchPage(object o, Gtk.SwitchPageArgs args) { if (Pages.CurrentPage == (int)Page.Brick) { lastPage = Page.Brick; } if (Pages.CurrentPage != (int)Page.Brick) { } if (Pages.CurrentPage == (int)Page.Sensor) //Sensor page { lastPage = Page.Sensor; if (brick != null) { if (sensorLogCheckbutton.Active && pollTimer.Enabled) //log for file { startPollTimer = false; Gtk.Application.Invoke(delegate { SetSensorSelection(false); SetPollSensorUi(false, "Stop", true, false); }); } else { if (!startPollTimer && !enableKeyboardInput.Active) { pollTimer.Enabled = false; startPollTimer = false; Gtk.Application.Invoke(delegate { SetSensorSelection(true); SetPollSensorUi(true, "Poll", true, true); }); } if (startPollTimer && !enableKeyboardInput.Active) { pollTimer.Enabled = true; startPollTimer = false; Gtk.Application.Invoke(delegate { SetSensorSelection(false); SetPollSensorUi(false, "Stop", true, true); }); } if (startPollTimer && enableKeyboardInput.Active) //ignore that poll sensor was set { pollTimer.Enabled = false; startPollTimer = false; Gtk.Application.Invoke(delegate { SetSensorSelection(true); SetPollSensorUi(false, "Poll", false, false); }); } if (!startPollTimer && enableKeyboardInput.Active) { pollTimer.Enabled = false; startPollTimer = false; Gtk.Application.Invoke(delegate { SetSensorSelection(true); SetPollSensorUi(false, "Poll", false, false); }); } } } } if (Pages.CurrentPage != (int)Page.Sensor) //not sensor page { if (pollTimer.Enabled && informOnPoll && sensorLogCheckbutton.Active) { Gtk.Application.Invoke(delegate { MessageDialog md = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Close, "\nPlease note that communicating with the NXT while polling and saving sensor values might interfere with sensor readings. Certain options has been disabled"); md.Icon = global::Gdk.Pixbuf.LoadFromResource(MessageDialogIconName); md.WindowPosition = Gtk.WindowPosition.CenterOnParent; md.Run(); md.Destroy(); }); informOnPoll = false; } if (pollTimer.Enabled && !sensorLogCheckbutton.Active) { pollTimer.Enabled = false; startPollTimer = true; } } if (Pages.CurrentPage == (int)Page.Motor) //Motor page { lastPage = Page.Motor; if (pollTimer.Enabled && sensorLogCheckbutton.Active || enableKeyboardInput.Active) //logging sensor values and saving to file or keyboad to move vehicle { DisableTachoUserInput(); } else { if (brick != null && brick.Connection.IsConnected) { EnableMotorTachoTimers(); } } } if (Pages.CurrentPage != (int)Page.Motor) //Not motor page { EnableTachoUserInput(); DisableMotorTachoTimers(); } if (Pages.CurrentPage == (int)Page.File) //File page { lastPage = Page.File; if (pollTimer.Enabled && sensorLogCheckbutton.Active) { DisableFileUserInput(); } else { EnableFileUserInput(); if (brick != null && brick.Connection.IsConnected) { if (!isFileListLoaded) { LoadFileList(); } } } } if (Pages.CurrentPage != (int)Page.File) //Not file page //fileNodeStore.Clear(); { if (lastPage == Page.File) { //no settings to save } } if (Pages.CurrentPage == (int)Page.Keyboard) //keyboard page { lastPage = Page.Keyboard; if (pollTimer.Enabled && sensorLogCheckbutton.Active) { DisableVehicleUserInput(); } else { if (!enableKeyboardInput.Active) { EnableVehicleUserInput(); } } } if (Pages.CurrentPage != (int)Page.Keyboard) //Not keyboard page { } if (Pages.CurrentPage == (int)Page.Mailbox) //Mailbox page { if (brick != null && brick.Connection.IsConnected) { EnableReadMessage(!isConnectedViaUSB()); } } if (Pages.CurrentPage != (int)Page.Mailbox) //Not Mailbox page { } if (Pages.CurrentPage == (int)Page.Tunnel) //Tunnel page { } if (Pages.CurrentPage != (int)Page.Tunnel) //Not Tunnel page { } }
void UpdateAssignView(TreeModel model, TreeIter iter) { if (selectedInterface != string.Empty && selectedInterface != "") { // if exclusive flag is on, please check if the card has been assigned String clientIp = combobox2.ActiveText.Split(':') [0]; String clientId = combobox2.ActiveText.Split(':') [1]; if (exclusiveFlag) { TcpClient client = new TcpClient(ServerIp, Int32.Parse(TcpPort)); object content = model.GetValue(iter, 3).ToString(); //GPU UUID Type contentType = content.GetType(); Protocol verifyExclusiveStatus = new Protocol(client, ConstValues.PROTOCOL_FN_VERIFY_GPU_EXCLUSIVE, contentType, content); verifyExclusiveStatus.Start(); if ((String)verifyExclusiveStatus.ResultObject == "True") { // allow to setup the selected gpu card to exclusive mode // a. save related information to a temploary table Dictionary <String, String> assignEntry = new Dictionary <string, string> (); assignEntry.Add("action", "add"); assignEntry.Add("resource_ip", selectedInterface); assignEntry.Add("gpu_uuid", model.GetValue(iter, 3).ToString()); assignEntry.Add("assign_type", exclusiveFlag ? "Exclusive" : "Share"); assignEntry.Add("agent_id", clientId); AssignmentChange.Add(assignEntry); // b. a record will append into current treeview gpuAssignView.AppendValues(selectedInterface, model.GetValue(iter, 2).ToString(), model.GetValue(iter, 3).ToString(), model.GetValue(iter, 4).ToString(), selectedSpeed, exclusiveFlag ? "Exclusive" : "Share"); treeview6.Model = gpuAssignView; } else { // not allow to to set this gpu card to exclusive mode. exit function, and give a customer a message box. MessageDialog msg = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "This GPU has been assigned to other clinet.\nIt can't be assigned as EXCLUSIVE mode.\nPlease remove other assignment and try again."); msg.Response += (o, args) => { if (args.ResponseId == ResponseType.Ok) { msg.Destroy(); } }; msg.ShowAll(); } } else { Dictionary <String, String> assignEntry = new Dictionary <string, string> (); assignEntry.Add("action", "add"); assignEntry.Add("resource_ip", selectedInterface); assignEntry.Add("gpu_uuid", model.GetValue(iter, 3).ToString()); assignEntry.Add("assign_type", exclusiveFlag ? "Exclusive" : "Share"); assignEntry.Add("agent_id", clientId); AssignmentChange.Add(assignEntry); // b. a record will append into current treeview gpuAssignView.AppendValues(selectedInterface, model.GetValue(iter, 2).ToString(), model.GetValue(iter, 3).ToString(), model.GetValue(iter, 4).ToString(), selectedSpeed, exclusiveFlag ? "Exclusive" : "Share"); treeview6.Model = gpuAssignView; } } else { MessageDialog msg = new MessageDialog(null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "No GPU Source Interface Chosen"); msg.Response += (o, args) => { if (args.ResponseId == ResponseType.Ok) { msg.Destroy(); } }; msg.ShowAll(); } selectedSpeed = string.Empty; selectedInterface = string.Empty; exclusiveFlag = false; }
void ejecutar_consulta_reporte(PrintContext context) { //string mesage_1 = "NO Tiene Comprobante de Servicio"; //string mesage_2 = "NO Tiene Comprobante de PAGO o ABONO"; //string mesage_3 = "NO Tiene Comprobante de PAGARE"; //string mesage_4 = "NO Tiene PASE QX/URGENCIA"; Cairo.Context cr = context.CairoContext; Pango.Layout layout = context.CreatePangoLayout(); comienzo_linea = 85; NpgsqlConnection conexion; conexion = new NpgsqlConnection(connectionString + nombrebd); // Verifica que la base de datos este conectada try{ imprime_encabezado(cr, layout); fontSize = 8.0; layout = context.CreatePangoLayout(); desc.Size = (int)(fontSize * pangoScale); layout.FontDescription = desc; conexion.Open(); NpgsqlCommand comando; comando = conexion.CreateCommand(); int folioservicio = 0; string query_fechas = " AND to_char(osiris_erp_cobros_enca.fechahora_creacion,'yyyy-MM-dd') >= '" + entry_ano1.Text + "-" + entry_mes1.Text + "-" + entry_dia1.Text + "' " + " AND to_char(osiris_erp_cobros_enca.fechahora_creacion,'yyyy-MM-dd') <= '" + entry_ano2.Text + "-" + entry_mes2.Text + "-" + entry_dia2.Text + "' "; comando.CommandText = "SELECT osiris_erp_cobros_enca.folio_de_servicio,osiris_erp_cobros_enca.pid_paciente AS pidpaciente, " + "osiris_his_paciente.nombre1_paciente || ' ' || osiris_his_paciente.nombre2_paciente || ' ' || osiris_his_paciente.apellido_paterno_paciente || ' ' || osiris_his_paciente.apellido_materno_paciente AS nombre_completo," + "osiris_erp_cobros_enca.fechahora_creacion " + "FROM osiris_erp_cobros_enca,osiris_his_paciente " + "WHERE osiris_erp_cobros_enca.pid_paciente = osiris_his_paciente.pid_paciente " + "AND cancelado = 'false' " + query_fechas + " ORDER BY osiris_erp_cobros_enca.folio_de_servicio;"; Console.WriteLine(comando.CommandText.ToString()); NpgsqlDataReader lector = comando.ExecuteReader(); while (lector.Read()) { folioservicio = (int)lector["folio_de_servicio"]; //Console.WriteLine(folioservicio.ToString()); if ((string)classpublic.lee_registro_de_tabla("osiris_erp_comprobante_servicio", "folio_de_servicio", "WHERE folio_de_servicio = '" + folioservicio.ToString().Trim() + "'", "folio_de_servicio", "int") == "") { //Console.WriteLine(folioservicio.ToString().Trim()+" NO Tiene Comprobante de Servicio "); if ((string)classpublic.lee_registro_de_tabla("osiris_erp_abonos", "folio_de_servicio", "WHERE folio_de_servicio = '" + folioservicio.ToString().Trim() + "' AND honorario_medico = 'false' ", "folio_de_servicio", "int") == "") { //Console.WriteLine(folioservicio.ToString().Trim()+" NO Tiene Comprobante de PAGO o ABONO "); if ((string)classpublic.lee_registro_de_tabla("osiris_erp_comprobante_pagare", "folio_de_servicio", "WHERE folio_de_servicio = '" + folioservicio.ToString().Trim() + "' ", "folio_de_servicio", "int") == "") { //Console.WriteLine(folioservicio.ToString().Trim()+" NO Tiene Comprobante de PAGARE "); if ((string)classpublic.lee_registro_de_tabla("osiris_erp_pases_qxurg", "folio_de_servicio", "WHERE folio_de_servicio = '" + folioservicio.ToString().Trim() + "' ", "folio_de_servicio", "int") == "") { //Console.WriteLine(folioservicio.ToString().Trim()+" NO Tiene PASE QX/URGENCIA "); cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText("FECHA :" + (string)lector["fechahora_creacion"].ToString() + "N° Atencion :" + folioservicio.ToString() + " Expediente: " + (string)lector["pidpaciente"].ToString() + " Paciente: " + (string)lector["nombre_completo"].ToString()); Pango.CairoHelper.ShowLayout(cr, layout); comienzo_linea += separacion_linea; salto_de_pagina(cr, layout); fontSize = 8.0; layout = context.CreatePangoLayout(); desc.Size = (int)(fontSize * pangoScale); layout.FontDescription = desc; } } } } } }catch (NpgsqlException ex) { MessageDialog msgBoxError = new MessageDialog(MyWinError, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, "PostgresSQL error: {0}", ex.Message); msgBoxError.Run(); msgBoxError.Destroy(); } conexion.Close(); }
bool CreateLogin() { logger.Info("Создание учетной записи на сервере..."); try { //Проверка существует ли логин string sql = "SELECT COUNT(*) FROM users WHERE login = @login"; QSMain.CheckConnectionAlive(); MySqlCommand cmd = new MySqlCommand(sql, QSMain.connectionDB); cmd.Parameters.AddWithValue("@login", entryLogin.Text); if (Convert.ToInt32(cmd.ExecuteScalar()) > 0) { string Message = "Пользователь с логином " + entryLogin.Text + " уже существует в базе. " + "Создание второго пользователя с таким же логином невозможно."; MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Ok, Message); md.Run(); md.Destroy(); return(false); } sql = "SELECT COUNT(*) from mysql.user WHERE USER = @login"; cmd = new MySqlCommand(sql, QSMain.connectionDB); cmd.Parameters.AddWithValue("@login", entryLogin.Text); try { if (Convert.ToInt32(cmd.ExecuteScalar()) > 0) { string Message = "Пользователь с логином " + entryLogin.Text + " уже существует на сервере. " + "Если он использовался для доступа к другим базам, может возникнуть путаница. " + "Использовать этот логин?"; MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.YesNo, Message); bool result = (ResponseType)md.Run() == ResponseType.Yes; md.Destroy(); return(result); } } catch (MySqlException ex) { if (ex.Number == 1045) { logger.Warn(ex, "Нет доступа к таблице пользователей, пробую создать пользователя в слепую."); } else { logger.Error(ex, "Ошибка чтения таблицы пользователей!"); QSMain.ErrorMessage(this, ex); return(false); } } //Создание пользователя. sql = "CREATE USER @login IDENTIFIED BY @password"; cmd = new MySqlCommand(sql, QSMain.connectionDB); cmd.Parameters.AddWithValue("@login", entryLogin.Text); cmd.Parameters.AddWithValue("@password", entryPassword.Text); cmd.ExecuteNonQuery(); cmd.CommandText = "CREATE USER @login @'localhost' IDENTIFIED BY @password"; cmd.ExecuteNonQuery(); logger.Info("Ok"); return(true); } catch (Exception ex) { logger.Error(ex, "Ошибка создания пользователя!"); QSMain.ErrorMessage(this, ex); return(false); } }
void ejecutar_consulta_reporte(PrintContext context) { decimal total_inventario = 0; int idgrupoproducto = 0; string descriopciongrupoproducto = ""; decimal totales_x_grupo = 0; //Array stringArray = Array.CreateInstance(typeof(String), 20, 2); //stringArray.SetValue("Mahesh", 0,0); Cairo.Context cr = context.CairoContext; Pango.Layout layout = context.CreatePangoLayout(); imprime_encabezado(cr, layout); Pango.FontDescription desc = Pango.FontDescription.FromString("Sans"); // cr.Rotate(90) Imprimir Orizontalmente rota la hoja cambian las posiciones de las lineas y columna fontSize = 8.0; layout = null; layout = context.CreatePangoLayout(); desc.Size = (int)(fontSize * pangoScale); layout.FontDescription = desc; NpgsqlConnection conexion; conexion = new NpgsqlConnection(connectionString + nombrebd); // Verifica que la base de datos este conectada try{ conexion.Open(); NpgsqlCommand comando; comando = conexion.CreateCommand(); Console.WriteLine(query_consulta); comando.CommandText = query_consulta; NpgsqlDataReader lector = comando.ExecuteReader(); if (lector.Read()) { idgrupoproducto = int.Parse(lector["idgrupoproducto"].ToString()); descriopciongrupoproducto = lector["descripcion_grupo_producto"].ToString().Trim(); comienzo_linea = 80; fontSize = 7.0; layout = null; layout = context.CreatePangoLayout(); desc.Size = (int)(fontSize * pangoScale); layout.FontDescription = desc; layout.FontDescription.Weight = Weight.Bold; // Letra negrita cr.MoveTo(65 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["descripcion_grupo_producto"].ToString().Trim()); Pango.CairoHelper.ShowLayout(cr, layout); layout.FontDescription.Weight = Weight.Normal; comienzo_linea += separacion_linea; cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["idproducto"].ToString().Trim()); Pango.CairoHelper.ShowLayout(cr, layout); if (lector["descripcion_producto"].ToString().Length > 65) { cr.MoveTo(65 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["descripcion_producto"].ToString().Trim().Substring(0, 65)); Pango.CairoHelper.ShowLayout(cr, layout); } else { cr.MoveTo(65 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["descripcion_producto"].ToString().Trim()); Pango.CairoHelper.ShowLayout(cr, layout); } cr.MoveTo(340 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["stock"].ToString()); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(420 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", decimal.Parse(lector["costoproducto"].ToString()))); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(460 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["embalaje"].ToString()); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(540 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", decimal.Parse(lector["costoproductounitario"].ToString().Trim()))); Pango.CairoHelper.ShowLayout(cr, layout); if (tipo_reporte == "inventario_fisico") { cr.MoveTo(600 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:F}", decimal.Parse(lector["porcentageganancia"].ToString().Trim()))); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(680 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", decimal.Parse(lector["costoproductounitario"].ToString().Trim()) * decimal.Parse(lector["stock"].ToString()))); Pango.CairoHelper.ShowLayout(cr, layout); } if (tipo_reporte == "cargos_x_fecha") { cr.MoveTo(600 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", decimal.Parse(lector["costoproductounitario"].ToString().Trim()) * decimal.Parse(lector["stock"].ToString()))); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(600 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["stock"].ToString()); Pango.CairoHelper.ShowLayout(cr, layout); } if (tipo_reporte == "inventario_actual") { cr.MoveTo(600 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", decimal.Parse(lector["costoproductounitario"].ToString().Trim()) * decimal.Parse(lector["stock"].ToString()))); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(680 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["stock"].ToString()); Pango.CairoHelper.ShowLayout(cr, layout); } totales_x_grupo += decimal.Parse(lector["costoproductounitario"].ToString().Trim()) * decimal.Parse(lector["stock"].ToString()); total_inventario += decimal.Parse(lector["costoproductounitario"].ToString().Trim()) * decimal.Parse(lector["stock"].ToString()); comienzo_linea += separacion_linea; while (lector.Read()) { if (idgrupoproducto != int.Parse(lector["idgrupoproducto"].ToString())) { desc.Size = (int)(fontSize * pangoScale); layout.FontDescription = desc; layout.FontDescription.Weight = Weight.Bold; // Letra negrita if (tipo_reporte == "inventario_fisico") { cr.MoveTo(400 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText("TOTAL " + descriopciongrupoproducto); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(680 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", totales_x_grupo)); Pango.CairoHelper.ShowLayout(cr, layout); } if (tipo_reporte == "cargos_x_fecha") { cr.MoveTo(400 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText("TOTAL " + descriopciongrupoproducto); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(600 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", totales_x_grupo)); Pango.CairoHelper.ShowLayout(cr, layout); //cr.MoveTo(680*escala_en_linux_windows, comienzo_linea*escala_en_linux_windows); layout.SetText(string.Format("{0:C}",totales_x_grupo)); Pango.CairoHelper.ShowLayout (cr, layout); } if (tipo_reporte == "inventario_actual") { cr.MoveTo(400 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText("TOTAL " + descriopciongrupoproducto); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(680 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", totales_x_grupo)); Pango.CairoHelper.ShowLayout(cr, layout); } comienzo_linea = 531; salto_de_pagina(cr, layout); desc.Size = (int)(fontSize * pangoScale); layout.FontDescription = desc; layout.FontDescription.Weight = Weight.Bold; // Letra negrita cr.MoveTo(65 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["descripcion_grupo_producto"].ToString().Trim()); Pango.CairoHelper.ShowLayout(cr, layout); comienzo_linea += separacion_linea; salto_de_pagina(cr, layout); idgrupoproducto = int.Parse(lector["idgrupoproducto"].ToString()); descriopciongrupoproducto = lector["descripcion_grupo_producto"].ToString().Trim(); totales_x_grupo = 0; desc.Size = (int)(fontSize * pangoScale); layout.FontDescription = desc; layout.FontDescription.Weight = Weight.Normal; // Letra normal } cr.MoveTo(05 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["idproducto"].ToString().Trim()); Pango.CairoHelper.ShowLayout(cr, layout); if (lector["descripcion_producto"].ToString().Length > 65) { cr.MoveTo(65 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["descripcion_producto"].ToString().Trim().Substring(0, 65)); Pango.CairoHelper.ShowLayout(cr, layout); } else { cr.MoveTo(65 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["descripcion_producto"].ToString().Trim()); Pango.CairoHelper.ShowLayout(cr, layout); } cr.MoveTo(340 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["stock"].ToString()); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(420 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", decimal.Parse(lector["costoproducto"].ToString()))); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(460 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["embalaje"].ToString()); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(540 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", decimal.Parse(lector["costoproductounitario"].ToString().Trim()))); Pango.CairoHelper.ShowLayout(cr, layout); if (tipo_reporte == "inventario_fisico") { cr.MoveTo(600 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:F}", decimal.Parse(lector["porcentageganancia"].ToString().Trim()))); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(680 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", decimal.Parse(lector["costoproductounitario"].ToString().Trim()) * decimal.Parse(lector["stock"].ToString()))); Pango.CairoHelper.ShowLayout(cr, layout); } if (tipo_reporte == "cargos_x_fecha") { cr.MoveTo(600 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", decimal.Parse(lector["costoproductounitario"].ToString().Trim()) * decimal.Parse(lector["stock"].ToString()))); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(680 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(lector["stock"].ToString()); Pango.CairoHelper.ShowLayout(cr, layout); } if (tipo_reporte == "inventario_actual") { cr.MoveTo(600 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:F}", decimal.Parse(lector["porcentageganancia"].ToString().Trim()))); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(680 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", decimal.Parse(lector["costoproductounitario"].ToString().Trim()) * decimal.Parse(lector["stock"].ToString()))); Pango.CairoHelper.ShowLayout(cr, layout); } totales_x_grupo += decimal.Parse(lector["costoproductounitario"].ToString().Trim()) * decimal.Parse(lector["stock"].ToString()); total_inventario += decimal.Parse(lector["costoproductounitario"].ToString().Trim()) * decimal.Parse(lector["stock"].ToString()); comienzo_linea += separacion_linea; salto_de_pagina(cr, layout); } desc.Size = (int)(fontSize * pangoScale); layout.FontDescription = desc; layout.FontDescription.Weight = Weight.Bold; // Letra negrita if (tipo_reporte == "inventario_fisico") { cr.MoveTo(400 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText("TOTAL " + descriopciongrupoproducto); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(680 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", totales_x_grupo)); Pango.CairoHelper.ShowLayout(cr, layout); comienzo_linea += separacion_linea; salto_de_pagina(cr, layout); //cr.MoveTo(680*escala_en_linux_windows, comienzo_linea*escala_en_linux_windows); layout.SetText(string.Format("{0:C}",total_inventario)); Pango.CairoHelper.ShowLayout (cr, layout); } if (tipo_reporte == "cargos_x_fecha") { cr.MoveTo(400 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText("TOTAL " + descriopciongrupoproducto); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(600 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", totales_x_grupo)); Pango.CairoHelper.ShowLayout(cr, layout); comienzo_linea += separacion_linea; salto_de_pagina(cr, layout); //cr.MoveTo(600*escala_en_linux_windows, comienzo_linea*escala_en_linux_windows); layout.SetText(string.Format("{0:C}",total_inventario)); Pango.CairoHelper.ShowLayout (cr, layout); } if (tipo_reporte == "inventario_actual") { cr.MoveTo(400 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText("TOTAL " + descriopciongrupoproducto); Pango.CairoHelper.ShowLayout(cr, layout); cr.MoveTo(680 * escala_en_linux_windows, comienzo_linea * escala_en_linux_windows); layout.SetText(string.Format("{0:C}", totales_x_grupo)); Pango.CairoHelper.ShowLayout(cr, layout); comienzo_linea += separacion_linea; salto_de_pagina(cr, layout); //cr.MoveTo(680*escala_en_linux_windows, comienzo_linea*escala_en_linux_windows); layout.SetText(string.Format("{0:C}",total_inventario)); Pango.CairoHelper.ShowLayout (cr, layout); } } }catch (NpgsqlException ex) { MessageDialog msgBoxError = new MessageDialog(MyWinError, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Ok, "PostgresSQL error: {0}", ex.Message); msgBoxError.Run(); msgBoxError.Destroy(); Console.WriteLine("PostgresSQL error: {0}", ex.Message); return; } }
private void FetchThread() { if (Interlocked.CompareExchange(ref FetchThreadFlag, 1, 0) == 0) { Application.Invoke((sender, e) => ChangeStatus("Veriler getiriliyor...")); try { Fetcher.Fetch(); FetchedCurrency = Fetcher.Base; Application.Invoke(delegate { MainPlotModel.Series.Clear(); string suffix = " (" + FetchedCurrency.ToString() + ")"; foreach (KeyValuePair <Currencies, List <Node> > pair in Fetcher.Data) { MainPlotModel.Series.Add(new LineSeries { Title = pair.Key.ToString() + " - " + pair.Key.GetStringValue() + suffix, ItemsSource = pair.Value, DataFieldX = "Time", DataFieldY = "Value", MarkerType = MarkerType.Circle }); } RenderAnnotations(); MainPlotModel.InvalidatePlot(true); MainPlotModel.ResetAllAxes(); }); } catch (Exception ex) when(ex is DateException || ex is SymbolsException) { Application.Invoke(delegate { MessageDialog dialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, ex.Message); dialog.Run(); dialog.Destroy(); }); } catch (WebException ex) { Application.Invoke(delegate { MessageDialog dialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "Sunucuya istekte bulunurken bir hata ile karşılaşıldı.\n\n" + "Mesaj: " + ex.Message + "\n" + "HResult: " + ex.HResult + "\n" + "Status: " + ex.Status); dialog.Run(); dialog.Destroy(); }); } Application.Invoke((sender, e) => ChangeStatus(ReadyStatusText)); Interlocked.Decrement(ref FetchThreadFlag); } else { Application.Invoke(delegate { MessageDialog dialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "Lütfen çalışan işlemin bitmesini bekleyin."); dialog.Run(); dialog.Destroy(); }); } }
public static bool Open(Widget parent) { var file = string.Empty; if (!IsUnix) { using (var openDialog = new OpenFileDialog()) { // check file exists openDialog.CheckFileExists = true; // If the previously browsed directory exists, then direct the user to it, otherwise direct to home directory. openDialog.InitialDirectory = Directory.Exists(Settings.Default.PreviousBrowseFolder) ? Settings.Default.PreviousBrowseFolder : Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); // Set the filter to show only 'prf' files openDialog.Filter = "Projects file (*.prj)|*.prj|Lock file (*.prj.lk) |*.prj.lk|All Files (*.*)|*.*"; openDialog.FilterIndex = 1; //RestoreDirectory = true, openDialog.ShowReadOnly = false; openDialog.ShowDialog(); file = openDialog.FileName; openDialog.Reset(); } } else { using (var openDialog = new FileChooserDialog("Open File", parent as Window, FileChooserAction.Open)) { openDialog.AddButton("Open", ResponseType.Ok); openDialog.AddButton("Cancel", ResponseType.Close); SetCurrentFolder(Directory.Exists(Settings.Default.PreviousBrowseFolder) ? Settings.Default.PreviousBrowseFolder : Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), openDialog.Handle); using (var openFilter = new FileFilter()) { openFilter.Name = "Projects File"; openFilter.AddMimeType("Projects File"); openFilter.AddPattern("*.prj"); openDialog.AddFilter(openFilter); } using (var openFilter = new FileFilter()) { openFilter.Name = "Projects Lock File"; openFilter.AddMimeType("Projects Lock File"); openFilter.AddPattern("*.prj.lk"); openDialog.AddFilter(openFilter); } using (var openFilter = new FileFilter()) { openFilter.Name = "All files"; openFilter.AddMimeType("All"); openFilter.AddPattern("*.*"); openDialog.AddFilter(openFilter); } if (openDialog.Run() == (int)ResponseType.Ok) { file = openDialog.File.ParsedName; } openDialog.Destroy(); } } // if no file has been provided / the file does not exist - do not continue if (string.IsNullOrEmpty(file) || !File.Exists(file)) { return(false); } //Console.WriteLine(Path.GetExtension(file)); // ensure that the correct file extension is being used if (Path.GetExtension(file) != ".prj") { using (var md = new MessageDialog(parent as Window, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "The selected file is not recognized by Projects.")) { md.Run(); md.Destroy(); } return(false); } // get the path from the selected file, by finding the last occurrence of a directory separator and save it into // the "PreviousBrowseFolder" Setting Settings.Default.PreviousBrowseFolder = file.Substring(0, file.LastIndexOf(Path.DirectorySeparatorChar)); // save settings Settings.Default.Save(); if (File.Exists(file + ".lk")) { using ( var dialog = new MessageDialog(parent as Window, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, $"The file is currently in use. If you're sure that this isn't the case, please delete the following file:\n {file}.lk") ) { dialog.Run(); dialog.Destroy(); } return(false); } var window = new ProjectWindow(file); window.Show(); parent.Destroy(); return(true); }
public Gfax(string fname, string[] args) : base(APPNAME, VERSION, Modules.UI, args, new object [0]) { //Phonebook[] pb; delete me // Set the program icon Gtk.Window.DefaultIconName = "gfax"; Application.Init(); // check to see if we've run before, if so gfax will be there if (Settings.RunSetupAtStart) { Settings.RunSetupAtStart = false; MessageDialog md; md = new MessageDialog( null, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, Catalog.GetString( @" This is the first time you have run Gfax. You should set your MODEM TYPE and PORT under preferences. Gfax is initially setup to use Efax, you may change it use Hylafax if you prefer or require connection to a network facsimile server.") ); md.Run(); md.Destroy(); } if (!Directory.Exists(gfax.SpoolDirectory)) { G_Message gm = new G_Message(Catalog.GetString( @"Your spool directory is missing! Please login as the root user and create the " + gfax.SpoolDirectory + " directory.\n\nAll users should be able to write to it.\n")); return; } if (!Directory.Exists(gfax.SpoolDirectory + "/doneq")) { G_Message gm = new G_Message(Catalog.GetString( @"The doneq directory is missing in your spool directory! Please login as the root user and create the " + gfax.SpoolDirectory + "/doneq" + " directory.\n\nAll users should be able to write to it.\n")); return; } if (!Directory.Exists(gfax.SpoolDirectory + "/recq")) { G_Message gm = new G_Message(Catalog.GetString( @"The recq directory is missing in your spool directory! Please login as the root user and create the " + gfax.SpoolDirectory + "/recq" + " directory.\n\nAll users should be able to write to it.\n")); return; } gxml = new Glade.XML(null, "gfax.glade", "GfaxWindow", null); gxml.Autoconnect(this); // Set initial gui state as per preferences // GConf.PropertyEditors.EditorShell doesn't handle // checkmenuitems; eventsEnabled = false; if (Settings.TransmitAgent == "hylafax") { AutoQRefreshCheckMenuItem.Active = Settings.RefreshQueueEnabled; EmailNotificationCheckMenuItem.Active = Settings.EmailNotify; HiResolutionModeCheckMenuItem.Active = Settings.HiResolution; LogEnabledCheckMenuItem.Active = Settings.LogEnabled; } if (Settings.TransmitAgent == "efax") { AutoQRefreshCheckMenuItem.Active = Settings.RefreshQueueEnabled; AutoQRefreshCheckMenuItem.Sensitive = false; EmailNotificationCheckMenuItem.Active = false; EmailNotificationCheckMenuItem.Sensitive = false; HiResolutionModeCheckMenuItem.Active = Settings.HiResolution; LogEnabledCheckMenuItem.Visible = false; } FaxTracingCheckMenuItem.Active = Settings.Faxtracing; eventsEnabled = true; StatusText.Editable = false; StatusText.CanFocus = false; StatusText.Buffer = StatusTextBuffer; // Set the program icon Gdk.Pixbuf Icon = new Gdk.Pixbuf(null, "gfax.png"); gfax.MainWindow = GfaxWindow; // Setup listview icons InitListViewIcons(); StatusStore = new ListStore( typeof(Gdk.Pixbuf), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(DateTime), typeof(string)); RecvStore = new ListStore( typeof(Gdk.Pixbuf), typeof(string), typeof(string), typeof(string), typeof(DateTime), typeof(string)); lv = new G_ListView(StatusList, StatusStore); lv.AddColumnIcon(Gtk.Stock.Info, 0); lv.AddColumnTitle(Catalog.GetString("Jobid"), 1, 1); lv.AddColumnTitle(Catalog.GetString("Number"), 2, 2); lv.AddColumnTitle(Catalog.GetString("Status"), 3, 3); lv.AddColumnTitle(Catalog.GetString("Owner"), 4, 4); lv.AddColumnTitle(Catalog.GetString("Pages"), 5, 5); lv.AddColumnTitle(Catalog.GetString("Dials"), 6, 6); lv.AddColumnDateTime(Catalog.GetString("Send At"), "G", 7, 7); lv.AddColumnTitle(Catalog.GetString("Information"), 8, 8); // List view for completed jobs tab jobsCompletedView = new G_ListView(JobsCompleteList, StatusStore); jobsCompletedView.AddColumnIcon(Gtk.Stock.Info, 0); jobsCompletedView.AddColumnTitle(Catalog.GetString("Jobid"), 1, 1); jobsCompletedView.AddColumnTitle(Catalog.GetString("Number"), 2, 2); jobsCompletedView.AddColumnTitle(Catalog.GetString("Status"), 3, 3); jobsCompletedView.AddColumnTitle(Catalog.GetString("Owner"), 4, 4); jobsCompletedView.AddColumnTitle(Catalog.GetString("Pages"), 5, 5); jobsCompletedView.AddColumnTitle(Catalog.GetString("Dials"), 6, 6); jobsCompletedView.AddColumnDateTime(Catalog.GetString("Send At"), "G", 7, 7); jobsCompletedView.AddColumnTitle(Catalog.GetString("Information"), 8, 8); jobsReceivedView = new G_ListView(JobsReceivedList, RecvStore); jobsReceivedView.AddColumnIcon(Gtk.Stock.Info, 0); jobsReceivedView.AddColumnTitle(Catalog.GetString("Sender"), 1, 1); jobsReceivedView.AddColumnTitle(Catalog.GetString("Status"), 2, 2); jobsReceivedView.AddColumnTitle(Catalog.GetString("Pages "), 3, 3); jobsReceivedView.AddColumnDateTime(Catalog.GetString("Arrived"), "G", 4, 4); jobsReceivedView.AddColumnTitle(Catalog.GetString("Filename"), 5, 5); StatusList.Selection.Changed += new EventHandler(on_StatusList_selection); StatusList.Selection.Mode = SelectionMode.Multiple; StatusList.HeadersVisible = true; JobsCompleteList.Selection.Changed += new EventHandler(on_JobsCompleteList_selection); JobsCompleteList.Selection.Mode = SelectionMode.Multiple; JobsCompleteList.HeadersVisible = true; JobsReceivedList.Selection.Changed += new EventHandler(on_JobsReceivedList_selection); JobsReceivedList.Selection.Mode = SelectionMode.Multiple; JobsReceivedList.HeadersVisible = true; // Make sure headers are visible lv.AddTextToRow(null, "", "", "", "", "", "", null, ""); jobsCompletedView.AddTextToRow(null, "", "", "", "", "", "", null, ""); jobsReceivedView.AddTextToRow(null, "", "", "", null, ""); StatusStore.Clear(); RecvStore.Clear(); DeleteJobButton.Sensitive = false; if (Settings.TransmitAgent == "hylafax") { ModifyJobButton.Sensitive = false; } else { ModifyJobButton.Visible = false; } ViewPrintButton.Sensitive = false; // Setup some global variables gfax.MainProgressBar = Appbar.Progress; gfax.GStatusTextBuffer = StatusTextBuffer; gfax.GAppbar = Appbar; gfax.Pulser = new Pulser(); gfax.Status = new Status(StatusText, StatusTextBuffer); if (Settings.RefreshQueueEnabled) { GLib.Timeout.Add((uint)(Settings.RefreshQueueInterval * 1000), new TimeoutHandler(queue_refresh)); } async_update_status(); if (Settings.TransmitAgent == "hylafax") { while (gfax.activeNetwork) { System.Threading.Thread.Sleep(100); } async_net_read_finished(); } activeQ = ActiveQ.send; async_update_queue_status("sendq"); StatusIcon sicon = new StatusIcon(Icon); sicon.Activate += new EventHandler(OnImageClick); sicon.Tooltip = "Gfax Facsimile Sender"; // showing the trayicon sicon.Visible = true; // setup system tray icon gfax.MainWindow.SkipTaskbarHint = true; gfax.MainWindow.Iconify(); Application.Run(); }
// Constructor for teacheraddfeedbackwindow public TeacherAddFeedbackWindow(User user, TextViewList textviews, string Filename) : base("Add Feedback") { this.user = user; this.textviews = textviews; this.Filename = Filename; SetSizeRequest(300, 300); Grid grid = new Grid(); Label labClass = new Label("Class:"); Entry entClass = new Entry(); entClass.Changed += (e, arg) => { className = entClass.Text; }; Button buttonCancel = new Button("Cancel"); buttonCancel.Clicked += delegate { Destroy(); }; Button buttonFeedback = new Button("Feedback"); buttonFeedback.Clicked += delegate { string feedbackString = String.Empty; List <MetaType> metaTypeList = new List <MetaType>(); // Packs the workspace into a single string for easy transfer foreach (Widget w in this.textviews) { if (w.GetType() == typeof(MovableCasCalcView)) { MetaType metaType = new MetaType(); MovableCasCalcView calcView = (MovableCasCalcView)w; metaType.type = typeof(MovableCasCalcView); metaType.metastring = calcView.calcview.input.Text; metaType.locked = calcView.textview.locked; metaTypeList.Add(metaType); } else if (w is MovableCasCalcMulitlineView) { MetaType metaType = new MetaType(); MovableCasCalcMulitlineView calcview = (MovableCasCalcMulitlineView)w; metaType.type = typeof(MovableCasCalcMulitlineView); metaType.metastring = calcview.calcview.SerializeCasTextView(); metaType.locked = calcview.textview.locked; metaTypeList.Add(metaType); } else if (w is MovableCasResult) { MetaType metaType = new MetaType(); MovableCasResult casres = (MovableCasResult)w; metaType.type = typeof(MovableCasResult); metaType.metastring = Export.Serialize(casres.casresult.facitContainer); metaType.locked = casres.textview.locked; metaTypeList.Add(metaType); } else if (w.GetType() == typeof(MovableCasTextView)) { MetaType metaType = new MetaType(); MovableCasTextView textView = (MovableCasTextView)w; metaType.type = typeof(MovableCasTextView); metaType.metastring = textView.textview.SerializeCasTextView(); metaType.locked = textView.textview.locked; metaTypeList.Add(metaType); } } if (metaTypeList.Count != 0 && string.IsNullOrEmpty(className) == false && string.IsNullOrEmpty(this.Filename) == false) { feedbackString = Export.Serialize(metaTypeList); } string[] StudentList = this.user.teacher.GetCompletedList(this.Filename, className); grid.Destroy(); grid = new Grid(); for (int i = 0; i < StudentList.Length / 2; i++) { int j = 2 * i; Button button = new Button(StudentList[j]); button.Clicked += delegate { this.user.teacher.AddFeedback(feedbackString, this.Filename, StudentList[j], className); MessageDialog ms = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, "Added feedback"); ms.Run(); ms.Destroy(); Destroy(); }; grid.Attach(button, 1, 1 + i, 1, 1); } Add(grid); ShowAll(); }; grid.Attach(labClass, 1, 1, 1, 1); grid.Attach(entClass, 2, 1, 1, 1); grid.Attach(buttonCancel, 1, 3, 1, 1); grid.Attach(buttonFeedback, 2, 3, 1, 1); Add(grid); ShowAll(); }
public void Import(string fileName, Gtk.Window parent) { ZipFile file = new ZipFile(fileName); XmlDocument stackXml = new XmlDocument(); stackXml.Load(file.GetInputStream(file.GetEntry("stack.xml"))); XmlElement imageElement = stackXml.DocumentElement; int width = int.Parse(imageElement.GetAttribute("w")); int height = int.Parse(imageElement.GetAttribute("h")); Size imagesize = new Size(width, height); Document doc = PintaCore.Workspace.CreateAndActivateDocument(fileName, imagesize); doc.HasFile = true; XmlElement stackElement = (XmlElement)stackXml.GetElementsByTagName("stack")[0]; XmlNodeList layerElements = stackElement.GetElementsByTagName("layer"); if (layerElements.Count == 0) { throw new XmlException("No layers found in OpenRaster file"); } doc.ImageSize = imagesize; doc.Workspace.CanvasSize = imagesize; for (int i = 0; i < layerElements.Count; i++) { XmlElement layerElement = (XmlElement)layerElements[i]; int x = int.Parse(GetAttribute(layerElement, "x", "0")); int y = int.Parse(GetAttribute(layerElement, "y", "0")); string name = GetAttribute(layerElement, "name", string.Format("Layer {0}", i)); try { // Write the file to a temporary file first // Fixes a bug when running on .Net ZipEntry zf = file.GetEntry(layerElement.GetAttribute("src")); Stream s = file.GetInputStream(zf); string tmp_file = System.IO.Path.GetTempFileName(); using (Stream stream_out = File.Open(tmp_file, FileMode.OpenOrCreate)) { byte[] buffer = new byte[2048]; while (true) { int len = s.Read(buffer, 0, buffer.Length); if (len > 0) { stream_out.Write(buffer, 0, len); } else { break; } } } UserLayer layer = doc.CreateLayer(name); doc.Insert(layer, 0); layer.Opacity = double.Parse(GetAttribute(layerElement, "opacity", "1"), GetFormat()); layer.BlendMode = StandardToBlendMode(GetAttribute(layerElement, "composite-op", "svg:src-over")); using (var fs = new FileStream(tmp_file, FileMode.Open)) using (Pixbuf pb = new Pixbuf(fs)) { using (Context g = new Context(layer.Surface)) { CairoHelper.SetSourcePixbuf(g, pb, x, y); g.Paint(); } } try { File.Delete(tmp_file); } catch { } } catch { MessageDialog md = new MessageDialog(parent, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Could not import layer \"{0}\" from {0}", name, file); md.Title = "Error"; md.Run(); md.Destroy(); } } file.Close(); }
protected void HotKeyPressed(object o, KeyPressEventArgs args) { // Help screen if (args.Event.Key == Gdk.Key.F1) { var help = "F1 - Окно помощи (это окно)"; help += "\n----------------------------"; help += "\nCtrl+R - обновить содержимое окна"; help += "\n----------------------------"; help += "\nPageDown - следующий вопрос"; help += "\nPageUp - предыдущий вопрос"; help += "\n1,2,3,4,5,6,7,8,9,0 - отметить/снять ответ"; var msgHelp = new MessageDialog(this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, help); msgHelp.Run(); msgHelp.Destroy(); return; } // Hopefully manual fix for the screen problem if ((args.Event.State & Gdk.ModifierType.ControlMask) == Gdk.ModifierType.ControlMask) { // Refresh the window position if ((args.Event.Key == Gdk.Key.r)) { this.Fullscreen(); return; } } // Anti-cheat Alt+Tab blocker if ((args.Event.State & Gdk.ModifierType.Mod1Mask) == Gdk.ModifierType.Mod1Mask) { if (args.Event.Key == Gdk.Key.Tab) { var msg = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "Не подглядывай!\nDon't try to cheat!\n:P"); msg.Run(); msg.Destroy(); return; } } // Next question if (args.Event.Key == Gdk.Key.Page_Down) { NextQuestion(null, null); return; } // Previous question if (args.Event.Key == Gdk.Key.Page_Up) { PreviousQuestion(null, null); return; } // Halt test if ( args.Event.Key == Gdk.Key.Escape || (((args.Event.State & Gdk.ModifierType.Mod1Mask) == Gdk.ModifierType.Mod1Mask) && args.Event.Key == Gdk.Key.F4) ) { var question = "Вы уверены, что хотите завершить тест досрочно?\nAre you sure you wish to halt the test?"; var msg = new MessageDialog(this, DialogFlags.Modal, MessageType.Question, ButtonsType.YesNo, question); int result = msg.Run(); msg.Destroy(); if (result == (int)ResponseType.Yes) { HaltTest(null, null); } return; } // Select/Deselect answer from 1 to 10 switch (args.Event.Key) { case Gdk.Key.Key_1: { if (answers.Length >= 1) { answers [0].Active = !answers [0].Active; } } break; case Gdk.Key.Key_2: { if (answers.Length >= 2) { answers [1].Active = !answers [1].Active; } } break; case Gdk.Key.Key_3: { if (answers.Length >= 3) { answers [2].Active = !answers [2].Active; } } break; case Gdk.Key.Key_4: { if (answers.Length >= 4) { answers [3].Active = !answers [3].Active; } } break; case Gdk.Key.Key_5: { if (answers.Length >= 5) { answers [4].Active = !answers [4].Active; } } break; case Gdk.Key.Key_6: { if (answers.Length >= 6) { answers [5].Active = !answers [5].Active; } } break; case Gdk.Key.Key_7: { if (answers.Length >= 7) { answers [6].Active = !answers [6].Active; } } break; case Gdk.Key.Key_8: { if (answers.Length >= 8) { answers [7].Active = !answers [7].Active; } } break; case Gdk.Key.Key_9: { if (answers.Length >= 9) { answers [8].Active = !answers [8].Active; } } break; case Gdk.Key.Key_0: { if (answers.Length >= 10) { answers [9].Active = !answers [9].Active; } } break; default: break; } }
/// <summary> /// Creates a new instance of the <see cref="MainWindow"/> class. /// </summary> public MainWindow() : base(Gtk.WindowType.Toplevel) { // Initialize the GTK UI this.Build(); // Bind the handler events Game.ProgressChanged += OnModuleInstallationProgressChanged; Game.DownloadFinished += OnGameDownloadFinished; Game.DownloadFailed += OnGameDownloadFailed; Game.LaunchFailed += OnGameLaunchFailed; Game.GameExited += OnGameExited; Launcher.LauncherDownloadProgressChanged += OnModuleInstallationProgressChanged; Launcher.LauncherDownloadFinished += OnLauncherDownloadFinished; Launcher.ChangelogDownloadFinished += OnChangelogDownloadFinished; // Set the initial launcher mode SetLauncherMode(ELauncherMode.Inactive, false); // Set the window title Title = LocalizationCatalog.GetString("Launchpad - {0}", Config.GetGameName()); // Create a new changelog widget, and add it to the scrolled window this.Browser = new Changelog(this.browserWindow); browserWindow.ShowAll(); indicatorLabel.Text = LocalizationCatalog.GetString("Idle"); // First of all, check if we can connect to the patching service. if (!Checks.CanPatch()) { MessageDialog dialog = new MessageDialog( null, DialogFlags.Modal, MessageType.Warning, ButtonsType.Ok, LocalizationCatalog.GetString("Failed to connect to the patch server. Please check your settings.")); dialog.Run(); dialog.Destroy(); indicatorLabel.Text = LocalizationCatalog.GetString("Could not connect to server."); repairGameAction.Sensitive = false; } else { // TODO: Load this asynchronously // Load the game banner (if there is one) if (Config.GetPatchProtocol().CanProvideBanner()) { using (MemoryStream bannerStream = new MemoryStream()) { // Fetch the banner from the server Config.GetPatchProtocol().GetBanner().Save(bannerStream, ImageFormat.Png); // Load the image into a pixel buffer bannerStream.Position = 0; this.gameBanner.Pixbuf = new Pixbuf(bannerStream); } } // If we can connect, proceed with the rest of our checks. if (ChecksHandler.IsInitialStartup()) { Log.Info("This instance is the first start of the application in this folder."); MessageDialog shouldInstallHereDialog = new MessageDialog( null, DialogFlags.Modal, MessageType.Question, ButtonsType.OkCancel, LocalizationCatalog.GetString( "This appears to be the first time you're starting the launcher.\n" + "Is this the location where you would like to install the game?") + $"\n\n{ConfigHandler.GetLocalDir()}" ); if (shouldInstallHereDialog.Run() == (int)ResponseType.Ok) { shouldInstallHereDialog.Destroy(); // Yes, install here Log.Info("User accepted installation in this directory. Installing in current directory."); ConfigHandler.CreateLauncherCookie(); } else { shouldInstallHereDialog.Destroy(); // No, don't install here Log.Info("User declined installation in this directory. Exiting..."); Environment.Exit(2); } } if (Config.ShouldAllowAnonymousStats()) { StatsHandler.SendUsageStats(); } // Load the changelog. Try a direct URL first, and a protocol-specific // implementation after. if (LauncherHandler.CanAccessStandardChangelog()) { Browser.Navigate(Config.GetChangelogURL()); } else { Launcher.LoadFallbackChangelog(); } // If the launcher does not need an update at this point, we can continue checks for the game if (!Checks.IsLauncherOutdated()) { if (!Checks.IsPlatformAvailable(Config.GetSystemTarget())) { Log.Info($"The server does not provide files for platform \"{ConfigHandler.GetCurrentPlatform()}\". " + "A .provides file must be present in the platforms' root directory."); SetLauncherMode(ELauncherMode.Inactive, false); } else { if (!Checks.IsGameInstalled()) { // If the game is not installed, offer to install it Log.Info("The game has not yet been installed."); SetLauncherMode(ELauncherMode.Install, false); // Since the game has not yet been installed, disallow manual repairs this.repairGameAction.Sensitive = false; // and reinstalls this.reinstallGameAction.Sensitive = false; } else { // If the game is installed (which it should be at this point), check if it needs to be updated if (Checks.IsGameOutdated()) { // If it does, offer to update it Log.Info($"The game is outdated. \n\tLocal version: {Config.GetLocalGameVersion()}"); SetLauncherMode(ELauncherMode.Update, false); } else { // All checks passed, so we can offer to launch the game. Log.Info("All checks passed. Game can be launched."); SetLauncherMode(ELauncherMode.Launch, false); } } } } else { // The launcher was outdated. Log.Info($"The launcher is outdated. \n\tLocal version: {Config.GetLocalLauncherVersion()}"); SetLauncherMode(ELauncherMode.Update, false); } } }
/// <summary> /// Triggered once the user presses the create button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void _createButton_Clicked(object sender, EventArgs e) { var path = _filepathEntry.Text; var file = _fileEntry.Text + ".prj"; var full = System.IO.Path.Combine(path, file); var cont = true; // Console.WriteLine("Before: " + path + ", " + file); if (File.Exists(full)) { // create a dialog asking the user if they wish to overwrite the file // implements IDisposable using ( var overwriteConfirm = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Question, ButtonsType.YesNo, $"File: {_fileEntry.Text} already exists in the desired path.\nDo you want to overwrite it?") ) { // if the user presses Yes if (overwriteConfirm.Run() == (int)ResponseType.Yes) { // check if the lockfile exists and delete the file if it does not if (!File.Exists(full + ".lk")) { try { File.Delete(full); //cont = true; } catch (IOException ioException) { using ( var error = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, $"IoException: {ioException.Message}")) { error.Run(); error.Destroy(); } cont = false; } overwriteConfirm.Destroy(); } // otherwise show an error message saying the file has been locked else { //implements IDisposable using (var error = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "The file has been locked for editing and cannot be deleted")) { error.Run(); error.Destroy(); overwriteConfirm.Destroy(); } cont = false; } } else { overwriteConfirm.Destroy(); cont = false; } } } if (!cont) { return; } #if DEBUG Console.WriteLine($"LoadOnStart: {_loadOnStartButton.Active}"); #endif // if the user has checked the load on startup tick box, if (_loadOnStartButton.Active) { // modify the application properties which are used to determine the file to load // at start-up and then save the properties. backend.Settings.Default.LoadOnStartup = true; backend.Settings.Default.FileOnStartup = full; backend.Settings.Default.Save(); #if DEBUG Console.WriteLine( $"{backend.Settings.Default.FileOnStartup} \n {backend.Settings.Default.FileOnStartup}"); #endif } // destroy the wizard window Destroy(); // create the Project window new ProjectWindow(path, file).Show(); }
private bool updatePrefs() { this.Log().Debug("Updating the prefs"); if (isUpdating) { this.Log().Debug("UI is currently updating. No need to update."); return(false); } bool hasError = false; string errorData = ""; // Test for the new defaults this.Log().Info("Validating input preferences"); Prefs prefsToTest = new Prefs(); prefsToTest.prefPrefix = "testCurrent"; prefsToTest.format = (Prefs.prefFormat)comboFormat.Active; int output; Int32.TryParse(txtWidth.Text, out output); prefsToTest.width = output; Int32.TryParse(txtHeight.Text, out output); prefsToTest.height = output; prefsToTest.keepProportion = chkProportion.Active; string message; if (!prefsToTest.ValidatePrefs(out message)) { hasError = true; errorData += message; } if (hasError) { this.Log().Warn("Error found in the validation: " + Environment.NewLine + Environment.NewLine + message); // update with defaults if (prefsToTest.width <= 0) { this.Log().Debug("Bad width input, using default"); txtWidth.Text = defaultPrefs.width.ToString(); } if (prefsToTest.height <= 0) { this.Log().Debug("Bad height input, using default"); txtHeight.Text = defaultPrefs.height.ToString(); } // bad input MessageDialog result = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Invalid inputs. Please make sure you are using correct inputs." + Environment.NewLine + Environment.NewLine + "Error(s) found:" + Environment.NewLine + message); if (result.Run() == (int)ResponseType.Ok) { result.Destroy(); } } else { this.Log().Info("Updating valid prefs and save"); currentPrefs = prefsToTest; currentPrefs.prefPrefix = "Current"; currentPrefs.SavePrefToManager(mgr.GetManager()); mgr.Save(); updateFromPref(); } return(true); }
private void Export(ExportType exportType) { ExportProperties props = null; ExportDialog export = new ExportDialog(exportType); export.Response += delegate(object obj, ResponseArgs resp) { if (resp.ResponseId == ResponseType.Ok) { props = export.Properties; } }; export.Run(); export.Destroy(); if (props == null) { return; } FileChooserDialog fc = new FileChooserDialog("Kaydedilecek Yeri Seçin", this, FileChooserAction.Save, "Vazgeç", ResponseType.Cancel, "Kaydet", ResponseType.Accept); if (fc.Run() == (int)ResponseType.Accept) { props.FileName = fc.Filename; } fc.Destroy(); if (props.FileName == null) { return; } if (props.Type == ExportType.PDF) { PdfExporter exporter = new PdfExporter { Width = props.Width, Height = props.Height, Background = OxyColor.FromRgb(props.Color[0], props.Color[1], props.Color[2]) }; try { using (FileStream file = File.Create(props.FileName)) exporter.Export(MainPlotModel, file); } catch (Exception ex) { MessageDialog dialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "Dışarı aktarılırken bir sorunla karşılaşıldı.\n\n" + "Mesaj: " + ex.Message); dialog.Run(); dialog.Destroy(); } } else if (props.Type == ExportType.PNG) { PngExporter exporter = new PngExporter { Width = (int)props.Width, Height = (int)props.Height, Background = OxyColor.FromRgb(props.Color[0], props.Color[1], props.Color[2]) }; try { using (FileStream file = File.Create(props.FileName)) exporter.Export(MainPlotModel, file); } catch (Exception ex) { MessageDialog dialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "Dışarı aktarılırken bir sorunla karşılaşıldı.\n\n" + "Mesaj: " + ex.Message); dialog.Run(); dialog.Destroy(); } } else if (props.Type == ExportType.SVG) { SvgExporter exporter = new SvgExporter { Width = (int)props.Width, Height = (int)props.Height }; try { using (FileStream file = File.Create(props.FileName)) exporter.Export(MainPlotModel, file); } catch (Exception ex) { MessageDialog dialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "Dışarı aktarılırken bir sorunla karşılaşıldı.\n\n" + "Mesaj: " + ex.Message); dialog.Run(); dialog.Destroy(); } } }
protected void OnButtonOkClicked(object sender, EventArgs e) { string sql; ISaaSService svc = null; if (entryLogin.Text == "root") { string Message = "Операции с пользователем root запрещены."; MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Ok, Message); md.Run(); md.Destroy(); return; } if (Session.IsSaasConnection) { int dlgRes; svc = Session.GetSaaSService(); if (NewUser) { //Проверка существует ли логин sql = "SELECT COUNT(*) FROM users WHERE login = @login"; QSMain.CheckConnectionAlive(); MySqlCommand cmd = new MySqlCommand(sql, QSMain.connectionDB); cmd.Parameters.AddWithValue("@login", entryLogin.Text); if (Convert.ToInt32(cmd.ExecuteScalar()) > 0) { string Message = "Пользователь с логином " + entryLogin.Text + " уже существует в базе. " + "Создание второго пользователя с таким же логином невозможно."; MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Ok, Message); md.Run(); md.Destroy(); return; } //Регистрируем пользователя в SaaS Result result = svc.registerUserV3(entryLogin.Text, entryPassword.Text, Session.SessionId, entryName.Text, entryEmail.Text); if (!result.Success) { if (result.Error == ErrorType.UserExists) { MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.YesNo, "Пользователь с таким логином уже существует. Предоставить ему доступ к базе?\n" + "ВНИМАНИЕ: Если вы указали новый пароль для пользователя, то он применен не будет."); dlgRes = md.Run(); md.Destroy(); if ((ResponseType)dlgRes == ResponseType.No) { return; } } else { MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Close, result.Description); md.Run(); md.Destroy(); return; } } //Создаем запись в Users. sql = "INSERT INTO users (name, login, deactivated, email, " + QSMain.AdminFieldName + ", description" + QSMain.GetPermissionFieldsForSelect() + GetExtraFieldsForSelect() + ") " + "VALUES (@name, @login, @deactivated, @email, @admin, @description" + QSMain.GetPermissionFieldsForInsert() + GetExtraFieldsForInsert() + ")"; } else { if (entryPassword.Text != passFill) { MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.YesNo, "Изменение пароля произойдет во всех базах, к которым пользователь имеет доступ.\nПродолжить?"); dlgRes = md.Run(); md.Destroy(); if ((ResponseType)dlgRes == ResponseType.Yes && !svc.changeUserPasswordByLogin(entryLogin.Text, Session.Account, entryPassword.Text)) { MessageDialog md1 = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Close, "Ошибка изменения пароля пользователя."); md1.Run(); md1.Destroy(); return; } else if ((ResponseType)dlgRes != ResponseType.Yes) { return; } } sql = "UPDATE users SET name = @name, deactivated = @deactivated, email = @email, " + QSMain.AdminFieldName + " = @admin," + "description = @description " + QSMain.GetPermissionFieldsForUpdate() + GetExtraFieldsForUpdate() + " WHERE id = @id"; } } else { if (NewUser) { if (!CreateLogin()) { return; } sql = "INSERT INTO users (name, login, deactivated, email, " + QSMain.AdminFieldName + ", description" + QSMain.GetPermissionFieldsForSelect() + GetExtraFieldsForSelect() + ") " + "VALUES (@name, @login, @deactivated, @email, @admin, @description" + QSMain.GetPermissionFieldsForInsert() + GetExtraFieldsForInsert() + ")"; } else { if (OriginLogin != entryLogin.Text && !RenameLogin()) { return; } if (entryPassword.Text != passFill) { ChangePassword(); } sql = "UPDATE users SET name = @name, deactivated = @deactivated, email = @email, login = @login, " + QSMain.AdminFieldName + " = @admin," + "description = @description " + QSMain.GetPermissionFieldsForUpdate() + GetExtraFieldsForUpdate() + " WHERE id = @id"; } UpdatePrivileges(); logger.Info("Запись пользователя..."); } try { QSMain.CheckConnectionAlive(); MySqlCommand cmd = new MySqlCommand(sql, QSMain.connectionDB); cmd.Parameters.AddWithValue("@id", entryID.Text); cmd.Parameters.AddWithValue("@name", entryName.Text); cmd.Parameters.AddWithValue("@login", entryLogin.Text); cmd.Parameters.AddWithValue("@admin", checkAdmin.Active); cmd.Parameters.AddWithValue("@deactivated", checkDeactivated.Active); cmd.Parameters.AddWithValue("@email", entryEmail.Text); foreach (KeyValuePair <string, CheckButton> Pair in RightCheckButtons) { cmd.Parameters.AddWithValue("@" + QSMain.ProjectPermission[Pair.Key].DataBaseName, Pair.Value.Active); } if (permissionViews != null) { foreach (var view in permissionViews) { cmd.Parameters.AddWithValue(view.DBFieldName, view.DBFieldValue); } } if (textviewComments.Buffer.Text == "") { cmd.Parameters.AddWithValue("@description", DBNull.Value); } else { cmd.Parameters.AddWithValue("@description", textviewComments.Buffer.Text); } cmd.ExecuteNonQuery(); if (QSMain.User.Login == entryLogin.Text) { QSMain.User.LoadUserInfo(); } logger.Info("Ok"); Respond(ResponseType.Ok); } catch (Exception ex) { logger.Error(ex, "Ошибка записи пользователя!"); QSMain.ErrorMessage(this, ex); } //Предоставляем пользователю доступ к базе if (Session.IsSaasConnection) { if (!svc.changeBaseAccessFromProgram(Session.SessionId, entryLogin.Text, Session.SaasBaseName, !checkDeactivated.Active, checkAdmin.Active)) { MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Close, "Ошибка предоставления доступа к базе данных."); md.Run(); md.Destroy(); return; } } }
protected void OnCSVExportActionActivated(object sender, EventArgs e) { if (Fetcher.Data == null || Fetcher.Data.Count == 0) { MessageDialog dialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "Dışarı aktarılacak veri yok."); dialog.Run(); dialog.Destroy(); return; } string FileName = null; FileChooserDialog fc = new FileChooserDialog("Kaydedilecek Yeri Seçin", this, FileChooserAction.Save, "Vazgeç", ResponseType.Cancel, "Kaydet", ResponseType.Accept); if (fc.Run() == (int)ResponseType.Accept) { FileName = fc.Filename; } fc.Destroy(); if (FileName == null) { return; } try { using (StreamWriter sw = File.CreateText(FileName)) { const string sep = ","; sw.NewLine = "\r\n"; List <Currencies> keys = new List <Currencies>(Fetcher.Data.Keys); string header = "Date" + sep; string suffix = "/" + FetchedCurrency.ToString(); foreach (Currencies cur in keys) { header += cur.ToString() + suffix + sep; } sw.WriteLine(header.Substring(0, header.Length - 1)); for (int i = 0; i < Fetcher.Data[keys[0]].Count; i++) { string line = Fetcher.Data[keys[0]][i].Time.ToString(DateStringFormat) + sep; foreach (Currencies cur in keys) { line += Fetcher.Data[cur][i].Value.ToString("0.0000000000", System.Globalization.CultureInfo.InvariantCulture) + sep; } sw.WriteLine(line.Substring(0, line.Length - 1)); } } } catch (Exception ex) { MessageDialog dialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "Dışarı aktarılırken bir sorunla karşılaşıldı.\n\n" + "Mesaj: " + ex.Message); dialog.Run(); dialog.Destroy(); } }
private void OnBtnSaveClicked(object sender, EventArgs e) { if (!RequiresSave()) { btnSave.Sensitive = false; return; } IDbTransaction transaction = sqlConn.BeginTransaction(); // Create command and set connection and transaction objects IDbCommand command = sqlConn.CreateCommand(); command.Connection = sqlConn; command.Transaction = transaction; try { TreeIter iter; int col; // Add the updates for each changed value for (int i = 0; i < needsSave; ++i) { iter = saveRequired[i].Item1; col = saveRequired[i].Item2; command.CommandText = "UPDATE " + curTable + " SET "; command.CommandText += dataViewer.GetColumn(col).Title; command.CommandText += " = '"; command.CommandText += data.GetValue(iter, col).ToString(); command.CommandText += "' WHERE "; command.CommandText += dataViewer.GetColumn(0).Title; command.CommandText += " = "; command.CommandText += data.GetValue(iter, 0).ToString(); command.CommandText += ";"; Console.WriteLine(command.CommandText); command.ExecuteNonQuery(); } // Start the transaction transaction.Commit(); // Remove everything from the save list RemoveAllSaveList(); // Successful MessageDialog dialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Ok, "Datos actualizados."); dialog.Run(); dialog.Destroy(); } catch (Exception /* ex */) { MessageDialog dialog = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "No se ha podido completar la transacción, volviendo atrás."); dialog.Run(); dialog.Destroy(); try { transaction.Rollback(); } catch (Exception /* nestedEx */) { MessageDialog dialog1 = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, "No se ha podido completar la transacción, ni volver atrás. Quizás haya datos dañados."); dialog1.Run(); dialog1.Destroy(); } } }
void HandleClicked(object sender, EventArgs e) { string template = string.Empty; Assembly asm = Assembly.GetExecutingAssembly(); string rsrc = _encrypted.Active ? "MetasploitPayloadUtility.EncryptedTemplate.txt" : "MetasploitPayloadUtility.GeneralTemplate.txt"; using (StreamReader rdr = new StreamReader(asm.GetManifestResourceStream(rsrc))) template = rdr.ReadToEnd(); string winx64Payload = "payload = new byte[][] {"; string winx86Payload = winx64Payload; string linx86Payload = winx86Payload; string linx64Payload = linx86Payload; MessageDialog md; try { if (!_encrypted.Active) { foreach (var pair in _newPayloads) { pair.Value ["Format"] = "csharp"; var response = _manager.ExecuteModule("payload", pair.Key, pair.Value); if (response.Count == 6) { md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Close, "Generating payload failed.\n\n" + response["error_message"]); md.Run(); md.Destroy(); return; } string payload = System.Text.Encoding.ASCII.GetString(response ["payload"] as byte[]) .Split('=') [1].Replace(";", ","); if (pair.Key.StartsWith("linux/x86") || pair.Key.StartsWith("osx/x86")) { linx86Payload += payload; } else if (pair.Key.StartsWith("linux/x64") || pair.Key.StartsWith("osx/x64")) { linx64Payload += payload; } else if (pair.Key.StartsWith("windows/x64")) { winx64Payload += payload; } else /*windows x86*/ { winx86Payload += payload; } } winx64Payload += "};"; winx86Payload += "};"; linx64Payload += "};"; linx86Payload += "};"; //Console.WriteLine (winx64Payload); //Console.WriteLine (winx86Payload); //Console.WriteLine (linx64Payload); //Console.WriteLine (linx86Payload); } else { byte[] parity = new byte[4]; for (int i = 0; i < 4; i++) { parity [i] = Convert.ToByte(Convert.ToInt32(Math.Floor(26 * _random.NextDouble() + 65))); } foreach (var pair in _newPayloads) { pair.Value ["Format"] = "raw"; var response = _manager.ExecuteModule("payload", pair.Key, pair.Value); if (response.Count == 6) { md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Close, "Generating payload failed.\n\n" + response["error_message"]); md.Run(); md.Destroy(); return; } if (pair.Key.StartsWith("linux/x86") || pair.Key.StartsWith("osx/x86")) { byte[] b = response ["payload"] as byte[]; byte[] encb = new byte[b.Length + 4]; encb [0] = parity [0]; encb [1] = parity [1]; encb [2] = parity [2]; encb [3] = parity [3]; for (int i = 4; i < b.Length; i++) { encb [i] = b [i - 4]; } linx86Payload += GetByteArrayString(EncryptData(encb, _random.Next(1024).ToString())); } else if (pair.Key.StartsWith("linux/x64") || pair.Key.StartsWith("osx/x64")) { byte[] b = response ["payload"] as byte[]; byte[] encb = new byte[b.Length + 4]; encb [0] = parity [0]; encb [1] = parity [1]; encb [2] = parity [2]; encb [3] = parity [3]; for (int i = 4; i < b.Length; i++) { encb [i] = b [i - 4]; } linx64Payload += GetByteArrayString(EncryptData(encb, _random.Next(1024).ToString())); } else if (pair.Key.StartsWith("windows/x64")) { byte[] b = response ["payload"] as byte[]; byte[] encb = new byte[b.Length + 4]; encb [0] = parity [0]; encb [1] = parity [1]; encb [2] = parity [2]; encb [3] = parity [3]; for (int i = 4; i < b.Length; i++) { encb [i] = b [i - 4]; } winx64Payload += GetByteArrayString(EncryptData(encb, _random.Next(1024).ToString())); } else /*windows x86*/ { byte[] b = response ["payload"] as byte[]; byte[] encb = new byte[b.Length + 4]; encb [0] = parity [0]; encb [1] = parity [1]; encb [2] = parity [2]; encb [3] = parity [3]; for (int i = 4; i < b.Length; i++) { encb [i] = b [i - 4]; } winx86Payload += GetByteArrayString(EncryptData(encb, _random.Next(1024).ToString())); } } winx64Payload += "};"; winx86Payload += "};"; linx64Payload += "};"; linx86Payload += "};"; //Console.WriteLine (winx64Payload); //Console.WriteLine (winx86Payload); //Console.WriteLine (linx64Payload); //Console.WriteLine (linx86Payload); string par = GetByteArrayString(parity); template = template.Replace("{{parity}}", par.Remove(par.Length - 1)); } } catch { md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Close, "Generating payload failed.\n\nPlease ensure all required (*) options are present and valid.\n\nIf you are sure options are correct, please file a bug."); md.Run(); md.Destroy(); return; } template = template.Replace("{{lin64}}", linx64Payload); template = template.Replace("{{lin86}}", linx86Payload); template = template.Replace("{{win64}}", winx64Payload); template = template.Replace("{{win86}}", winx86Payload); Guid uid = Guid.NewGuid(); CSharpCodeProvider provider = new CSharpCodeProvider(); ICodeCompiler icc = provider.CreateCompiler(); CompilerParameters parms = new CompilerParameters(); parms.GenerateExecutable = true; parms.OutputAssembly = System.IO.Path.GetTempPath() + uid.ToString() + ".exe"; CompilerResults results = icc.CompileAssemblyFromSource(parms, template); // System.Diagnostics.Process process = new System.Diagnostics.Process (); // System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo (); // // startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; // startInfo.FileName = "dmcs"; // startInfo.Arguments = System.IO.Path.GetTempPath () + uid.ToString (); // // process.StartInfo = startInfo; // process.Start (); // // process.WaitForExit (); md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Close, "Your binary is located at: " + System.IO.Path.GetTempPath() + uid.ToString() + ".exe"); md.Run(); md.Destroy(); return; }
private void recentDbList_ButtonPress(object o, ButtonPressEventArgs e) { if (e.Event.Button == 3) { Menu m = new Menu(); MenuItem deleteItem = new MenuItem("Remove"); deleteItem.ButtonPressEvent += new ButtonPressEventHandler(OnDeleteItemButtonPressed); m.Add(deleteItem); m.ShowAll(); m.Popup(); } else if (((Gdk.EventButton)e.Event).Type == Gdk.EventType.TwoButtonPress) { Gtk.TreeIter selected; if (recentDbList.Selection.GetSelected(out selected)) { dbPath = (string)recentDbListStore.GetValue(selected, 1); } if (!File.Exists(dbPath)) { MessageDialog msdSame = new MessageDialog(this, DialogFlags.Modal, MessageType.Warning, ButtonsType.YesNo, false, "The selected database could not be found, delete it from recents?"); ResponseType response = (ResponseType)msdSame.Run(); if (response == ResponseType.Yes) { msdSame.Destroy(); history.Remove(new KeyValuePair <string, string>((string)recentDbListStore.GetValue(selected, 0), (string)recentDbListStore.GetValue(selected, 1))); File.WriteAllText(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "/history.json", JsonConvert.SerializeObject(history, Formatting.Indented)); } else if (response == ResponseType.No || response == ResponseType.DeleteEvent) { msdSame.Destroy(); return; } recentDbListStore.Clear(); history = new List <KeyValuePair <string, string> >(); if (File.Exists(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "/history.json")) { history = JsonConvert.DeserializeObject <List <KeyValuePair <string, string> > >(File.ReadAllText(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "/history.json")); foreach (KeyValuePair <string, string> pair in history) { recentDbListStore.AppendValues(pair.Key, pair.Value); } } return; } db = new Database(dbPath); if (history.Contains(new KeyValuePair <string, string>(db.name, dbPath))) { List <KeyValuePair <string, string> > historyCopy = new List <KeyValuePair <string, string> >(history); historyCopy = historyCopy.ToList(); history = new List <KeyValuePair <string, string> >(); history.Add(historyCopy[historyCopy.IndexOf(new KeyValuePair <string, string>(db.name, dbPath))]); historyCopy.Remove(new KeyValuePair <string, string>(db.name, dbPath)); history.AddRange(historyCopy); File.WriteAllText(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "/history.json", JsonConvert.SerializeObject(history, Formatting.Indented)); } else { history.Add(new KeyValuePair <string, string>(db.name, dbPath)); File.WriteAllText(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "/history.json", JsonConvert.SerializeObject(history, Formatting.Indented)); } this.Hide(); DatabaseOverviewWindow dbo = new DatabaseOverviewWindow(db, dbPath); dbo.Show(); } }
public MainWindow() : base(Gtk.WindowType.Toplevel) { _algorithm.Padding = PaddingMode.None; this.Resize(600, 100); this.Title = "metafang"; _main = new VBox(); HBox title = new HBox(); title.PackStart(new Label("Login to your Metasploit RPC instance to begin"), true, true, 0); _main.PackStart(title, true, true, 0); HBox loginInfo = new HBox(); loginInfo.PackStart(new Label("Host:"), false, false, 20); Entry hostEntry = new Entry(); loginInfo.PackStart(hostEntry, false, false, 0); loginInfo.PackStart(new Label("User:"******"Pass:"******"Login"); login.Clicked += (object sender, EventArgs e) => { try { //Console.WriteLine ("Creating session"); _session = new MetasploitSession(userEntry.Text, passEntry.Text, hostEntry.Text); //Console.WriteLine ("Creating manager and getting current list of payloads"); _manager = new MetasploitManager(_session); _payloads = _manager.GetPayloads(); BuildWorkspace(); } catch (Exception ex) { MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, "Authentication failed. Please ensure your credentials and API URL are correct."); md.Run(); md.Destroy(); } }; HBox loginBox = new HBox(); loginBox.PackStart(login, false, false, 300); _main.PackStart(loginBox, true, true, 0); _main.ShowAll(); this.Add(_main); }
protected void OnButton45Clicked(object sender, EventArgs e) { TcpClient client = new TcpClient(ServerIp, Int32.Parse(TcpPort)); object content = AssignmentChange; Type contentType = AssignmentChange.GetType(); Protocol submitAssignmentChanges = new Protocol(client, ConstValues.PROTOCOL_FN_SAVE_ASSIGNMENT, contentType, content); submitAssignmentChanges.Start(); if ((String)submitAssignmentChanges.ResultObject == "True") { List <Dictionary <String, String> > assignmentList = new List <Dictionary <string, string> > (); TreeIter iter; TreeModel model = treeview6.Model; string agent_id = combobox2.ActiveText.Split(':') [1]; if (model.GetIterFirst(out iter)) { do { Dictionary <String, String> gpuAssign = new Dictionary <string, string> (); gpuAssign.Add("agent_id", agent_id); gpuAssign.Add("resource_ip", model.GetValue(iter, 0).ToString()); gpuAssign.Add("gpu_id", model.GetValue(iter, 1).ToString()); assignmentList.Add(gpuAssign); } while(model.IterNext(ref iter)); } List <String> rCudaClientRuntimeConfig = Configuration.GenerateRcudaClientRuntimeConfig(assignmentList); TcpClient client2 = new TcpClient(ServerIp, Int32.Parse(TcpPort)); object contentConfig = rCudaClientRuntimeConfig; Type contentTypeConfig = rCudaClientRuntimeConfig.GetType(); Protocol uploadRuntimeClientConfig = new Protocol(client2, ConstValues.PROTOCOL_FN_SAVE_RCUDA_CLIENT_CONFIG, contentTypeConfig, contentConfig); uploadRuntimeClientConfig.Start(); if ((String)uploadRuntimeClientConfig.ResultObject == "True") { MessageDialog msg = new MessageDialog(null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "Resource assignment and Runtime Config has been saved"); msg.Response += (o, args) => { if (args.ResponseId == ResponseType.Ok) { combobox2.Sensitive = true; button48.Sensitive = true; button43.Sensitive = false; button44.Sensitive = false; button45.Sensitive = false; button46.Sensitive = false; gpuAssignView = null; AssignmentInProcess = false; combobox2.Active = -1; foreach (var column in treeview6.Columns) { treeview6.RemoveColumn(column); } LoadAllGpuList(); msg.Destroy(); } }; msg.Show(); } else { MessageDialog msg = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Save Runtime Config Failed"); msg.Response += (o, args) => { if (args.ResponseId == ResponseType.Ok) { msg.Destroy(); } }; msg.Show(); } } else { MessageDialog msg = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Updating Resource Assignment Failed"); msg.Response += (o, args) => { if (args.ResponseId == ResponseType.Ok) { msg.Destroy(); } }; msg.Show(); } }
protected void OnPayloadChanged(object o, EventArgs e) { ComboBox combo = (ComboBox)o; TreeIter iter; Dictionary <string, object> opts = null; if (combo.GetActiveIter(out iter)) { opts = _manager.GetModuleOptions("payload", ((ComboBox)o).Model.GetValue(iter, 0).ToString()); } VBox payloadDetails = RedrawOptions(opts, false); HBox addBox = new HBox(); Button addPayload = new Button("Add payload"); addPayload.Clicked += (object sender, EventArgs es) => { TreeIter i; ((ComboBox)o).GetActiveIter(out i); if (_newPayloads.ContainsKey(((ComboBox)o).Model.GetValue(i, 0).ToString())) { MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Close, "Currently support only one of each type of payload.\n\nMultiple payloads of the same type will be supported in the future."); md.Run(); md.Destroy(); return; } int n = _treeViews [_parentNotebook.CurrentPage].Model.IterNChildren(); Dictionary <string, object> newopts = new Dictionary <string, object> (); foreach (Widget child in _dynamicOptions[_parentNotebook.CurrentPage].Children) { if (child is CheckButton) { newopts.Add((child as CheckButton).Label, (child as CheckButton).Active.ToString()); } else if (child is HBox) { foreach (Widget c in (child as HBox).Children) { if (c is Entry) { newopts.Add((c as Entry).TooltipText, (c as Entry).Text); } } } } _newPayloads.Add(((ComboBox)o).Model.GetValue(i, 0).ToString(), newopts); ((ListStore)_treeViews [_parentNotebook.CurrentPage].Model).AppendValues((n + 1).ToString(), ((ComboBox)o).Model.GetValue(i, 0).ToString()); CellRendererText tx = new CellRendererText(); _treeViews [_parentNotebook.CurrentPage].Columns [1].PackStart(tx, true); _treeViews [_parentNotebook.CurrentPage].ShowAll(); }; addBox.PackStart(addPayload, false, false, 0); payloadDetails.PackStart(addBox, false, false, 0); payloadDetails.ShowAll(); this.Resize(payloadDetails.Allocation.Width + (800 - payloadDetails.Allocation.Width), payloadDetails.Allocation.Height + (600 - payloadDetails.Allocation.Height)); }
private Semaphore threadMutex = new Semaphore(1, 1); //Ensure that only one operation is started at the same time //private event NoParamDelegate ThreadNotStarted; // This event is signaled if a background thread couldn't be started because another one is runniung private void SpawnThread(NoParamDelegate action, bool showPendingError = true, int wait = 500) { Thread t = new Thread( new ThreadStart( delegate() { if (threadMutex.WaitOne(wait)) { try { Gtk.Application.Invoke(delegate { replyStatusbar.Pop(1); ShowConnectIcon(); }); action(); } catch (MonoBrickException e) { Gtk.Application.Invoke(delegate { if (e is MonoBrickException) { ShowWarningIcon(); } else { ShowErrorIcon(); } replyStatusbar.Pop(1); replyStatusbar.Push(1, e.Message); }); if (e is ConnectionException) { brick.Connection.Close(); } } catch (Exception e) { Gtk.Application.Invoke(delegate { MessageDialog md = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "\n" + e.Message); md.Icon = global::Gdk.Pixbuf.LoadFromResource(MessageDialogIconName); md.Run(); md.WindowPosition = Gtk.WindowPosition.CenterOnParent; md.Destroy(); }); } finally { threadMutex.Release(); } } else { if (showPendingError) { Gtk.Application.Invoke(delegate { MessageDialog md = new MessageDialog(this, DialogFlags.Modal, MessageType.Error, ButtonsType.Close, "\nUnable to send command to NXT.\nAnother command is pending"); md.Icon = global::Gdk.Pixbuf.LoadFromResource(MessageDialogIconName); md.WindowPosition = Gtk.WindowPosition.CenterOnParent; md.Run(); md.Destroy(); }); } } } )); t.IsBackground = true; t.Priority = ThreadPriority.AboveNormal; t.Start(); }
protected VBox RedrawOptions(Dictionary <string, object> opts, bool mine) { VBox payloadDetails = _dynamicOptions [_parentNotebook.CurrentPage]; foreach (Widget widget in payloadDetails.Children) { payloadDetails.Remove(widget); } if (!mine) { foreach (var opt in opts) { string optName = opt.Key as string; string type = string.Empty; string defolt = string.Empty; bool required = false; string advanced = string.Empty; string evasion = string.Empty; string desc = string.Empty; string enums = string.Empty; foreach (var optarg in opt.Value as Dictionary <string, object> ) { switch (optarg.Key) { case "default": defolt = optarg.Value.ToString(); break; case "type": type = optarg.Value.ToString(); break; case "required": required = bool.Parse(optarg.Value.ToString()); break; case "advanced": advanced = optarg.Value.ToString(); break; case "evasion": evasion = optarg.Value.ToString(); break; case "desc": desc = optarg.Value.ToString(); break; case "enums": enums = optarg.Value.ToString(); break; default: MessageDialog md = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Close, "Don't know argument: " + optarg.Key + ". Please file a bug report with this information."); md.Run(); md.Destroy(); break; } } payloadDetails.PackStart(CreateWidget(optName, type, defolt, desc, advanced == string.Empty), false, false, 0); } } else { foreach (var opt in opts) { bool wut; payloadDetails.PackStart(CreateWidget(opt.Key, (bool.TryParse(opt.Value.ToString(), out wut) ? "bool" : "string"), opt.Value as string, "", false), false, false, 0); } } return(payloadDetails); }
public StudentAddCompletedWindow(User user, TextViewList textviews, string Filename) : base("Upload Completed Assignment") { this.user = user; this.textviews = textviews; this.Filename = Filename; SetDefaultSize(300, 300); List <MetaType> metaTypeList = new List <MetaType>(); // Packs the file into a single string foreach (Widget w in this.textviews) { if (w is MovableCasCalcView) { MetaType metaType = new MetaType(); MovableCasCalcView calcView = (MovableCasCalcView)w; metaType.type = typeof(MovableCasCalcView); metaType.metastring = calcView.calcview.input.Text; metaType.locked = calcView.textview.locked; metaTypeList.Add(metaType); } else if (w is MovableCasCalcMulitlineView) { MetaType metaType = new MetaType(); MovableCasCalcMulitlineView calcview = (MovableCasCalcMulitlineView)w; metaType.type = typeof(MovableCasCalcMulitlineView); metaType.metastring = calcview.calcview.SerializeCasTextView(); metaType.locked = calcview.textview.locked; metaTypeList.Add(metaType); } else if (w is MovableCasResult) { MetaType metaType = new MetaType(); MovableCasResult casres = (MovableCasResult)w; metaType.type = typeof(MovableCasResult); metaType.metastring = Export.Serialize(casres.casresult.facitContainer); metaType.locked = casres.textview.locked; metaTypeList.Add(metaType); } else if (w.GetType() == typeof(MovableCasTextView)) { MetaType metaType = new MetaType(); MovableCasTextView textView = (MovableCasTextView)w; metaType.type = typeof(MovableCasTextView); metaType.metastring = textView.textview.SerializeCasTextView(); metaType.locked = textView.textview.locked; metaTypeList.Add(metaType); } } if (metaTypeList.Count != 0 && !string.IsNullOrEmpty(this.Filename)) { string serializedString = ImEx.Export.Serialize(metaTypeList); this.user.student.AddCompleted(serializedString, this.Filename); MessageDialog ms = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Info, ButtonsType.Close, "Upload Successful"); ms.Run(); ms.Destroy(); } else { MessageDialog ms = new MessageDialog(this, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Close, "Upload failed"); ms.Run(); ms.Destroy(); } Destroy(); }
private void _screenRecorder_Completed(object sender, ScreenRecordCompletedEventArgs e) { Gtk.Application.Invoke(delegate { FileInfo info = new FileInfo(e.FileName); elapsedLabel.Text = _screenRecorder.Elapsed.ToString("c"); fileSizeLabel.Text = GetFileSize(info.Length); recordStopBtn.Label = "Record"; if (uploadOnStop.Active) { switch (_uploader.CheckRequirementStatus(e.FileName)) { case UploadRequirementStatus.Success: { UploadDialog dialog = new UploadDialog(_uploader, e.FileName); dialog.Run(); } break; case UploadRequirementStatus.FileNotFound: { string msg = string.Format("The file \"{0}\" was not found", e.FileName); MessageDialog dialog = new MessageDialog( this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, msg ); dialog.Run(); dialog.Destroy(); } break; case UploadRequirementStatus.FileNull: { MessageDialog dialog = new MessageDialog( this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "File not set" ); dialog.Run(); dialog.Destroy(); } break; case UploadRequirementStatus.FileTooLarge: { string msg = string.Format( "{0} service can upload files up to {1}, but the file {2} has a size of {3} which exceeds the service limit.", _uploader.Name, GetFileSize(_uploader.MaxFileSize), e.FileName, GetFileSize(info.Length) ); MessageDialog dialog = new MessageDialog( this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, msg ); dialog.Run(); dialog.Destroy(); } break; default: { throw new Exception("Unknown requirement"); } } } else { string msg = string.Format( "File location:{0}{0}{1}", Environment.NewLine, e.FileName ); MessageDialog dialog = new MessageDialog( this, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, msg ); dialog.Run(); dialog.Destroy(); } }); }
protected void OnRecordStopBtnClicked(object sender, EventArgs e) { Gtk.Application.Invoke(delegate { if (_screenRecorder.Recording) { _screenRecorder.FinishAsync(); } else { try { Directory.CreateDirectory(_settings.Recordings.Folder); string fileName = System.IO.Path.Combine( _settings.Recordings.Folder, string.Format( "{0}{1}", Guid.NewGuid().ToString("N"), ".gif" ) ); try { using (FileStream fs = File.Create(fileName)) { } recordStopBtn.Label = "Stop"; _screenRecorder.StartAsync(fileName, true); } catch { MessageDialog dialog = new MessageDialog( this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, string.Format("Cannot create the file {0}", fileName) ); dialog.Run(); dialog.Destroy(); } } catch { MessageDialog dialog = new MessageDialog( this, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, string.Format("Cannot create directory {0}", _settings.Recordings.Folder) ); dialog.Run(); dialog.Destroy(); } } }); }
protected void onClickBtnAddService(object sender, EventArgs e) { if (combocourse.Active == 0 || comboins.Active == 0 || comboveh.Active == 0 || comboclient.Active == 0) { var ms = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Todos los campos son requeridos!!!"); ms.Run(); ms.Destroy(); } else { var nameCourse = this.combocourse.ActiveText; var nameIns = this.comboins.ActiveText; var nameVeh = this.comboveh.ActiveText; var nameClien = this.comboclient.ActiveText; foreach (KeyValuePair <string, int> name in namesAndID) { if (nameCourse == name.Key) { tbinscour.Id_course = name.Value; } } foreach (KeyValuePair <string, int> name in namesAndIdInstructor) { if (nameIns == name.Key) { tbinscour.Id_instructor = name.Value; } } foreach (KeyValuePair <string, int> name in namesAndIdVeh) { if (nameVeh == name.Key) { tbinscour.Id_vehicle = name.Value; } } foreach (KeyValuePair <string, int> name in namesAndIdClient) { if (nameClien == name.Key) { tbinscour.Id_customer = name.Value; } } //tbinscour.Id_instructor = this.comboins.Active; //tbinscour.Id_vehicle = this.comboveh.Active; //tbinscour.Id_customer = this.comboveh.Active; tbinscour.Start_date = calenIni.GetDate().ToString("yyyy-MM-dd HH:mm:ss"); tbinscour.End_date = calenEnd.GetDate().ToString("yyyy-MM-dd HH:mm:ss"); //createDialog(dateString); //dtservice.getIdcourse(this.combocourse.ActiveText); ///tservices.State = dtservice.getIdstate(this.combostate.ActiveText); if (bscourseOperating.BSsaveCourseOperating(tbinscour)) { var ms = new MessageDialog(null, DialogFlags.Modal, MessageType.Info, ButtonsType.Ok, "Se guardo el servicio con exito!!!"); ms.Run(); ms.Destroy(); //CleanEntries(); } else { var ms = new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, "Revise los datos e intente nuevamente!!!"); ms.Run(); ms.Destroy(); this.combocourse.GrabFocus(); } } }