Migrar un diagrama de base de datos a otra base

/*
SrsScriptDiagram

Adapted from script found online at http://www.conceptdevelopment.net/Database/ScriptDiagram2008/

This script will extract the database diagram @DiagramName from <Database Name> and build
a script that can be used to load that diagram into another copy of the database.

Instructions:
1. Open this script in SQL Server Management Studio
2. Use the Specify values for Template Parameters (Ctrl+Shift+M) to set parameter values:
2a. Replace <Database Name,,> with the source database name.
2b. Replace <Diagram Name,,MainDiagram> with the desired diagram name.
3. Change the value of @TargetDatabase to the target database name, or leave as db_name() to use the current database.
4. Execute the script to build a diagram load script.
5. Save the output script.
6. Run the output script on a copy of the target database to restore the diagram.

Modification History:
Downloaded script from http://www.conceptdevelopment.net/Database/ScriptDiagram2008/
Formatting cleaned up to bring it closer to our standards.
Diagram name creation was set to original name if possible, date/time suffix is only used for uniqueness if needed.
Added explicit Target Database variable
Refactored FOR Template Parameters
*/

USE CFE

GO

DECLARE @DiagramName varchar(128)
, @TargetDatabase nvarchar(255)

SELECT @DiagramName = 'DiagramaCompleto'
, @TargetDatabase = db_name()

DECLARE @diagram_id int
, @index int
, @size int
, @chunk int
, @line varchar(max)
, @eol varchar(10)
, @CurrentDateString nvarchar(100)

-- Set start index, and chunk 'constant' value
SELECT @index = 1  --
, @chunk = 32 -- values that work: 2, 6
-- values that fail: 15,16, 64
, @eol = char(13) + char(10)
, @CurrentDateString = convert ( varchar(60) , sysdatetimeoffset() , 121 )

-- Get PK diagram_id using the diagram's name (which is what the user is familiar with)
SELECT @diagram_id = diagram_id
, @size = DATALENGTH(definition)
FROM sysdiagrams sd
WHERE sd.[name] = @DiagramName

IF ( @diagram_id IS NULL )
BEGIN
print '/**<error>' + @eol + @eol + 'Diagram name [' + @DiagramName + '] could not be found.' + @eol + @eol + '</error>*/'
END
ELSE -- Diagram exists
BEGIN
-- Now with the diagram_id, do all the work
print '/**'
print '<summary>'
print 'Restore diagram ''' + @DiagramName + ''''
print '</summary>'
print '<remarks>'
print 'Generated by SrsScriptDiagram Script'
print 'Will attempt to create [sysdiagrams] table if it doesn''t already exist'
print '</remarks>'
print '<generated>' + @CurrentDateString + '</generated>'
print '*/'
print ''
print ''
print 'USE ' + @TargetDatabase
print ''
print 'print ''=== Tool_ScriptDiagram2008 restore diagram [' + @DiagramName + '] ==='''
print '    -- If the sysdiagrams table has not been created in this database, create it!

IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ''sysdiagrams'')
BEGIN
-- Create table script generated by Sql Server Management Studio
-- _Assume_ this is roughly equivalent to what Sql Server/Management Studio
-- creates the first time you add a diagram to a 2008 database
CREATE TABLE [dbo].[sysdiagrams]
(
[name] [sysname] NOT NULL,
[principal_id] [int] NOT NULL,
[diagram_id] [int] IDENTITY(1,1) NOT NULL,
[version] [int] NULL,
[definition] [varbinary](max) NULL,
PRIMARY KEY CLUSTERED ( [diagram_id] ASC ) WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ,
CONSTRAINT [UK_principal_name] UNIQUE NONCLUSTERED ( [principal_id] ASC , [name] ASC ) WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF)
)

                    EXEC sys.sp_addextendedproperty @name=N''microsoft_database_tools_support'', @value=1 , @level0type=N''SCHEMA'',@level0name=N''dbo'', @level1type=N''TABLE'',@level1name=N''sysdiagrams''

                    print ''[sysdiagrams] table was created as it did not already exist''
END

