Cargar dropdownlist combo en MVC con una lista desde LINQ


@Html.DropDownListFor(m => m.Cheque.Bancos, new SelectList(Model.Cheque.Bancos, "Value", "Text"))


Cheque chq = new Cheque();

chq.Bancos = CargarBancos();

private IEnumerable<SelectListItem> CargarBancos()
{
IEnumerable<SelectListItem> ll;

using (var db = new X_XEntities())
{
var b = from t in db.BCT_DES
where t.TIPDESTAB == 5
select new { t.CODDESTAB, t.DESCORTAB };


ll = b.Select(aa => new SelectListItem
{
Text = aa.DESCORTAB,
Value = aa.CODDESTAB.ToString()
}).ToList();

}

return ll;
}

Ejemplos de JPA - Guia #1


http://wiki.netbeans.org/SimpleJPAApplicationWithNetbeans


EJEMPLO DE JPA
==============

1. Crear Enterprise Application (AppGestionPersona) [desmarcar Create EJB module y Create web app module]

2. Crear dominio con nombre Dominio.java (java application), desmarcar "Create Main Class" [Agregar el CODIGO 0]

3. Crear paquete uy.edu.ort.dominio (en el proyecto creado anteriormente)

4. Crear clase Persona dentro del paquete recien creado.

5. Crear un modulo EJB (Nombre: AppGestionPersonaPersistencia-ejb) y agregarlo al enterprise application creado anteriormente.

6. Agregar la libreria EclipseLink (click derecho en Libraries dentro del EJB y Add Library...)

7. Agregar el mysql-connector-java-5.1.13-bin.jar (click derecho en Libraries dentro del EJB y Add JAR/Folder...)

8. Agregar el proyecto Dominio (click derecho en Libraries dentro del EJB y Add Project... y elegir Dominio)

9. Crear la base de datos en MySql (nombre prueba1)

10. Crear una conexion a la base de datos:
      Click en la ficha Services
      Click derecho en Databases / New Connection
      Elegir el driver MySql
      Poner los parametros de acceso a la bd (usuario root, pwd root, y el nombre de la base de datos  prueba1)

