Ya tenemos lista la ventana principal ahora tenemos que empezar a crear las ventanas internas del programa, para empezar vamos a crear una carpeta en la cual estarán todas las formas que se llamara formas
Etiqueta: Programación

Ahora solo queda hacer la función para generar automáticamente el código HTML/PHP para la vista del catalogo en base a la nueva tabla.
La lógica es igual solo que es otro texto

Insertamos el siguiente codigo
' Gambas module file
Public Function creaVista() As String
Dim strVista As String
Dim conexion As New Connection
Dim strDatos As String
With conexion
.Type = "mysql"
.Port = "3306"
.Host = Settings["servidor"]
.User = Settings["usuario"]
.Password = Settings["password"]
.Name = Settings["baseDeDatos"]
.Open()
End With
Dim $result As Result
Dim $resultClases As Result
Dim strLLavePrimaria As String
$result = conexion.Exec("SHOW KEYS FROM " & FMain.txtTabla.Text & " WHERE Key_name = 'PRIMARY'")
strLLavePrimaria = $result["Column_name"]
conexion.Exec("delete from clases where clase= 'controladores/" & FMain.txtTabla.Text & ".controlador.php'")
conexion.Exec("delete from clases where clase= 'modelos/" & FMain.txtTabla.Text & ".modelo.php'")
conexion.Exec("insert into clases(clase) values('controladores/" & FMain.txtTabla.Text & ".controlador.php')")
conexion.Exec("insert into clases(clase) values( 'modelos/" & FMain.txtTabla.Text & ".modelo.php')")
$result = conexion.Exec("describe " & FMain.txtTabla.Text)
$result = conexion.Exec("describe " & FMain.txtTabla.Text)
Dim contador As Integer
Dim strEncabezadosTabla As String
Dim strCampos As String
Dim strControlesNuevos As String
Dim strControlesEditar As String
Dim strEditarJS As String
Dim strBloquear As String
Dim strEditarTraeDatos As String
contador = 0
strEncabezadosTabla = ""
strCampos = ""
strControlesNuevos = ""
strEditarJS = ""
While $result.Length > contador
strEncabezadosTabla &= "<th>" & utilerias.strPrimeraMayuscula($result["Field"]) & "</th>" & gb.CrLf
strCampos &= "<td>'.$value[\"" & $result["Field"] & "\"].'</td>" & gb.CrLf
If contador > 0
strControlesNuevos &= "" & " <!-- ENTRADA PARA " & UCase($result["Field"]) & " --> " & gb.CrLf
strControlesNuevos &= "" & " " & gb.CrLf
strControlesNuevos &= "" & " <div class=\"form-group\"> " & gb.CrLf
strControlesNuevos &= "" & " " & gb.CrLf
strControlesNuevos &= "" & " <div class=\"input-group\"> " & gb.CrLf
strControlesNuevos &= "" & " " & gb.CrLf
strControlesNuevos &= "" & " <span class=\"input-group-addon\">" & utilerias.strPrimeraMayuscula($result["Field"]) & ": </span> " & gb.CrLf
strControlesNuevos &= "" & " " & gb.CrLf
strControlesNuevos &= "" & " <input type=\"text\" class=\"form-control input-lg\" name=\"nuevo" & utilerias.strPrimeraMayuscula($result["Field"]) & "\" placeholder=\"Ingresar " & utilerias.strPrimeraMayuscula($result["Field"]) & "\" required> " & gb.CrLf
strControlesNuevos &= "" & " " & gb.CrLf
strControlesNuevos &= "" & " </div> " & gb.CrLf
strControlesNuevos &= "" & " " & gb.CrLf
strControlesNuevos &= "" & " </div> " & gb.CrLf
strEditarJS &= "" & " $(\"#editarDescripcion\").val(respuesta[\"descripcion\"]);" & gb.CrLf
End If
If $result["Key"] == "PRI"
strBloquear = "readonly"
Else
strBloquear = ""
End If
strControlesEditar &= "" & " <!-- ENTRADA PARA " & UCase($result["Field"]) & " --> " & gb.CrLf
strControlesEditar &= "" & " " & gb.CrLf
strControlesEditar &= "" & " <div class=\"form-group\"> " & gb.CrLf
strControlesEditar &= "" & " " & gb.CrLf
strControlesEditar &= "" & " <div class=\"input-group\"> " & gb.CrLf
strControlesEditar &= "" & " " & gb.CrLf
strControlesEditar &= "" & " <span class=\"input-group-addon\">" & utilerias.strPrimeraMayuscula($result["Field"]) & ": </span> " & gb.CrLf
strControlesEditar &= "" & " " & gb.CrLf
strControlesEditar &= "" & " <input " & strBloquear & " type=\"text\" class=\"form-control input-lg\" id=\"editar" & utilerias.strPrimeraMayuscula($result["Field"]) & "\" name=\"editar" & utilerias.strPrimeraMayuscula($result["Field"]) & "\" placeholder=\"Ingresar " & utilerias.strPrimeraMayuscula($result["Field"]) & "\" required> " & gb.CrLf
strControlesEditar &= "" & " " & gb.CrLf
strControlesEditar &= "" & " </div> " & gb.CrLf
strControlesEditar &= "" & " " & gb.CrLf
strControlesEditar &= "" & " </div> " & gb.CrLf
strEditarTraeDatos &= "" & " $(\"#editar" & utilerias.strPrimeraMayuscula($result["Field"]) & "\").val(respuesta[\"" & $result["Field"] & "\"]); " & gb.CrLf
$result.MoveNext
contador = contador + 1
Wend
strControlesEditar &= "" & " <input type=\"hidden\" id=\"editar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.text) & "\" name = \"editar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.text) & "\" > " & gb.CrLf
strEncabezadosTabla &= "<th>Acciones</th>"
strCampos &= "<td> " & gb.CrLf
strCampos &= "<div class = \"btn-group\"> " & gb.CrLf
strCampos &= " <button class= \"btn btn-warning btnEditar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\" id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.text) & " = \"'.$value[\"id\"].'\" data-toggle = \"modal\" data-target = \"#modalEditar" & Trim(utilerias.strPrimeraMayuscula(FMain.txtTabla.Text)) & "\"> <i class = \"fa fa-pencil\"> </i> </button> " & gb.CrLf
strCampos &= "<button class = \"btn btn-danger btnEliminar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\" id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "= \"'.$value[\"id\"].'\"><i class= \"fa fa-times\"></i></button>" & gb.CrLf
strCampos &= "</div>" & gb.CrLf
strCampos &= "</td> " & gb.CrLf
strVista &= "" & "<?php" & gb.CrLf
strVista &= "" & gb.CrLf
strVista &= "" & "if(\"off\" == \"offf\"){" & gb.CrLf
strVista &= "" & gb.CrLf
strVista &= "" & " echo '<script>" & gb.CrLf
strVista &= "" & gb.CrLf
strVista &= "" & " window.location = \"inicio\"; " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </script>'; " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " return; " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "} " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "?> " & gb.CrLf
strVista &= "" & "<div class=\"content-wrapper\">" & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <section class=\"content-header\">" & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <h1> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " Administrar <?php echo mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & " ')); ?> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </h1> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <ol class=\"breadcrumb\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <li><a href=\"inicio\"><i class=\"fa fa-dashboard\"></i> Inicio</a></li> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <li class=\"active\">Administrar <?php echo mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', '" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & " ')); ?></li> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </ol> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </section> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <section class=\"content\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"box\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"box-header with-border\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <button class=\"btn btn-primary\" data-toggle=\"modal\" data-target=\"#modalAgregar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " Agregar <?php echo mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', '" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & " ')); ?> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </button> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"box-body\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <table class=\"table table-bordered table-striped dt-responsive tablas\" width=\"100%\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <thead> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <tr> " & gb.CrLf
strVista &= "" & " " & strEncabezadosTabla
strVista &= "" & " </tr> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </thead> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <tbody> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <?php " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " $item = null; " & gb.CrLf
strVista &= "" & " $valor = null; " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " $" & FMain.txtTabla.Text & "= Controlador" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "::ctrMostrar($item, $valor); " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " foreach ($" & FMain.txtTabla.Text & " as $key => $value){ " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " echo ' <tr> " & gb.CrLf
strVista &= "" & strCampos & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </tr>'; " & gb.CrLf
strVista &= "" & " } " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " ?> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </tbody> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </table> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </section> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "</div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "<!--===================================== " & gb.CrLf
strVista &= "" & "MODAL <?php echo mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & (FMain.txtTabla.Text) & " ')); ?> " & gb.CrLf
strVista &= "" & " ======================================--> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "<div id=\"modalAgregar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.text) & "\" class=\"modal fade\" role=\"dialog\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"modal-dialog\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"modal-content\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <form role=\"form\" method=\"post\" enctype=\"multipart/form-data\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <!--===================================== " & gb.CrLf
strVista &= "" & " CABEZA DEL MODAL " & gb.CrLf
strVista &= "" & " ======================================--> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"modal-header\" style=\"background:#3c8dbc; color:white\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <h4 class=\"modal-title\">Agregar <?php echo mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & (FMain.txtTabla.Text) & " ')); ?> </h4> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " <!--===================================== " & gb.CrLf
strVista &= "" & " CUERPO DEL MODAL " & gb.CrLf
strVista &= "" & " ======================================--> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"modal-body\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"box-body\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
'strVista &= "" & " <!-- ENTRADA PARA DESCRIPCION --> " & gb.CrLf
strVista &= "" & " " & strControlesNuevos & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <!--===================================== " & gb.CrLf
strVista &= "" & " PIE DEL MODAL " & gb.CrLf
strVista &= "" & " ====================================== --> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"modal-footer\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <button type=\"button\" class=\"btn btn-default pull-left\" data-dismiss=\"modal\">Salir</button> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <button type=\"submit\" class=\"btn btn-primary\">Guardar</button> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <?php " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " $crear = new Controlador" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "(); " & gb.CrLf
strVista &= "" & " $crear ->ctrIngresar(); " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " ?> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </form> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "</div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "<!--===================================== " & gb.CrLf
strVista &= "" & "MODAL EDITAR USUARIO " & gb.CrLf
strVista &= "" & " ======================================--> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "<div id=\"modalEditar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\" class=\"modal fade\" role=\"dialog\">" & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"modal-dialog\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"modal-content\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <form role=\"form\" method=\"post\" enctype=\"multipart/form-data\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <!--===================================== " & gb.CrLf
strVista &= "" & " CABEZA DEL MODAL " & gb.CrLf
strVista &= "" & " ======================================--> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"modal-header\" style=\"background:#3c8dbc; color:white\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <button type=\"button\" class=\"close\" data-dismiss=\"modal\">×</button> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <h4 class=\"modal-title\">Agregar <?php echo mb_strtolower(preg_replace('/(?<=\\w)(\\p{Lu})/u', ' $1', ' " & (FMain.txtTabla.Text) & " ')); ?> </h4> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <!--===================================== " & gb.CrLf
strVista &= "" & " CUERPO DEL MODAL " & gb.CrLf
strVista &= "" & " ======================================--> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"modal-body\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"box-body\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <!-- ENTRADA PARA DESCRIPCION --> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & strControlesEditar
strVista &= "" & " " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <!--===================================== " & gb.CrLf
strVista &= "" & " PIE DEL MODAL " & gb.CrLf
strVista &= "" & " ======================================--> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <div class=\"modal-footer\"> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <button type=\"button\" class=\"btn btn-default pull-left\" data-dismiss=\"modal\">Salir</button> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <button type=\"submit\" class=\"btn btn-primary\">Modificar</button> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " <?php " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " $editar = new Controlador" & utilerias.strPrimeraMayuscula(FMain.txtTabla.text) & "(); " & gb.CrLf
strVista &= "" & " $editar ->ctrEditar(); " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " ?> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </form> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " </div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "</div> " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "<?php " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " $borrar = new Controlador" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "(); " & gb.CrLf
strVista &= "" & " $borrar ->ctrBorrar(); " & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "?> " & gb.CrLf
'JAVASCRIPT FUNCIONES
strVista &= "" & "<script type=\"text/javascript\">" & gb.CrLf
'ELIMINAR
strVista &= "" & "/*= == == == == == == == == == == == == == == == == == == == == == ==" & gb.CrLf
strVista &= "" & " ELIMINAR " & UCase(FMain.txtTabla.Text) & gb.CrLf
strVista &= "" & " == == == == == == == == == == == == == == == == == == == == == == = */" & gb.CrLf
strVista &= "" & "$(\".tablas\").on(\"click\", \".btnEliminar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\", function() {" & gb.CrLf
strVista &= "" & " var id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & " = $(this).attr(\"id" & FMain.txtTabla.Text & "\");" & gb.CrLf
strVista &= "" & " swal( {" & gb.CrLf
strVista &= "" & " title: '¿Está seguro de borrar?'," & gb.CrLf
strVista &= "" & " text: \"¡Si no lo está puede cancelar la accíón!\"," & gb.CrLf
strVista &= "" & " type: 'warning'," & gb.CrLf
strVista &= "" & " showCancelButton: true," & gb.CrLf
strVista &= "" & " confirmButtonColor: '#3085d6'," & gb.CrLf
strVista &= "" & " cancelButtonColor: '#d33'," & gb.CrLf
strVista &= "" & " cancelButtonText: 'Cancelar'," & gb.CrLf
strVista &= "" & " confirmButtonText: 'Si, borrar!'" & gb.CrLf
strVista &= "" & " }).then(function(result) {" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & " if (result.value) {" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & " window.location = \"index.php?ruta=" & (FMain.txtTabla.Text) & "&id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "=\"+id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "+\"&borrar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "=borrar\";" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & " }" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & " })" & gb.CrLf
strVista &= "" & "})" & gb.CrLf
'editar
strVista &= "" & "/* = == == == == == == == == == == == == == == == == == == == == == ==" & gb.CrLf
strVista &= "" & " EDITAR " & gb.CrLf
strVista &= "" & " == == == == == == == == == == == == == == == == == == == == == == = */" & gb.CrLf
strVista &= "" & "$(\".tablas\").on(\"click\", \".btnEditar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\", function() {" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & " var id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & " = $(this).attr(\"id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\");" & gb.CrLf
strVista &= "" & " console.log(id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & ");"
strVista &= "" & "" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & " var datos = new FormData();" & gb.CrLf
strVista &= "" & " datos.append(\"id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\", id" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "); " & gb.CrLf
strVista &= "" & " datos.append(\"buscar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\", \"buscar" & utilerias.strPrimeraMayuscula(FMain.txtTabla.Text) & "\");" & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & " $.ajax( {" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & " url:\"controladores/" & FMain.txtTabla.text & ".controlador.php\"," & gb.CrLf
strVista &= "" & " method:\"POST\"," & gb.CrLf
strVista &= "" & " data: datos," & gb.CrLf
strVista &= "" & " cache: false," & gb.CrLf
strVista &= "" & " contentType: false," & gb.CrLf
strVista &= "" & " processData: false," & gb.CrLf
strVista &= "" & " dataType:\"json\"," & gb.CrLf
strVista &= "" & " success: function(respuesta) {" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & strEditarTraeDatos & gb.CrLf
strVista &= "" & " " & gb.CrLf
strVista &= "" & " }" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & " });" & gb.CrLf
strVista &= "" & "" & gb.CrLf
strVista &= "" & "})" & gb.CrLf
strVista &= "" & "</script>" & gb.CrLf
Return strVista
End
En la siguiente publicación veremos como generar los archivos modelos/vista/Controlador al darle click al botón Crear Catalogo

En el diseño ya tenemos el menú, ahora nos toca insertar los controles que vamos a necesitar.
Se usaran los mas básicos que son el textbox, dir chooser y button









En la próxima publicación crearemos la ventana de configuración donde meteremos los parámetros para acceder a la base de datos de MySQL y mostraremos como lanzarlo desde el

En toda la comunidad libre de GNU/Linux nos encontramos herramientas que nos permiten hacer nuestro trabajado cómodamente ya sea office, edición de vídeo, edición de fotografía y en nuestro caso en el desarrollo de aplicaciones.
Mucho hemos hablado sobre el desarrollo en PHP, pero que hay del desarrollo rápido de aplicaciones RAD, que nos sirve para crear herramientas rápidas sin gastar mucho tiempo.
En el caso de Windows tenemos Visual Basic, poderosa herramienta que nos permite crear aplicaciones sencillas en un corto periodo de tiempo.
GNU/Linux no se queda atrás y tenemos Gambas3, cuyas bondades al igual que Visual Basic nos permite entre otras cosas lo siguiente:

INTRODUCCIÓN
Hace algunos días desarrollamos una aplicación en Java el cual tiene como función
principal generar un archivo PDF con la información del XML de la
factura que se generan aquí en México, actualmente van en la
versión 3.3 y este programa es para esa versión.
Pero a lo mas que logramos
hacer es ejecutar dentro de una carpeta el programa con un archivo
.sh, sin instalarlo como se debe.
Ahora queremos que nuestro
programa sea mas profesional y se instale en nuestro sistema
operativo con todo y los iconos en el menú listo para funcionar en cualquier sistema basado en debían y que se ejecute sin problemas,
de manera que el usuario no necesite hacer ajustes.
OBJETIVO
Crear el instalador de un programa escrito en Java con su icono en el menú y que funcione sin necesidad de usar la terminal.
CONOCIMIENTOS PREVIOS
Es necesario conocer los directorios en los que vamos a instalar, de hecho primeramente vamos instalarlo en el sistema de archivos.

nos vamos a la raíz de disco duro donde tenemos instalado vemos que
tenemos la carpetas OPT y USR .
En la carpeta OPT
guardamos normalmente los programas de terceros auto contenidos, es
el equivalente a archivos de programa de Windows.
URS
aquí van archivos relativos al
programa como los iconos que estos están dentro de una carpeta que
se llama Applications,
ademas aquí meteremos una carpeta llamada XMLAPDF
donde vendrán los reportes y nuestro archivo de base de datos, como
vamos hacer lectura y escritura de ese archivo dejamos esa carpeta
con acceso a lectura y escritura.
Archivos Carpeta OPT
Vamos
a meter nuestro ejecutable jar
con su carpeta lib en
una carpeta con el nombre de la aplicación dentro de la carpeta OPT
y para no tener problemas
con la versión de JAVA
que podría tener instalado el sistema operativo, nosotros mismos
agregaremos el jdk,
así nos ahorramos cualquier problema de incompatibilidad.
El jdk que utilizaremos
para este programa lo pueden descargar desde nuestra nube de Telegram
haciendo clic aquí.
Ahora
creamos el archivo llamado ejecutar.sh ,
este ejecutara el programa a través de jdk , dentro de ejecutar.sh
tendremos el siguiente comando
/opt/ConvertidorXMLPDF/jdk/bin/java
-jar /opt/ConvertidorXMLPDF/LeerXML.jar
Igual puede descargar el
archivo completo haciendo clic aquí

final esa carpeta nos quedaría así
Ahora le tenemos que crear un
acceso directo a ejecutar.sh dentro de la carpeta usr/bin
para que lo ejecute con los
máximos derechos, eso he
escuchado, por lo que entiendo es para que no requiera ejecutarlo
como sudo en la terminal.
sudo
ln -sf /opt/ConvertidorXMLPDF/ejecutar.sh /usr/bin/ConversorXML
Lanzador
con icono

un archivo de texto con el siguiente contenido, vemos como tomar el
icono de la carpeta que tenemos en OPT. Este archivo lo dejáramos en
la carpeta /usr/share/applications/
Ahora hacemos la prueba y si
nos vamos al menú y lo buscamos como Convertidor ya nos debe salir y
si le damos clic ya podremos ejecutar el programa.
Si el programa ya se ejecuta
correctamente ahora sigue el empaquetado.
CREANDO
EL INSTALADOR .DEB
Ahora lo que sigue es crear una carpeta con el nombre de la aplicación que ustedes preferían ponerle en mi caso le pondré ConvertidorXMLPDF Y allí meteremos todos los archivos que hemos creado con la misma ruta.
Ejemplo lo que metimos en OPT, agregaremos la carpeta OPT y metemos allí los archivos.
Ojo solo los archivos que hemos creado nosotros, no vallan a copiar toda la carpeta de OPT Igual hacer con la carpeta de USR donde tenemos la carpeta de trabajo XMLAPDF, el lanzador y el archivo que dejamos en la carpeta bin Igual crearemos una carpeta llamada DEBIAN y dentro de ella meteremos un archivo con el nombre control así sin extención.
Para que se puedan dar una idea es así como quedarían los archivos.


Se ve difícil pero en realidad es sencillo, en el video mostraremos como hacerlo. Ahora procederemos a crear el archivo .DEB Para ello nos vamos a la terminal y ubicamos la carpeta que hemos hecho, y la generamos con el siguiente comando
dpkg –build ConvertidorXMLPDF


podemos abrir el paquete para instalarlo
Bienvenidos sean otra vez a este post, lo que hoy se vendrá a explicar sera la manera de como conectar, enlazar, ligar un programa escrito en Java, lógicamente desde el código fuente, a una base de datos MySQL 5.6.X
La versión del MySQL es la versión que viene en la instalación de XAMPP 5.6.11.
Primeramente tendrán que instalar el MySQL, cualquiera de estos videomanuales te pueden servir, uno es para Linux Mint 17.2 Rafaela y otro es para la versión de Windows 10.
Instalación Windows 10
[youtube https://www.youtube.com/watch?v=7oFXfcPP9CE]
Instalación Linux Mint 17.2
[youtube https://www.youtube.com/watch?v=8yuUw0V7jz0]
Una vez instalado el servidor SQL procederemos a levantar la base de datos
[code languaje=”sql”]
— phpMyAdmin SQL Dump
— version 4.4.12
— http://www.phpmyadmin.net
—
— Servidor: localhost
— Tiempo de generación: 12-10-2015 a las 05:06:49
— Versión del servidor: 5.6.25
— Versión de PHP: 5.6.11
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
—
— Base de datos: `INVEN`
—
CREATE DATABASE IF NOT EXISTS `INVEN` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `INVEN`;
DELIMITER $$
—
— Procedimientos
—
DROP PROCEDURE IF EXISTS `sp_InsertaCliente`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_InsertaCliente`(in Nombres VARCHAR(200)
, Apellidos VARCHAR(200),Direccion varchar(200),Ciudad varchar(200)
,Telefono varchar(200),RFC VARCHAR(10),FechaNacimiento VARCHAR(200),Estado VARCHAR(200)
,Municipio varchar(200),CodigoPostal VARCHAR(200))
BEGIN
INSERT INTO `Clientes`
(
`Nombres`,
`Apellidos`,
`Direccion`,
`Ciudad`,
`Telefono`,
`RFC`,
`FechaNacimiento`,
`Estado`,
`Municipio`,
`CodigoPostal`
)
VALUES
(
Nombres,
Apellidos,
Direccion,
ciudad,
Telefono,
RFC,
FechaNacimiento,
Estado,
Municipio,
CodigoPostal
);
END$$
DELIMITER ;
— ——————————————————–
—
— Estructura de tabla para la tabla `Clientes`
—
DROP TABLE IF EXISTS `Clientes`;
CREATE TABLE IF NOT EXISTS `Clientes` (
`idCliente` bigint(20) NOT NULL,
`Nombres` varchar(100) DEFAULT NULL,
`Apellidos` varchar(45) DEFAULT NULL,
`Direccion` varchar(45) DEFAULT NULL,
`Ciudad` varchar(45) DEFAULT NULL,
`Telefono` varchar(45) DEFAULT NULL,
`RFC` varchar(45) DEFAULT NULL,
`FechaNacimiento` datetime(6) DEFAULT NULL,
`Estado` varchar(45) DEFAULT NULL,
`Municipio` varchar(45) DEFAULT NULL,
`CodigoPostal` varchar(45) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=latin1;
—
— Volcado de datos para la tabla `Clientes`
—
[/code]
Ya levantada la base de datos tendremos que agregar la siguiente librería para conectar MySQL mysql-connector-java-5.1.6-bin.jar, la agregamos de igual modo que hemos estado agregando librerías en los post anteriores.
Bien ya agregada la librería creamos la siguiente clase
[code languaje=”Java”]
/*
Clase conexión, recibe la información de la conexión y se conecta
*/
package herramientas;
import java.sql.*;
import javax.swing.JOptionPane;
public class conexion {
public static String strServidor= new String();
public static String strBaseDeDatos=new String();
public static String strUsuarioSQL=new String();
public static String strPSWSQL=new String();
Connection conexion= null;
public Connection conectado(){
try{
Class.forName("com.mysql.jdbc.Driver");
conexion = DriverManager.getConnection("jdbc:mysql://"+ this.strServidor +"/" +this.strBaseDeDatos + "?user="+this.strUsuarioSQL + "&password="+ this.strPSWSQL);
Statement stm = conexion.createStatement();
}
catch(SQLException e)
{
JOptionPane.showMessageDialog(null, "ERROR DE CONEXIÓN"+e);
}
catch(ClassNotFoundException e)
{
JOptionPane.showMessageDialog(null, e);
}
return conexion;
}
public void desconectar(){
conexion = null;
System.out.println("conexion terminada");
}
}
[/code]
Luego al usar la clase conexión, lo haríamos de la siguiente forma
[code languaje=”Java”]
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package interfaces;
import clases.classUsuarios;
//AQUI ES DONDE TENEMOS LA CLASE CONEXION
import herramientas.conexion;
import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.jar.Attributes;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.*;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* @author julio
*/
public class frmLogueo extends javax.swing.JFrame {
/**
* Creates new form frmLogueo
*/
public frmLogueo() {
initComponents();
leerConfiguracion();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
lblServidor = new javax.swing.JLabel();
txtServer = new javax.swing.JTextField();
lblUsuario = new javax.swing.JLabel();
txtUsuario = new javax.swing.JTextField();
lblContraseña = new javax.swing.JLabel();
cmdAccesar = new javax.swing.JButton();
pswContraseña = new javax.swing.JPasswordField();
lblBase = new javax.swing.JLabel();
txtBase = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setAlwaysOnTop(true);
setLocationByPlatform(true);
setResizable(false);
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/padlock.jpg"))); // NOI18N
lblServidor.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
lblServidor.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblServidor.setText("SERVIDOR");
lblServidor.setToolTipText("");
lblUsuario.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
lblUsuario.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblUsuario.setText("USUARIO");
lblContraseña.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
lblContraseña.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblContraseña.setText("CONTRASEÑA");
cmdAccesar.setText("ACCESO");
cmdAccesar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cmdAccesarActionPerformed(evt);
}
});
lblBase.setFont(new java.awt.Font("Arial", 1, 14)); // NOI18N
lblBase.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
lblBase.setText("BASE DE DATOS");
lblBase.setToolTipText("");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(129, 129, 129)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(lblServidor, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(txtUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(lblUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(pswContraseña)
.addComponent(txtServer, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(lblContraseña, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblBase, javax.swing.GroupLayout.DEFAULT_SIZE, 138, Short.MAX_VALUE)
.addComponent(txtBase)))
.addGroup(layout.createSequentialGroup()
.addGap(114, 114, 114)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(123, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(140, 140, 140)
.addComponent(cmdAccesar, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(156, Short.MAX_VALUE)))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addGap(30, 30, 30)
.addComponent(lblServidor)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblBase)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtBase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
.addComponent(lblUsuario)
.addGap(12, 12, 12)
.addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(lblContraseña)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(pswContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(93, 93, 93))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(459, Short.MAX_VALUE)
.addComponent(cmdAccesar, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap()))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>
private void cmdAccesarActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
// File archivoConexion = new File("Conexion.xml");
//
// if (archivoConexion.exists())
// System.out.println("El fichero");
// else
crearXML2();
//AQUI CREAMOS LA INSTANCIA A LA CLASE
conexion con = new conexion();
//AQUI LLENAMOS CON LOS DATOS NECESARIOS DE CONEXIÓN
con.strServidor=this.txtServer.getText();
con.strPSWSQL="";
con.strUsuarioSQL="root";
con.strBaseDeDatos=this.txtBase.getText();
//AQUI REALIZAMOS LA CONEXIÓN
con.conectado();
leerConfiguracion();
frmPrincipal principal= new frmPrincipal();
classUsuarios usuarios = new classUsuarios();
//ESTO YA ES OTRA HISTORIA, AQUI VERIFICA SI EL USUARIO Y CONTRASEÑA COINCIDEN
if (usuarios.blnChecaUsuarioContra("SELECT * FROM Usuarios where Usuario=’"+this.txtUsuario.getText() +"’ and Contra=’"+this.pswContraseña.getText()+"’")==true){
this.setVisible(false);
principal.setVisible(true);
}
else
JOptionPane.showMessageDialog(null, "USUARIO O CONTRASEÑA INCORRECTO"+this.pswContraseña.getText());
System.out.println("SELECT * FROM Usuarios where Usuario=’"+this.txtUsuario.getText() +"’ and Contra=’"+this.pswContraseña.getText()+"’");
} catch (ParserConfigurationException ex) {
Logger.getLogger(frmLogueo.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(frmLogueo.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* @param args the command line arguments
*/
// public static void main(String args[]) {
// /* Set the Nimbus look and feel */
// //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
// /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
// * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
// */
// try {
// for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
// if ("Nimbus".equals(info.getName())) {
// javax.swing.UIManager.setLookAndFeel(info.getClassName());
// break;
// }
// }
// } catch (ClassNotFoundException ex) {
// java.util.logging.Logger.getLogger(frmLogueo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (InstantiationException ex) {
// java.util.logging.Logger.getLogger(frmLogueo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (IllegalAccessException ex) {
// java.util.logging.Logger.getLogger(frmLogueo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// } catch (javax.swing.UnsupportedLookAndFeelException ex) {
// java.util.logging.Logger.getLogger(frmLogueo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
// }
// //</editor-fold>
//
// /* Create and display the form */
// java.awt.EventQueue.invokeLater(new Runnable() {
// public void run() {
// new frmLogueo().setVisible(true);
// }
// });
// }
// Variables declaration – do not modify
private javax.swing.JButton cmdAccesar;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel lblBase;
private javax.swing.JLabel lblContraseña;
private javax.swing.JLabel lblServidor;
private javax.swing.JLabel lblUsuario;
private javax.swing.JPasswordField pswContraseña;
private javax.swing.JTextField txtBase;
private javax.swing.JTextField txtServer;
private javax.swing.JTextField txtUsuario;
// End of variables declaration
public void crearXML2() throws ParserConfigurationException, TransformerConfigurationException, TransformerException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation implementation = builder.getDOMImplementation();
Document document = implementation.createDocument(null, "Configuracion", null);
document.setXmlVersion("1.0");
Element raiz = document.getDocumentElement();
Element nodoServidor = document.createElement("Servidor"); //creamos un nuevo elemento
Text nodoValorServidor = document.createTextNode(this.txtServer.getText()); //Ingresamos la info
nodoServidor.appendChild(nodoValorServidor);
raiz.appendChild(nodoServidor); //pegamos el elemento a la raiz "Documento"
Element nododb = document.createElement("DB"); //creamos un nuevo elemento
Text nodoValorDB = document.createTextNode(this.txtBase.getText()); //Ingresamos la info
nododb.appendChild(nodoValorDB);
raiz.appendChild(nododb); //pegamos el elemento a la raiz "Documento"
Element nodoUsuario = document.createElement("Usuario"); //creamos un nuevo elemento
Text nodoValorUsuario = document.createTextNode(this.txtUsuario.getText()); //Ingresamos la info
nodoUsuario.appendChild(nodoValorUsuario);
raiz.appendChild(nodoUsuario); //pegamos el elemento a la raiz "Documento"
Source source = new DOMSource(document);
StreamResult result = new StreamResult(new java.io.File("Conexion.xml"));//nombre del archivo
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(source, result);
}
public void leerConfiguracion(){
try{
File fXmlFile = new File("Conexion.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//optional, but recommended
//read this – http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Configuracion");
System.out.println("—————————-");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
this.txtServer.setText( eElement.getElementsByTagName("Servidor").item(0).getTextContent());
this.txtBase.setText(eElement.getElementsByTagName("DB").item(0).getTextContent());
this.txtUsuario.setText(eElement.getElementsByTagName("Usuario").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
[/code]
Por si llegaran a necesitar la clase usuarios
[code languaje=”Java”]
/*
CREADO POR JULIO
*/
package clases;
import java.sql.SQLException;
import herramientas.conexion.*;
import com.sun.crypto.provider.RSACipher;
import herramientas.conexion;
import java.awt.List;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author julio
*/
public class classUsuarios {
private conexion con;
PreparedStatement ps;
ResultSet res;
public classUsuarios() {
con = new conexion();
}
public boolean blnChecaUsuarioContra( String sql){
boolean data =false;
String idUsuarios="IdUsuarios";
try{
ps= con.conectado().prepareStatement(sql);
res = ps.executeQuery();
while(res.next()){
//System.out.println(res.getNString(idUsuarios));
data=true;
System.out.println(res.getWarnings());
}
res.close();
}catch(SQLException e){
System.out.println(e);
}
return data;
}
}
[/code]
Estimados lectores buen día, gracias por pasarse por aquí, este es su espacio y siempre serán bienvenidos, recuerden que pueden dejar su opinión en cada publicación, también se avisa que toda información publicada aquí es de libre distribución.
En la entrada anterior en lo referente a Java, vimos como instalar la IDE NetBeans mostrando a cada detalle cada paso, continuando en ello en esta ocasión mostraremos como generar un “XML” escribiendo código Java desde la IDE que hemos instalado.
Para ello se ha diseñado y programado una forma la que simula ser un Login para dar acceso a usuarios en la cual pedirá el servidor, base de datos, usuario y contraseña tal como se ve en la imagen.
La información que va a almacenar el XML serán los datos de conexión, por ejemplo tomando en cuenta la imagen de arriba seria, localhost, comercial y julio.
El contenido del archivo XML final sera el siguiente:
[code language=”xml”]
localhost
comercial
Julio
[/code]
Bien para ello tenemos que agregar al proyecto las librerias JDOM 2.0.6 el cual podrás descargar de la pagina oficial http://www.jdom.org/ o también del enlace de nuestra cuenta de Mediafire haciendo click aquí.
El próximo paso sera descomprimir y agregar todas las librerías de este paquete que son 5 archivos *.*jar al proyecto, para ello nos vamos al árbol del proyecto, damos click derecho en donde dice libraries y damos clic en add JAR/folder, tal como se muestra en la imagen, al principio batalle para posicionarme en la carpeta donde están las librerías por que hacia doble click en una carpeta y se agregaba toda la carpeta, después se soluciono.
Luego nos saldrá una ventana en la cual tendremos que buscar las librerías de Jdom que descargamos, una vez descargada podremos ver las librerías agregadas al proyecto así como se ven en la imagen de arriba.
Ya con esto podemos agregar los encabezados en la clase en donde se van a usar las librerías, aunque, no es muy necesario ya que al poner el código el mismo IDE nos marcara de que sera necesario importar las librerías en la clase, de una u otra forma les dejare el código por si desean copiar y pegar para ahorrarse tiempo.
[code language=”Java”]
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package interfaces;
import clases.classUsuarios;
import herramientas.conexion;
import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.jar.Attributes;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import javax.xml.*;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
[/code]
El siguiente paso sera crear la función que genere nuestro preciado y hermoso XML y usarlo en el transcurso del programa como acceso de configuraciones locales por equipo, entonces les dejo el código para que lo puedan adaptar a sus necesidades
[code language=”Java”]
public void crearXML2() throws ParserConfigurationException, TransformerConfigurationException, TransformerException{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation implementation = builder.getDOMImplementation();
Document document = implementation.createDocument(null, “Configuracion”, null);
document.setXmlVersion(“1.0”);
Element raiz = document.getDocumentElement();
Element nodoServidor = document.createElement(“Servidor”); //creamos un nuevo elemento
Text nodoValorServidor = document.createTextNode(this.txtServer.getText()); //Ingresamos la info
nodoServidor.appendChild(nodoValorServidor);
raiz.appendChild(nodoServidor); //pegamos el elemento a la raiz “Documento”
Element nododb = document.createElement(“DB”); //creamos un nuevo elemento
Text nodoValorDB = document.createTextNode(this.txtBase.getText()); //Ingresamos la info
nododb.appendChild(nodoValorDB);
raiz.appendChild(nododb); //pegamos el elemento a la raiz “Documento”
Element nodoUsuario = document.createElement(“Usuario”); //creamos un nuevo elemento
Text nodoValorUsuario = document.createTextNode(this.txtUsuario.getText()); //Ingresamos la info
nodoUsuario.appendChild(nodoValorUsuario);
raiz.appendChild(nodoUsuario); //pegamos el elemento a la raiz “Documento”
Source source = new DOMSource(document);
StreamResult result = new StreamResult(new
java.io.File(“Conexion.xml”));//nombre del archivo
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(source, result);
}
[/code]
Y listo, esta función la podrás ejecutar en cualquier parte de la clase en donde este declarada, yo la use al momento de darle click en accesar
[code language=”Java”]
private void cmdAccesarActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
// File archivoConexion = new File(“Conexion.xml”);
//
// if (archivoConexion.exists())
// System.out.println(“El fichero”);
// else
crearXML2();
conexion con = new conexion();
con.strServidor=this.txtServer.getText();
con.strPSWSQL=””;
con.strUsuarioSQL=”root”;
con.strBaseDeDatos=this.txtBase.getText();
con.conectado();
leerConfiguracion();
frmPrincipal principal= new frmPrincipal();
classUsuarios usuarios = new classUsuarios();
if (usuarios.blnChecaUsuarioContra(“SELECT * FROM Usuarios where Usuario='”+this.txtUsuario.getText() +”‘ and Contra='”+this.pswContraseña.getText()+”‘”)==true){
this.setVisible(false);
principal.setVisible(true);
}
else
JOptionPane.showMessageDialog(null, “USUARIO O CONTRASEÑA INCORRECTO”+this.pswContraseña.getText());
System.out.println(“SELECT * FROM Usuarios where Usuario='”+this.txtUsuario.getText() +”‘ and Contra='”+this.pswContraseña.getText()+”‘”);
} catch (ParserConfigurationException ex) {
Logger.getLogger(frmLogueo.class.getName()).log(Level.SEVERE, null, ex);
} catch (TransformerException ex) {
Logger.getLogger(frmLogueo.class.getName()).log(Level.SEVERE, null, ex);
}
}
[/code]
Y eso seria así de fácil sin complicarse mucho.
Bien espero que les sea de utilidad, yo busque por muchos blogs y algunos de ellos me ayudaron y después se adapto el código para que funcionara de acuerdo a nuestras necesidades.
Saludos no olviden dejar su huella en la caja de comentarios y puntuar la publicación.
Camaradas bienvenidos a mi blog, cada vez me esta gustando wordpress, aunque aun no termino de dejar blogger, luego veremos los pros y contras de cada servicio de blogueo.
Este post será el primero de una serie de publicaciones en los cuales se hablara de programación en JAVA, en esta serie de entradas se describira de manera detallada desde como instalar la IDE para programar, hasta de como realizar programas que ayuden a las personas a realizar sus labores cotidianas, tal vez para los usuarios avanzados de programación en JAVA sea algo aburrido explicar todo a detalle, es cierto, puede ser así por que las entradas estan dirigidas a todo tipo de publico sea programador con experiencia o no lo sea.
Bien lo primero que tenemos que hacer es descargar el NetBeans, la versión que se estará utilizando será la 8.0.2, lo podemos descargar de la pagina oficial https://netbeans.org/ o bien descargarlo desde este enlace de nuestra cuenta de mediafire, es un ejecutable que pesa alrededor de 200Mb
Como podran ver en la imagen, esta instalacion es el que tiene todas las caracteristicas, de esta forma no nos faltara nada, como somos principiantes vale mas que sobre a que falte.
Una vez que que concluya la descarga comenzaremos a instalar, para ello abriremos el ejecutable y nos saldra la primera pantalla en la cual nos dice el contenido de la instalación, tal como se ve en la imagen.
Despues de dar click al boton Next nos aparecera una ventana en la cual nos preguntara si estamos de acuerdo con la licencia del producto, asi que la leemos y si estamos de acuerdo seleccionamos el check con una palomita “I Accept the terms….” para despues dar click en Next.
En la siguiente ventana aparecera los terminos de licencia de JUnit los cuales tambien tenemos que leer, se que si van a leer, si estamos de acuerdo con la licencia aceptamos los terminos pero si por alguna razón religiosa, politica etc no estan de acuerdo con los terminos de la licencia pues eligen No instalar JUnit y le dan siguiente, tal como se observa en la siguiente pagina.
Prosiguiendo, nos pedira la ruta de la instalación de NetBeans y tambien nos pedira la ruta de JDK, si no tenemos instalado el JDK nos pondra ese campo de texto en blanco y si el campo de texto esta en blanco la instalacion dejara de avanzar de manera que no se realizara.
En caso de eso tienes que descargar el JDK de JAVA, que lo puedes descargar de la siguiente pagina http://www.oracle.com/technetwork/es/java/javase/downloads/index.html
Debe de aparecer tal y como se ve en la imagen siguiente:
Si todo ha salido bien hasta aqui y damos Click en Next entonces la pantalla siguiente saldra la instalación en curso, va a tardar unos minutos, así que sean pacientes.
Al final de la instalación les saldra una ultima ventana en donde se le pedira apoyo para enviar datos de forma anonima para mejorar este producto, yo en lo particular le puse que no, pero igual si ustedes desean ayudar les recomiendo que investiguen mas a fondo la manera de recolección y tratado de tales datos, yo en mi caso como ignoro la manera en la cual se usaran y recolectaran tales datos preferi darle que no.
Aun asi camaradas no olviden apoyar al software libre distribuyendo o donando, recuerden siempre que el software libre es patrimonio de la humanidad, y mucha gente de manera desinterezada trabaja en ello y libera su trabajo no quedandoselo para si mismo.
Bien una vez instalado ya tendremos la IDE tal y como se muestra en la imagen.
Y ya esta hecho el primera paso para empezar lo que podria ser un gran proyecto, de aqui en adelante lo unico que te limita es tu imaginación, y tambien en donde todos vean problemas tu encuentrales solución, los problemas de otros pueden ser tu mina de oro tu alimento tu pan de cada dia, muchos buscan soluciones y tu las puedes dar generando aplicaciones.
Muchas gracias camaradas por llegar a leer hasta el final, si te ha servido este blog favor de comentar y puntuar sea negativo y positivo, los comentarios para mejorar bien fundamentados y no anonimos seran bien recibidos, no olviden tambien compartir si la información les es de utilidad, saludos y hasta la proxima