-- Target table will now exist, if it didn''t before'
print 'SET NOCOUNT ON -- Hide (1 row affected) messages'
print 'DECLARE @newid INT'
print 'DECLARE @DiagramSuffix          varchar (50)'
print 'DECLARE @NewDiagramName nvarchar(100)' -- asw 2010/03/25 use default name if diagram does not already exist.
print ''
print 'SET @DiagramSuffix = '' '' + LEFT(CONVERT(VARCHAR(23), GETDATE(), 121), 16)'
print ''
print 'IF EXISTS ( SELECT * FROM sysdiagrams sd WHERE ( sd.name = ''' + @DiagramName + ''' ) )'
print 'BEGIN'
print ' print ''Suffix diagram name with date, to ensure uniqueness.'''
print ' SELECT @NewDiagramName = ''' + @DiagramName + ''' + '' '' + LEFT(CONVERT(VARCHAR(23), GETDATE(), 121), 16)'
print 'END'
print 'ELSE'
print 'BEGIN'
print ' print ''Use diagram name without suffix.'''
print ' SELECT @NewDiagramName = ''' + @DiagramName + ''''
print 'END'
print ''
print 'print ''Create row for new diagram'''

-- Output the INSERT that _creates_ the diagram record, with a non-NULL [definition],
-- important because .WRITE *cannot* be called against a NULL value (in the WHILE loop)
-- so we insert 0x so that .WRITE has 'something' to append to...

print 'BEGIN TRY'
print '    print ''Write diagram ' + @DiagramName + ' as '' + @NewDiagramName + '' into new row (and get [diagram_id])'''

SELECT @line =
'    INSERT INTO sysdiagrams ([name], [principal_id], [version], [definition])'
+ ' VALUES ( @NewDiagramName , '+ CAST (sd.principal_id AS VARCHAR(100))+', '+CAST (sd.version AS VARCHAR(100))+', 0x)'
FROM sysdiagrams sd
WHERE ( sd.diagram_id = @diagram_id )

print @line
print '    SET @newid = SCOPE_IDENTITY()'
print 'END TRY'
print 'BEGIN CATCH'
print '    print ''XxXxX '' + Error_Message() + '' XxXxX'''
print '    print ''XxXxX END Tool_ScriptDiagram2008 - fix the error before running again XxXxX'''
print '    RETURN'
print 'END CATCH'
print ''
print 'print ''Now add all the binary data...'''
print 'BEGIN TRY'

WHILE ( @index < @size )
BEGIN
-- Output as many UPDATE statements as required to append all the diagram binary
-- data, represented as hexadecimal strings
SELECT @line =
'    UPDATE sysdiagrams SET [definition] .Write ('
+ ' ' + UPPER(sys.fn_varbintohexstr (SUBSTRING (sd.definition, @index, @chunk)))
+ ', null, 0) WHERE ( diagram_id = @newid ) -- index:' + CAST(@index AS VARCHAR(100))
FROM sysdiagrams sd
WHERE (sd.diagram_id = @diagram_id )

print @line

SET @index = @index + @chunk

END

print ''
print '    print ''=== Finished writing diagram id '' + CAST(@newid AS VARCHAR(100)) + ''  ==='''
print '    print ''=== Refresh your Databases-[DbName]-Database Diagrams to see the new diagram ==='''
print 'END TRY'
print 'BEGIN CATCH'
print '    -- If we got here, the [definition] updates didn''t complete, so delete the diagram row'
print '    -- (and hope it doesn''t fail!)'
print '    DELETE FROM sysdiagrams WHERE diagram_id = @newid'
print '    print ''XxXxX '' + Error_Message() + '' XxXxX'''
print '    print ''XxXxX END Tool_ScriptDiagram2008 - fix the error before running again XxXxX'''
print '    RETURN'
print 'END CATCH'
END

print 'USE master'
print ''

Listar las tablas que no tienen claves foranea (FK)

DECLARE @TablasConFk TABLE
(
[object_Id] int
)

INSERT @TablasConFk ( [object_Id] )
SELECT referenced_object_id
FROM sys.foreign_keys
UNION
SELECT [parent_object_id]
FROM sys.foreign_keys