11. Crear un Persistence Unit (Click derecho sobre AppGestionPersonaPersistencia-ejb, New / Other / Persistence

12. Ponerle nombre GestionPersonaPU y elegir como Persistence Provider: EclipseLink (JPA...)

13. En data source, poner New Data Source...

14. Ponerle nombre: jdbc/prueba

15. En el combo de Database Connection, elegir la conexion creada anteriormente

16. En Table Generation Strategy marcar Drop and Create

[[PARA BORRAR CONEXIONES YA EXISTENTES:
  a. Editar el archivo glassfish-resources.xml (ubicado dentro de la carpeta setup de la ruta donde esta el ejb)
        b. Borrar la linea que dice jdbc-resource...
c. Ir al Enterprise Beans, en la ficha Services, en Databases, ubicar la conexion, hacerle Disconnect y luego borrarla.
]]


CREACION DEL ENTITY BEAN
========================

17. Crear un paquete uy.edu.ort.gestion.persona.entidades (click derecho sobre el ejb, New / Java Package... y luego Finish)

18. Sobre el paquete recien creado, boton derecho, New / Entity Class, y en class name, poner PersonaEntity

19. Editar el PersonaEntity.java recien creado y agregar este codigo en los imports (arriba del todo):
import javax.persistence.Table;
import javax.persistence.Column;

20. Agregar el codigo de la Entity Personas [CODIGO 1]


CREACION DEL SESION BEAN
========================

21. Crear el paquete uy.edu.ort.gestion.persona.negocio (click derecho sobre el ejb, New / Java Package... y luego Finish)

22. Crear un session bean PersonaSB, de tipo Stateless e interfaz Local (click derecho en el paquete creado en el paso anterior, New /
Session Bean)

23. ESTE PASO CREA DOS FUENTES: PersonaSB.java y PersonaSBLocal.java. Este ultimo es la interfaz.

24. Agregar el codigo a la interfaz (PersonaSBLocal.java) [CODIGO 2] (OBSERVAR EN EL CODIGO QUE HAY QUE HACER UN IMPORTS
DE LA CLASE PERSONA, PORQUE SINO NO SE PUEDE USAR EL OBJETO PERSONA)

25. Agregar el codigo al Session Bean (PersonaSB.java). [CODIGO 3]


CREACION DEL WEB SERVICE
========================

EN ESTE PASO SE CREA UN WEB SERVICE A PARTIR DE LOS METODOS DEL SESSION BEAN

26. Crear el paquete uy.edu.ort.gestion.persona.ws (click derecho sobre el EJB, New / Java Package... y luego Finish)

27. Click derecho en el paquete recien creado, New / Web Service

28. Ponerle nombre PersonaWS

29. Marcar Create Web Service from Existing Session Bean y luego dar Browse, y elegir PersonaSB (esto crea el codigo automaticamente en
base a lo que tenga el Session Bean)


DEPLOY
======

30. Click derecho sobre la Enterprise Application (AppGestionPersona) y luego Clean and Build.

Si dice BUILD SUCCESSFUL...

31. Click derecho sobre la AppGestionPersona, y luego DEPLOY.

VERIFICACION DEL DEPLOY
=======================

Para ver si el deploy quedo bien:

32. Abrir el administrador de glassfish (http://localhost:4848) [LOCALHOST O LA DIRECCION DONDE ESTE EL SERVIDOR GLASSFISH!!]

33. Click en Applications... Tiene que aparecer AppGestionPersona

34. Click en AppGestionPersona

35. Click en View Endpoint (abajo a la derecha)

36. Click en /PersonaWS/PersonaWS?Tester

37. Click en http://direccion_que_aparezca:8080/PersonaWS/PersonaWS?Tester


[CREAR UN CLIENTE PARA PROBAR LA APLICACION]

38. Crear un paquete dentro de ClientePrueba que se llame uy.edu.ort.cliente

39. Crear un nuevo proyecto en NetBeans (menu File / New Project / Java / Java Application)

40. Llamarlo ClientePrueba y dejar marcada la opcion "Create Main Class". En el nombre del main class poner uy.edu.ort.cliente.ClientePrueba (esto ya crea el paquete y deja el .java ahi adentro)

41. Agregar el [CODIGO 4]

42. Sobre el paquete donde esta el ClientePrueba.java, click derecho y crear un Cliente Web Service con la WSDL generada anteriormente [para saber la wsdl se puede ir al servidor glassfish]. Para esto marcar WSDL URL e indicar la url del wsdl:

http://localhost:8080/PersonaWS/PersonaWS?wsdl

[ESTA URL SE PUEDE VER EN EL ADMIN DE GLASSFISH]

43. Elegir el paquete donde estara el webservice (uy.edu.ort.cliente)

PARA PROBAR EL CLIENTE, CLICK DERECHO SOBRE ClientePrueba.java, y Run.




















[CODIGO 0]

/*
 * 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 uy.edu.ort.dominio;

/**
 *
 * @author CRUSSO_PC
 */
public class Persona {
    private long id;
    private String nombre;
    private String apellido;
    private String direccion;
 
    public String getNombre() {
        return nombre;
    }
 
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
 
    public String getApellido(){
        return apellido;
    }
 
    public void setApellido(String apellido) {
        this.apellido = apellido;
    }
 
    public String getDireccion(){
        return direccion;
    }
 
    public void setDireccion(String direccion)
    {
        this.direccion = direccion;
    }
}

[FIN DEL CODIGO 0]




[CODIGO 1]
/*
 * 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 uy.edu.ort.gestion.persona.entidades;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * @author CRUSSO_PC
 */
@Entity
@Table(name="PERSONAS")
public class PersonaEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="ID")
    private Long id;

    @Column(name="NOMBRE", nullable=false)
    private String nombre;

    @Column(name="APELLIDO", nullable=false)
    private String apellido;
 
    @Column(name="DIRECCION", nullable=false)
    private String direccion;
     
    public Long getId() {
        return id;
    }

    public String getNombre(){
        return nombre;
    }
 
    public void setNombre(String nombre){
        this.nombre = nombre;
    }
 
    public String getApellido(){
        return apellido;
    }
 
    public void setApellido(String apellido){
        this.apellido = apellido;      
    }
 
    public String getDireccion() {
        return direccion;      
    }
 
    public void setDireccion(String direccion){
        this.direccion = direccion;
    }
 
    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof PersonaEntity)) {
            return false;
        }
        PersonaEntity other = (PersonaEntity) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "uy.edu.ort.gestion.persona.entidades.PersonaEntity[ id=" + id + " ]";
    }
 
}
[FIN CODIGO 1]