SELECT name as Tabla
FROM sys.objects obj
LEFT OUTER JOIN @TablasConFk conFk ON ( obj.[object_id] = conFk.[object_Id] )
WHERE type_desc = 'USER_TABLE'
AND conFk.[object_Id] IS NULL
ORDER BY Tabla


Listar comentarios de tablas y campos

Listar comentarios de las tablas

SELECT objname, CONVERT(VARCHAR(500), value)
      FROM ::FN_LISTEXTENDEDPROPERTY(N'MS_DESCRIPTION', N'USER', N'DBO', N'TABLE', NULL, NULL, NULL)
where objtype = 'TABLE'


Listar comentarios de los campos de una tabla

select 
        st.name [Table],
        sc.name [Column],
        sep.value [Description]
    from sys.tables st
    inner join sys.columns sc on st.object_id = sc.object_id
    left join sys.extended_properties sep on st.object_id = sep.major_id
                                         and sc.column_id = sep.minor_id
                                         and sep.name = 'MS_Description'                                         
    where st.name = 'Nombre de la Tabla'


    and sc.name = 'Nombre del campo'



Con stored procedures...

//crea o actualiza la propiedad MS_description, de la tabla especificada
exec mer_ActualizarDescripcionTabla 'Cliente', 'tabla de clientes de la empresa'-                          

//actualiza o crea la propiedad especificada, para el campo de la tabla especifcadas, y le pone el valor indicado
exec mer_ActualizarPropiedadCampo 'Tipo', 'Cliente', 'Nombre', 'Nombre del cliente'

//elimina la propiedad MS_description, de la tabla especificada
exec mer_EliminarDescripcionTabla 'Cliente'                                    

//elimina la propiedad que tenga el nombre especificado, del campo de la tabla especificados
exec mer_EliminarPropiedadCampo 'Tipo', 'Cliente', 'Nombre'                    

//lista los comentarios de todas las tablas
exec mer_listarComentariosTablas                                                  

//lista todas las propiedades del tipo especificado, de todos los campos de todas las tablas    
exec mer_listarPropiedadesCampos 'Tipo'                        
 
//lista el valor de una propiedad dada de un campo de una tabla.
exec mer_listarPropiedadCampo 'Tipo', 'Cliente', 'FechaNacimiento'                        



Stored procedures

--Comienzo de SPs -------------------------------------------------------
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

CREATE PROCEDURE [dbo].[mer_ActualizarDescripcionTabla]
    -- Los parámetros son el nombre de la tabla y la descripción
    @nombre_tabla sysname = '',
    @descripcion_tabla sql_variant = ''
AS
BEGIN
    BEGIN TRY
 
        IF EXISTS (SELECT OBJNAME AS 'tabla', VALUE AS 'COMENTARIO'
                   FROM ::FN_LISTEXTENDEDPROPERTY(N'MS_DESCRIPTION', N'USER', N'DBO', N'TABLE',
                   @nombre_tabla, NULL, NULL) XP
                   WHERE XP.NAME IN (N'MS_DESCRIPTION'))

            EXEC sys.sp_updateextendedproperty
                @name=N'MS_Description',
                @value=@descripcion_tabla,
                @level0type=N'SCHEMA',
                @level0name=N'dbo',
                @level1type=N'TABLE',
                @level1name=@nombre_tabla
       ELSE
            EXEC sys.sp_addextendedproperty
                @name=N'MS_Description',
                @value=@descripcion_tabla,
                @level0type=N'SCHEMA',
                @level0name=N'dbo',
                @level1type=N'TABLE',
                @level1name=@nombre_tabla
    END TRY
    BEGIN CATCH
        SELECT
            ERROR_LINE() as ErrorLine,
            ERROR_MESSAGE() as ErrorMessage;

            PRINT 'No se pudo agregar la descripción ''' + convert(nvarchar(128),@descripcion_tabla) + '''a la tabla ' + convert(nvarchar(128),@nombre_tabla)
            PRINT 'Error Line: ' + convert(varchar(50),ERROR_LINE())
            PRINT 'ErrorMessage: ' + ERROR_MESSAGE()
            ROLLBACK TRANSACTION
    END CATCH
END


-------------------------------------------------------------------------------------------------------------

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

CREATE PROCEDURE [dbo].[mer_ActualizarPropiedadCampo]
    -- Los parámetros son el nombre de la tabla, el nombre de la columna y la descripción
    @propiedad sysname = '',
    @nombre_tabla sysname = '',
    @nombre_campo sysname = '',
    @descripcion_campo sql_variant = ''
AS
    BEGIN TRY
        IF EXISTS(SELECT objname, value
                  FROM fn_listextendedproperty (@propiedad, N'schema', 'dbo',
                  N'table', @nombre_tabla, N'column', null) WHERE objname = @nombre_campo)
            EXEC sys.sp_updateextendedproperty
                @name=@propiedad,
                @value=@descripcion_campo,
                @level0type=N'SCHEMA',
                @level0name=N'dbo',
                @level1type=N'TABLE',
                @level1name=@nombre_tabla,
                @level2type=N'COLUMN',
                @level2name=@nombre_campo
        ELSE
            EXEC sys.sp_addextendedproperty
                @name=@propiedad,
                @value=@descripcion_campo,
                @level0type=N'SCHEMA',
                @level0name=N'dbo',
                @level1type=N'TABLE',
                @level1name=@nombre_tabla,
                @level2type=N'COLUMN',
                @level2name=@nombre_campo
    END TRY
    BEGIN CATCH
        SELECT
            ERROR_LINE() as ErrorLine,
            ERROR_MESSAGE() as ErrorMessage;

            PRINT 'No se pudo agregar la descripción ''' + convert(nvarchar(128),@descripcion_campo) + '''al campo ' + convert(nvarchar(128),@nombre_campo) + ' en la tabla ' + convert(nvarchar(128),@nombre_tabla)
            PRINT 'Error Line: ' + convert(varchar(50),ERROR_LINE())
            PRINT 'ErrorMessage: ' + ERROR_MESSAGE()
            ROLLBACK TRANSACTION
    END CATCH


-------------------------------------------------------------------------------------------------------------


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

CREATE PROCEDURE [dbo].[mer_EliminarDescripcionTabla]
    @nombre_tabla sysname = ''
AS
    BEGIN TRY
        EXEC sys.sp_dropextendedproperty
            @name=N'MS_Description',
            @level0type=N'SCHEMA',
            @level0name=N'dbo',
            @level1type=N'TABLE',
            @level1name=@nombre_tabla
    END TRY
    BEGIN CATCH
        SELECT
            ERROR_LINE() as ErrorLine,
            ERROR_MESSAGE() as ErrorMessage;

            PRINT 'No se pudo agregar la descripción ''' + '''al campo ' + ' en la tabla ' + convert(nvarchar(128),@nombre_tabla)
            PRINT 'Error Line: ' + convert(varchar(50),ERROR_LINE())
            PRINT 'ErrorMessage: ' + ERROR_MESSAGE()
            ROLLBACK TRANSACTION
    END CATCH



-------------------------------------------------------------------------------------------------------------


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

 
CREATE PROCEDURE [dbo].[mer_EliminarPropiedadCampo]
    @propiedad sysname = '',
    @nombre_tabla sysname = '',
    @nombre_campo sysname = ''
AS
    BEGIN TRY
        EXEC sys.sp_dropextendedproperty
            @name=@propiedad,
            @level0type=N'SCHEMA',
            @level0name=N'dbo',
            @level1type=N'TABLE',
            @level1name=@nombre_tabla,
            @level2type=N'COLUMN',
            @level2name=@nombre_campo
    END TRY
    BEGIN CATCH
        SELECT
            ERROR_LINE() as ErrorLine,
            ERROR_MESSAGE() as ErrorMessage;

            PRINT 'No se pudo agregar la descripción ''' + '''al campo ' + convert(nvarchar(128),@nombre_campo) + ' en la tabla ' + convert(nvarchar(128),@nombre_tabla)
            PRINT 'Error Line: ' + convert(varchar(50),ERROR_LINE())
            PRINT 'ErrorMessage: ' + ERROR_MESSAGE()
            ROLLBACK TRANSACTION
    END CATCH





-------------------------------------------------------------------------------------------------------------

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

CREATE PROCEDURE [dbo].[mer_ListarComentariosTablas]
AS

DECLARE @comentarios TABLE(tabla sysname, descripcion VARCHAR(500))
INSERT INTO @comentarios (tabla, descripcion)
SELECT objname, CONVERT(VARCHAR(500), value)
      FROM ::FN_LISTEXTENDEDPROPERTY(N'MS_DESCRIPTION', N'USER', N'DBO', N'TABLE', NULL, NULL, NULL)
INSERT INTO @comentarios (tabla)
  SELECT table_name
    FROM information_schema.tables
   WHERE table_name NOT IN
      (select tabla FROM @comentarios)
   AND TABLE_TYPE <> 'VIEW'

SELECT * from @comentarios ORDER BY tabla



-------------------------------------------------------------------------------------------------------------

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


CREATE PROCEDURE [dbo].[mer_ListarPropiedadesCampos]
    @propiedad sysname = ''
AS

DECLARE @propiedades TABLE (
       esquema sysname,
       tabla sysname,
       columna sysname,
       valor VARCHAR(500))


DECLARE c CURSOR FOR
       SELECT table_schema, table_name
         FROM information_schema.tables
       WHERE table_type != 'VIEW'

DECLARE @s sysname, @t sysname

OPEN c
FETCH c INTO @s, @t
WHILE @@FETCH_STATUS = 0 BEGIN
    INSERT INTO @propiedades (esquema, tabla, columna, valor)
             SELECT @s, @t, objname, convert(varchar(500), value)
               FROM fn_listextendedproperty (@propiedad, N'schema', @s, N'table', @t, N'column', null);
             
       FETCH c INTO @s, @t
END
CLOSE c
DEALLOCATE c

INSERT INTO @propiedades (esquema, tabla, columna)
SELECT table_schema, table_name, column_name
  FROM information_schema.columns s
 WHERE table_name IN
                (SELECT table_name
                 FROM information_schema.tables
     where TABLE_TYPE <> 'VIEW')
 AND NOT EXISTS
   (SELECT *
      FROM @propiedades c
     WHERE s.table_schema = c.esquema
       AND s.table_name = c.tabla
          AND s.column_name = c.columna)

SELECT *
  FROM @propiedades
 ORDER BY esquema, tabla, columna


-------------------------------------------------------------------------------------------------------------


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

CREATE PROCEDURE [dbo].[mer_ListarPropiedadCampo]
    @propiedad sysname = '',
    @tabla sysname = '',
    @campo sysname = ''
AS

DECLARE @propiedades TABLE (
       esquema sysname,
       tabla sysname,
       columna sysname,
       valor VARCHAR(500))


DECLARE c CURSOR FOR
       SELECT table_schema, table_name
         FROM information_schema.tables
       WHERE table_type != 'VIEW' and
table_name = @tabla

DECLARE @s sysname, @t sysname

OPEN c
FETCH c INTO @s, @t
WHILE @@FETCH_STATUS = 0 BEGIN
    INSERT INTO @propiedades (esquema, tabla, columna, valor)
             SELECT @s, @t, objname, convert(varchar(500), value)
               FROM fn_listextendedproperty (@propiedad, N'schema', @s, N'table', @tabla, N'column', @campo);
             
       FETCH c INTO @s, @t
END
CLOSE c
DEALLOCATE c

select *
from @propiedades

Conectar Nexus 5 con MyPhoneExplorer

1. Habilitar opciones de desarrollo en el celular: Ajustes / Informacion del telefono / Dar 7 taps sobre Numero de compilacion Ir a Ajustes / Opciones de desarrollo / Habilitar Depuracion USB 2. Enchufar el cel con cable usb 3. Si el driver no se instala, ir a dispositivos, actualizar driver, y poner esta ruta: C:\android-studio\sdk\extras\google\usb_driver 4. Abrir MyPhoneExplorer 5. Si da un error, ir al celular y ver si hay un mensaje indicando si se autoriza al pc a conectarse con el cel, poner sí.

Crear plugin para Windows Live Writer

http://blogs.msdn.com/b/dawate/archive/2010/12/30/how-to-create-a-windows-live-writer-twitter-plugin-that-supports-bit-ly.aspx


Ubicacion de WindowsLive.Writer.Api.dll:

                  C:\Program Files\Windows Live\Writer

SyntaxHighlighter para Windows Live Writer

Plugin:
    http://wlwsyntaxhighlighter.codeplex.com/


Cambios en la plantilla HTML de blogger:


<script src='http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shCore.js' type='text/javascript'/>
<script src='http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushJScript.js' type='text/javascript'/>
<script src='http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/shBrushCSharp.js' type='text/javascript'/>

<link href='http://agorbatchev.typepad.com/pub/sh/3_0_83/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://agorbatchev.typepad.com/pub/sh/3_0_83/styles/shCoreDefault.css' rel='stylesheet' type='text/css'/>
<link href='http://agorbatchev.typepad.com/pub/sh/3_0_83/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>


<script type='text/javascript'>
  $(document).ready(function() {
      $("pre").removeClass("php");
      $("pre").removeClass("js");
      $("pre").removeClass("c");

      $("pre").addClass("brush: csharp");

      SyntaxHighlighter.config.clipboardSwf = 'http://agorbatchev.typepad.com/pub/sh/3_0_83/scripts/clipboard.swf';
      SyntaxHighlighter.config.bloggerMode = true;
   
      SyntaxHighlighter.all()
  });
</script>

Microsoft Live Writer con Blogger

Cuando hay problemas de conexion, es por la seguridad de dos pasos que implementa Google:

Leer:

http://lehsys.blogspot.com/2013/11/windows-live-writer-2012-problems-with.html

Java EE - instructivo

Java EE

Pasos para crear un EJB Stateless con Web Service:

1. Crear Enterprise Application:
              File / New Project... -> Java EE -> Enterprise application (desmarcar Create EJB module y Create Web Application Module)

2. Crear EJB Module
              File / New Project... -> Java EE -> EJB Module
              Elegir el enterprise application creado en el paso 1, y GlassFish como servidor

3. Crear aplicación java para contener las interfaces Remotas
              File / New Project... -> Java -> Java Application
              (Desmarcar la opción Create Main Class)

[TODAVIA NO PONER EL CODIGO DE LA INTERFAZ, 1RO CREAR EL SESSION BEAN, Y VINCULARLO CON LO CREADO EN EL PASO 3]


4. Crear un Stateless Session Bean
                Click derecho sobre el package del EJB creado en el paso 2, New / Session Bean...
                Marcar Stateless
                Definir el nombre del package (ej, org.empresa.prueba)
                Elegir como Remote in Project: Interfaces (o como se nombró en el paso 3)

                Agregar este código:

package com.paquete1.interfaces;

import javax.ejb.Stateless;

@Stateless
public class SessionBean1 implements Temperatura {
    @Override
    public int obtenerTemperatura()
    {
        return 23;
    }
}

5. Este es el código de la interfaz:

                      @Remote
                      public interface Temperatura {
                          public int obtenerTemperatura();
                      }


6. Crear el Cliente Remoto:
                 - Crear una aplicación java y marcar la opción Create Main Class
                 - Sobre la carpeta Libraries, agregar el JAR gf-client.jar que está en c:\glassfish3\glassfish\lib
                 - Sobre la carpeta Libraries, Add Project y luego seleccionar la ubicacion del proyecto de interfaz, creado en el punto 3

Agregar este código en el cliente remoto:

package cliente;

import org.empresa.prueba.Temperatura;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class Cliente {

    public static void main(String[] args) throws NamingException {
        try {
            Properties prop = new Properties();
         
            prop.setProperty("org.omg.CORBA.ORBInitialHost", "localhost");
            prop.setProperty("org.omg.CORBA.ORBInitialPort", "3700");
         
            InitialContext ctx = new InitialContext(prop);
         
            Temperatura temp = (Temperatura)ctx.lookup("java:global/EnterpriseApplication1/EJBModule1/SessionBean1");
         
            int t = temp.obtenerTemperatura();
         
            System.out.println("Temperatura: " + t);
        } catch (Exception e)
        {
            System.out.println("error!");
        }      
    }
}


7. Asegurarse que está corriendo GlassFish

8. Botón derecho sobre el Enterprise Application / Deploy

[SI NO FUNCIONA EL DEPLOY, verificar en la ficha "services" en netbeans, que no haya ninguna conexión rota a Java DB]

9. Seleccionar el proyecto del cliente remoto, y luego poner play [el PLAY se ejecuta siempre sobre lo que esté seleccionado. Si se elije el EBJ por ej, y se da PLAY, da error!]

PASOS PARA CONVERTIR EL SESSION BEAN EN UN WEBSERVICE

1. Cambiar el código del session bean para que quede así:

package org.empresa.prueba;

import javax.ejb.Stateless;
import javax.jws.WebMethod;
import javax.jws.WebService;

@Stateless
@WebService
public class SessionBean1 implements Temperatura {
    @Override
    public int obtenerTemperatura()
    {
        return 34;
    }
 
    @WebMethod
    public String sayHello(String name) {
        return "HELLO!!";
    }
}

2. Hacer deploy del enterprise application.

3. Para testear el webservice:
                 abrir el admin de GlassFish (http://localhost:4848)
                 click en Applications
                 click en el Enterprise Application que corresponda
                 buscar el nombre del EJB y click en View Endpoint
                 hacer click en la url que dice Tester

4. SI SE HACEN CAMBIOS, HAY QUE HACER DEPLOY DEL ENTERPRISE APPLICATION, SI SE HACE SOLO DEL MODULO EJB, DA ERROR!!

CLIENTE DEL WEBSERVICE

1. Crear una clase java para el webservice:

package cliente;

import javax.jws.WebService;
import javax.jws.WebMethod;

@WebService
public class Hello {
    private String message = new String("Hello, ");

    public void Hello() {
    }

    @WebMethod
    public String sayHello(String name) {
        return message + name + ".";
    }
}


2. Crear el cliente:

package cliente;

import javax.naming.NamingException;
import javax.xml.ws.WebServiceRef;

public class Cliente {
    @WebServiceRef(wsdlLocation="http://localhost:8080/SessionBean1Service/SessionBean1?wsdl")
    static Hello service;

    public static void main(String[] args) throws NamingException {
        try {                    
            Hello h = new Hello();
                         
            String s = h.sayHello("abc");                      
            System.out.println(s);
         
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Logger log4net en C# (para una aplicacion de escritorio)

Ejemplo de un Rolling log file appender: en este ejemplo, se guarda el log en un archivo de texto, con tamaño máximo de 10Mb (atributo: maximumFileSize).

Cuando se llega al tamaño máximo se sobreescribe el archivo, dejando hasta 5 archivos de backup (atributo: maxSizeRollBackups)

1. Descargar las dll's de log4j desde esta ubicación:

http://apache.mirrors.pair.com//logging/log4net/binaries/log4net-1.2.13-bin-newkey.zip
(http://logging.apache.org/log4net/download_log4net.cgi)

2. Agregar una referencia al archivo log4net.dll

3. En App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>

  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="c:\log\MySampleLogFile.log" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <filter type="log4net.Filter.LoggerMatchFilter">
        <loggerToMatch value="Amazon" />
        <acceptOnMatch value="false" />
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
      </layout>
    </appender>
  </log4net>

</configuration>


4. Ejemplo de uso:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using log4net.Config;

namespace log1
{
    class Program
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(Program));


        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();        

            for (int i = 0; i < 100; i++)
            {
                logger.Debug("Log de debug");
                logger.Info("Log informativo");
                logger.Warn("Log de warning");
                logger.Error("Log de error");
                logger.Fatal("Log de error fatal");
            }
        }
    }
}


Consultas SQL estándar con SqlQuery en Data Entity Framework

        class Cliente
        {
            public int Id {get; set;}
            public string Nombre {get; set;}
        }

        public IEnumerable<Cliente> leerClientesPorAPEPAT(String apepat)
        {
            var db = new X_XEntities();

            var parameter = new SqlParameter("@param", String.Format("%{0}%", apepat));

            var c = db.Database.SqlQuery<Cliente>("select top 500 id, nombre from Cliente " +
                                                                              "where tipper = 1 and " +
                                                                              "(apepat like @param) ", parameter);

            return c;
        }

Pure black and white con GIMP

-Colors/Desaturate (removes all color)
- Colors/Threshold (only keeps two levels, adjust threshold to taste)