[CODIGO 2]
/*
 * 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 uy.edu.ort.gestion.persona.negocio;

import javax.ejb.Local;
import uy.edu.ort.dominio.Persona;

/**
 *
 * @author CRUSSO_PC
 */
@Local
public interface PersonaSBLocal {
    public void alta(Persona persona);
    public void eliminar(Persona persona);
    public void modificar(Persona persona);  
}

[FIN DEL CODIGO 2]


[CODIGO 3]
/*
 * 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 uy.edu.ort.gestion.persona.negocio;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import uy.edu.ort.dominio.Persona;
import uy.edu.ort.gestion.persona.entidades.PersonaEntity;

/**
 *
 * @author CRUSSO_PC
 */
@Stateless
public class PersonaSB implements PersonaSBLocal {
    @PersistenceContext
    EntityManager em;
 
    @Override
    public void alta(Persona persona)
    {
        PersonaEntity personaEntity = new PersonaEntity();
        personaEntity.setDireccion(persona.getDireccion());
        personaEntity.setNombre(persona.getNombre());
        personaEntity.setApellido(persona.getApellido());
        em.persist(personaEntity);
    }
 
    @Override
    public void eliminar(Persona persona)
    {      
    }

    @Override
    public void modificar(Persona persona)
    {      
    }

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
}

[FIN DEL CODIGO 3]




[CODIGO 4]
/*
 * 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 uy.edu.ort.cliente;

/**
 *
 * @author CRUSSO_PC
 */
public class ClientePrueba {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        PersonaWS port = new PersonaWS_Service().getPersonaWSPort();
     
        Persona persona = new Persona();
     
        persona.setDireccion("Lejos");
        persona.setNombre("Juan");
        persona.setApellido("Perez");
     
        port.alta(persona);
     
        System.out.println("Fin!!");
    }
 
}

[FIN DEL CODIGO 4]



Errores y soluciones de deployment en Java EE

EL ARCHIVO GLASSFISH-RESOURCES.XML ES IMPORTANTE!
ES EL QUE TIENE TODAS LAS CONEXIONES DE BD.
SI HAY ERRORES DE DEPLOYMENT REFERIDOS A LAS CONEXIONES, HAY QUE REVISAR ESTE ARCHIVO (ESTA DENTRO DEL EJB, EN LA CARPETA SETUP)

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'OPTION SQL_SELECT_LIMIT=DEFAULT' at line 1
=======================================================================
Verificar que se está utilizando la version mysql-connector-java-5.1.23.jar
Y verificar que está copiado en estas ubicaciones:
                c:\glassfish4\glassfish\domains\<dominio>\lib
                c:\glassfish4\glassfish\domains\<dominio>\lib\ext

Test de webservices REST
==================
Hay que elegir correctamente el proyecto para test. La 1ra pantalla muestra como NO funciona, la 2da es la correcta (siempre elegir el proyecto con "Web Test Client in Project..."



Si da errores de FileNotFoundException (ej, que no puede encontrar el build.xml, etc)
==========================================================
Revisar las propiedades de cada proyecto, y ver si hay "missing files" en algun lado

Si da error: java.lang.Exception: Virtual server server already has a web module Web1
==========================================================

1. Hacer undeploy de la aplicacion (si es que esta deployed en glassfish)
2. Bajar servidor Glassfish
3. Borrar el contenido de la carpeta: C:\glassfish4\glassfish\domains\domain1\generated
4. Subir el servidor Glassfish
5. Hacer el deploy nuevamente

Si no encuentra el WADL cuando se quiere testear un webservice REST
=================================================
Revisar el archivo persistence.xml

Debe ser parecido a este:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="Web1PU" transaction-type="JTA">
      
      <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
      
    <jta-data-source>jdbc/achilles</jta-data-source>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    
        <properties>
      <property name="javax.persistence.schema-generation.database.action" value="create"/>
    </properties>
  </persistence-unit>
</persistence>


Si da error de Application contains no valid components
======================================
El EJB debe contener por lo menos un Session Bean!!! sino da este error.

Si no se puede hacer el deploy
=====================
Verificar que no este intentando crear las tablas y ya estan en la base de datos.

Si no hace insert...
============
Verificar si esta marcado Use Java Transaction APIs (JTA) en persistence.xml.
Si esta marcado, los begin, commit y rollback los maneja JPA, por lo cual no hay que ponerlos.

Si no se puede hacer deploy y aparece este mensaje:
===================================

There is no installed container capable of handling this application


En el enterprise application, click derecho, Add Java EE Module
Seleccionar el módulo EJB.

Luego hacer deploy de nuevo.



Como hacer deploy utilizando el glassfish server:
================================

Click derecho sobre el enterprise application.
Clean and Build

Esto genera un archivo .ear dentro de la carpeta dist:

Por ejemplo:

C:\_KARINA\EJB2\AppGestionPersona\dist\AppGestionPersona.ear

OJO!!! si el deploy luego falla, puede que el NetBeans no haya podido generar el .ear.

En este caso:

Abrir la carpeta dist de cada una de las aplicaciones que componen la solución
Borrar todo el contenido de la carpeta "dist" [si no deja borrarlo, puede ser que el archivo lo tenga capturado el java, para eso hacer control
alt suprimir, task manager, y matar todos los java que haya... Si se hace esto hay que levantar de nuevo el servidor de aplicaciones, porque es uno
de esos javas qeu matamos recién]

Volver a hacer clean and build


[DEPLOY]

OJO!! ANTES DE HACER EL DEPLOY RECORDAR CREAR LA BASE DE DATOS!!

Renombrar el .ear generado a .zip, abrirlo y copiar el archivo glassfish-resources.xml (que esta en la carpeta del EJB), a la carpeta META-INF. (luego renombrarlo nuevamente a .ear)

OJO!!!! al archivo glassfish-resources.xml hay que configurarle el password antes de incluirlo en META-INF (en la property name="Password")

OJO!!! El nombre del datasource que se defina en el persistence unit en el netbeans debe ser asi: java:app/achilles
(The solution is making the resource an application-wide resource. Make sure you make the JNDI name prefixed with java:app/. And so,
in your case, it'll be java:app/Vodafone. This should be done in both your persistence.xml file and
in the WEB-INF/glassfish-resources.xml file also)

Para hacer el deploy desde el Glassfish:



1. Abrir Glassfish como administrador: http://localhost:4848 (usuario admin, passwd root)
2. Click en Applications
3. Click en Deploy...
4. Seleccionar "packaged file to be uploaded to the server"
5. Seleccionar el archivo .ear que se generó dentro de la carpeta "dist" del enterprise application (ej: C:\_KARINA\EJB2\AppGestionPersona\dist\AppGestionPersona.ear)
6. Dar OK


Ejemplo MVC

Controllers / ClienteController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;
using LibX.X;
using LibX.X.X.cifIO;

namespace MvcApplication1.Controllers
{
    public class ClientesController : Controller
    {
        //
        // GET: /FormularioClientes/

        public ActionResult Formulario()
        {
            Parametros p = new Parametros();
            ViewBag.doccli = p.comboBCT("TIPDOC");
            ViewBag.paises = p.comboBCT("PAIS");
         
            return View();
        }

        public ActionResult Listado(FormCollection form)
        {
            SqlDb odb = new SqlDb();

            odb.AbrirDB();
            odb.BeginTran();

            ViewBag.doccli = form["doccli"];

            cli.doccli = int.Parse(form["doccli"].ToString());
            cli.numcli = long.Parse(form["numcli"].ToString());
            cli.digcli = form["digcli"].ToString();

            Cliente c = new Cliente();

            try
            {
                cli.LeerCliente(odb);
             
                c.doccli = cli.doccli;
                c.numcli = cli.numcli;
                c.nomabr = cli.nomabr;

                odb.CommitTran();
                odb.CerrarDB();
            }
            catch (Exception e)
            {
                c.nomabr = "NO HAY DATOS...";
            }

            return View(c);
        }

    }
}

Models / Cliente.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication1.Models
{
    public class Cliente
    {
        public int doccli {get; set;}

        [StringLength(7)]
        public long numcli {get; set;}

        public int digcli {get; set;}

        public String nomabr { get; set; }
    }


}


Models / Parametros.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using LibX.X;
using LibX.X.Y.bctIO;

namespace MvcApplication1.Models
{
    public class Parametros
    {
        public int ItemBCT { get; set; }
        public List<System.Web.Mvc.SelectListItem> ItemBCTList { get; set; }

        public List<System.Web.Mvc.SelectListItem> comboBCT(String tabla)
        {
            SqlDb odb = new SqlDb();

            odb.AbrirDB();
            odb.BeginTran();

            des.LeerBCTPorTabla(odb, tabla);

            List<System.Web.Mvc.SelectListItem> lista = new List<System.Web.Mvc.SelectListItem>();

            for (int i = 0; i < odb.dt.Rows.Count; i++)
            {
                SelectListItem item = new SelectListItem { Value = odb.dt.Rows[i]["coddestab"].ToString(), Text = odb.dt.Rows[i]["coddestab"].ToString() + " - " + odb.dt.Rows[i]["descortab"].ToString() };

                lista.Add(item);
                /*
                ItemBCTList = new List<System.Web.Mvc.SelectListItem>() {
                        new SelectListItem { Value = "1", Text = "Renault" },
                        new SelectListItem { Value = "2", Text = "Peugeot" } };
                 * */
            }

            odb.CommitTran();
            odb.CerrarDB();

            return lista;
           // return ItemBCTList;
        }
    }
}


Views / Clientes / Formulario.cshtml

<!DOCTYPE html>
@using MvcApplication1.Models
@model Cliente

@{
    ViewBag.Title = "Formulario";
}
<link href="../../Content/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="../../Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.10.3.js" type="text/javascript"></script>


@using (Html.BeginForm("Listado", "Clientes", FormMethod.Post))
{    
    @Html.DropDownList("doccli")    
    @Html.Label("Numcli")
    @Html.TextBoxFor(m => m.numcli)

    @Html.TextBoxFor(m => m.digcli)
    
    <input id="Submit1" type="submit" value="submit" />    
}





Sony Vegas Pro 11 edición multicam

1. Sincronizar (antes visualizar en un visor externo, y calcular donde se va a comenzar)
2. Poner las dos o mas pistas en el Sony Vegas
3. Mute a todos los videos (circulo tachado)
4. Unmute al 1er video
5. Presionar el icono Pan & Crop (de los dos iconos que estan al final del track, el primero, que parece un rombo)
6. Asegurarse que el slide de la posicion esta en cero, y que el icono del candado esta presionado
7. Con scroll de rueda, hacer zoom y agrandar el cuadro que tiene la F para poder ver en el preview la posicion del video.

**** SI EL PREVIEW NO APARECE, HAY QUE INSTALAR LA ULTIMA VERSION DE QUICKTIME ****

Migración de instantmantis 1.0.8 a mantisbt 1.2.17

1. Instalar XAMPP 1.8.3 (xampp-win32-1.8.3-3-VC11-installer.exe)
    Extraer el contenido de mantis1.2.17 a la carpeta c:\xampp\htdocs

2. Editar el archivo C:\xampp\mysql\bin\my.ini y definir los siguientes seteos:

                  [client]
                  password       = root
               
                  [mysqld]
                  max_allowed_packet = 1000000M
                  wait_timeout = 600
 
3. Exportar la base de datos del mantis 1.0.8, mediante la opción Tools/Extract Database. DESMARCAR LA OPCION DE CREAR BASE DE DATOS. Exportarlo como mantis.sql

3. Exportar la base de datos del mantis 1.0.8:
       mysqldump -hXmantis -P3360 -uroot -pELPASSWORD --default-character-set=latin1 prueba > p1.dump

4. Crear la base de datos en el servidor nuevo:
       CREATE DATABASE prueba CHARSET latin1 COLLATE latin1_swedish_ci

5. Mover el p1.dump creado en el paso 3, a la ubicación c:\xampp\mysql\bin

6. Importar la base de datos:
       type p1.dump | mysql -hlocalhost -p3306 -uroot -proot --default-character-set=latin1 prueba


4. Mover el archivo mantis.sql generado mediante el paso anterior, a la carpeta c:\xampp\mysql\bin

5. Ejecutar:

               C:\xampp\mysql\bin>mysql -uroot -h127.0.0.1 -proot mantis < mantis.sql


6. Ingresar a http://localhost/mantis/admin/install.php

7. Ingresar los siguientes datos:

                hostname: 127.0.0.1   [NO PONER LOCALHOST!!!]
                Username (for Database): root
                Password (for Database): root
                Database name: mantis
                Admin Username (to create database): root
                Admin Password (to create database): root

Presionar Install/Upgrade Database


XAMPP 1.8.3 INCLUYE:
  • Apache 2.4.9
  • MySQL 5.6.16
  • PHP 5.5.11
  • phpMyAdmin 4.1.12
  • FileZilla FTP Server 0.9.41
  • Tomcat 7.0.42 (with mod_proxy_ajp as connector)
  • Strawberry Perl 5.16.3.1 Portable
  • XAMPP Control Panel 3.2.1 (from hackattack142)