Crear un aspmenu por código

Menu m = new Menu();
XmlDataSource x = new XmlDataSource();
x.DataBind(); 

x.EnableCaching = false;
m.MaximumDynamicDisplayLevels = 4;

m.StaticDisplayLevels = 10;
m.DynamicHorizontalOffset = 1;

m.DynamicVerticalOffset=1;

string s = "" + "";
x.Data = s;
m.DataSource = x;
m.DataBind();
form1.Controls.Add(m);

Zip y Unzip desde Excel VBA

Fuente: http://www.rondebruin.nl/windowsxpzip.htm


Sub Unzip1()
    Dim FSO As Object
    Dim oApp As Object
    Dim FName As Variant
    Dim FileNameFolder As Variant
    Dim DefPath As String
    Dim strDate As String

    FName = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
                                        MultiSelect:=False)
    If FName = False Then
        'Do nothing
    Else
        'Root folder for the new folder.
        'You can also use DefPath = "C:\Users\Ron\test\"
        DefPath = Application.DefaultFilePath
        If Right(DefPath, 1) <> "\" Then
            DefPath = DefPath & "\"
        End If

        'Create the folder name
        strDate = Format(Now, " dd-mm-yy h-mm-ss")
        FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\"

        'Make the normal folder in DefPath
        MkDir FileNameFolder

        'Extract the files into the newly created folder
        Set oApp = CreateObject("Shell.Application")

        oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(FName).items

        'If you want to extract only one file you can use this:
        'oApp.Namespace(FileNameFolder).CopyHere _
         'oApp.Namespace(Fname).items.Item("test.txt")

        MsgBox "You find the files here: " & FileNameFolder

        On Error Resume Next
        Set FSO = CreateObject("scripting.filesystemobject")
        FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
    End If
End Sub


Sub Zip_File_Or_Files()
    Dim strDate As String, DefPath As String, sFName As String
    Dim oApp As Object, iCtr As Long, I As Integer
    Dim FName, vArr, FileNameZip

    DefPath = Application.DefaultFilePath
    If Right(DefPath, 1) <> "\" Then
        DefPath = DefPath & "\"
    End If

    strDate = Format(Now, " dd-mmm-yy h-mm-ss")
    FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"

    'Browse to the file(s), use the Ctrl key to select more files
    FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
                    MultiSelect:=True, Title:="Select the files you want to zip")
    If IsArray(FName) = False Then
        'do nothing
    Else
        'Create empty Zip File
        NewZip (FileNameZip)
        Set oApp = CreateObject("Shell.Application")
        I = 0
        For iCtr = LBound(FName) To UBound(FName)
            vArr = Split97(FName(iCtr), "\")
            sFName = vArr(UBound(vArr))
            If bIsBookOpen(sFName) Then
                MsgBox "You can't zip a file that is open!" & vbLf & _
                       "Please close it and try again: " & FName(iCtr)
            Else
                'Copy the file to the compressed folder
                I = I + 1
                oApp.Namespace(FileNameZip).CopyHere FName(iCtr)

                'Keep script waiting until Compressing is done
                On Error Resume Next
                Do Until oApp.Namespace(FileNameZip).items.Count = I
                    Application.Wait (Now + TimeValue("0:00:01"))
                Loop
                On Error GoTo 0
            End If
        Next iCtr

        MsgBox "You find the zipfile here: " & FileNameZip
    End If
End Sub

Sub NewZip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
    If Len(Dir(sPath)) > 0 Then Kill sPath
    Open sPath For Output As #1
    Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    Close #1
End Sub


Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Rob Bovey
    On Error Resume Next
    bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function


Function Split97(sStr As Variant, sdelim As String) As Variant
'Tom Ogilvy
    Split97 = Evaluate("{""" & _
                       Application.Substitute(sStr, sdelim, """,""") & """}")
End Function


Agregar fichas y botones personalizados a Office 2007

Mediante Microsoft Office 2007 Custom UI Editor es posible agregar elementos al "ribbon" de Office y vincularlos con métodos escritos en VBA. Estos son los pasos:

Se puede descargar el Custom UI Editor desde el sitio OpenXML Developer

Cargar en el Custom UI Editor el archivo de Office al que se le quiere agregar una custom ribbon

Editando el xml se pueden agregar elementos.
En este ejemplo, se agrega una ficha llamada "Procesos Especiales" y dos botones "Cargar" y "Grabar"














En el campo onAction se debe especificar un nombre de método, que será creado luego en VBA de esta forma:


Sub rxbtn_Click(control As IRibbonControl)
    If control.ID = "btn_Cargar" Then
        Cargar
    Else
        If control.ID = "btn_Grabar" Then
            Grabar
        End If
    End If
End Sub

Este método debe ir en un módulo global (no en una hoja)

Al grabarlo, el resultado es el siguiente:












Como asignar íconos a los botones.

Bajar la galería de íconos para Office desde esta ubicación

Abrir el excel de la galería.

Habilitar la ficha "programador" (botón de Office/opciones de excel/Mostrar ficha programador en la cinta de opciones)

Elegir una galería y hacer click en el ícono que se desee utilizar.
























Al hacer click sobre el ícono aparece el nombre: imageMSO: DatabasePermissionsMenu

Este es el nombre que debe utilizarse en el xml (ver imágen de arriba), de esta forma:

 imageMso=DatabasePermissionsMenu


Otro link interesante: Visual Ribbon Editor

Lista de IDs de elementos de Office: Office Control IDs Excel2007 




Como formatear los tags pre para que queden como en este blog

pre {
overflow: auto;
padding-left: 15px;
padding-right: 15px;
font-size: 11px;
line-height: 15px;
margin-top: 10px;
width: 93%;
display: block;
background-color: #eeeeee;
color: #000000;
max-height: 300px;
}

Hacer que el sonido del micrófono salga por los parlantes

Crear un archivo con extensión .reg y copiar el siguiente código:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Class\{4D36E96C-E325-11CE-BFC1-08002BE10318}\0005\AD1981\Disable]
"MonR"=hex:01
"MicV"=hex:00

Luego ejecutarlo y listo.

Funcionó en mi notebook Compaq hp nx7400, puede ser que no funcione en otros modelos

Buscar texto dentro de cualquier tipo de archivo en Windows XP

Para este tip no es necesario iniciar el servicio de index server:

-Inicio / Buscar

-Click en "servicios de Index Server"

-Opciones avanzadas

-Click en "Mostrar/ocultar arbol de la consola"

-Click derecho en "Servicio de Index Server en el equipo local" / Propiedades

-Marcar "Indizar archivos con extensiones desconocidas"


Si se desea hacer con el registro, establecer en 1 el valor de DWORD del flag FilterFilesWithUnknownExtensions en la siguiente rama del registro:

HKEY_LOCAL_MACHINE\SYSTEM\ControlSet\Control\ContentIndex

Enviar mails desde vbscript con CDO

EnviarMail """Nombre destinatario"" ", "destinatario@abc.com", "prueba", "esta es una prueba de mail"

Sub EnviarMail(Origen, destinatario, Subject, body)
            Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory.
            Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network).
           
            Const cdoAnonymous = 0 'Do not authenticate
            Const cdoBasic = 1 'basic (clear-text) authentication
            Const cdoNTLM = 2 'NTLM
           
            Set objMessage = CreateObject("CDO.Message")
            objMessage.Subject = Subject
            objMessage.From = Origen
            objMessage.To = destinatario
            objMessage.TextBody = body
            objMessage.AddAttachment "c:\temp\11.txt"
           
            '==This section provides the configuration information for the remote SMTP server.
           
            objMessage.Configuration.Fields.Item _
            ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
           
            'Name or IP of Remote SMTP Server
            objMessage.Configuration.Fields.Item _
            ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "servidor.correo.net"
           
            'Type of authentication, NONE, Basic (Base64 encoded), NTLM
            objMessage.Configuration.Fields.Item _
            ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic
           
            'Your UserID on the SMTP server
            objMessage.Configuration.Fields.Item _
            ("http://schemas.microsoft.com/cdo/configuration/sendusername") = "userid@X.net"
           
            'Your password on the SMTP server
            objMessage.Configuration.Fields.Item _
            ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
           
            'Server port (typically 25)
            objMessage.Configuration.Fields.Item _
            ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
           
            'Use SSL for the connection (False or True)
            objMessage.Configuration.Fields.Item _
            ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = False
           
            'Connection Timeout in seconds (the maximum time CDO will try to establish a connection to the SMTP server)
            objMessage.Configuration.Fields.Item _
            ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
           
            objMessage.Configuration.Fields.Update
           
            '==End remote SMTP server configuration section==
           
            objMessage.Send
End Sub

Exportar e importar datos con BCP


bcp "select * from base..tabla" queryout c:\temp\out1.dat  -S
servidor\instancia -T -n -U usuario -P password
Para exportar: bcp PEPE out C:\pepe.csv -S Xsrv\sql2005 -d prueba -T -c importar: bcp PEPE2 in C:\pepe.csv -S Xsrv\sql2005 -d prueba -T -c

Deshabilitar teclas extendidas en teclados multimedia

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout]
"Scancode Map"=hex:00,00,00,00,00,00,00,00,03,00,00,00,00,00,6a,e0,00,00,69,e0,\
  00,00,00,00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout\DosKeybCodes]
"00000402"="bg"
"00000404"="ch"
"00000405"="cz"
"00000406"="dk"
"00000407"="gr"
"00000408"="gk"
"00000409"="us"
"0000040A"="sp"
"0000040B"="su"
"0000040C"="fr"
"0000040E"="hu"
"0000040F"="is"
"00000410"="it"
"00000411"="jp"
"00000412"="ko"
"00000413"="nl"
"00000414"="no"
"00000415"="pl"
"00000416"="br"
"00000418"="ro"
"00000419"="ru"
"0000041A"="yu"
"0000041B"="sl"
"0000041C"="us"
"0000041D"="sv"
"0000041F"="tr"
"00000422"="us"
"00000423"="us"
"00000424"="yu"
"00000425"="et"
"00000426"="us"
"00000427"="us"
"00000804"="ch"
"00000807"="sg"
"00000809"="uk"
"0000080A"="la"
"0000080C"="be"
"00000813"="be"
"00000816"="po"
"00000C0C"="cf"
"00000C1A"="us"
"00001009"="us"
"0000100C"="sf"
"00001809"="us"
"00010402"="us"
"00010405"="cz"
"00010407"="gr"
"00010408"="gk"
"00010409"="dv"
"0001040A"="sp"
"0001040E"="hu"
"00010410"="it"
"00010415"="pl"
"00010419"="ru"
"0001041B"="sl"
"0001041F"="tr"
"00010426"="us"
"00010C0C"="cf"
"00010C1A"="us"
"00020408"="gk"
"00020409"="us"
"00030409"="usl"
"00040409"="usr"
"00050408"="gk"

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout\DosKeybIDs]
"00000410"="141"
"0000041F"="179"
"00010408"="220"
"00010410"="142"
"00010415"="214"
"0001041F"="440"
"00020408"="319"

Elegir de listas en Excel 2007

Ir a ficha Datos/Validación/Configuración/Lista/Elegir Rango





Redirigir la salida estándar a la impresora en Java


import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; /**  * Main.java  *  * @author www.javadb.com  */ public class Main {          /**      * Redirects System.out and sends all data to a file.      *      */     public void redirectSystemOut() {                  try {                          System.setOut(new PrintStream(new FileOutputStream("system_out.txt")));                      } catch (FileNotFoundException ex) {             ex.printStackTrace();             return;         }                  System.out.println("This won't get displayed on the console, but sent to the file system_out.txt");              }     /**      * Starts the program      *      * @param args the command line arguments      */     public static void main(String[] args) {         new Main().redirectSystemOut();     } }

Instalar PHP sobre IIS

La instalación sobre NT y 2000 puede variar ligeramente entre diferentes versiones, pero siguiendo estas líneas seguramente conseguiremos hacer funcionar el PHP. Este documento está basado en el archivo ReadMe que se incluye con el PHP, pero que con frecuencia nos olvidamos de que existe o nos parece demasiado complicado, o sencillamente, ¡qué diablos!... si está en castellano...

Descomprimir el archivo php-4.0.2-Win32.zip (o más reciente) desde es.php.net


Meter todos los archivos en una carpeta, como por ejemplo "c:php"


Copiar las .dlls necesarias (básicamente msvcrt.dll y php4ts.dll) en la carpeta c:\Windows\System (dejar, sobretodo php4isapi.dll en la carpeta c:\php)


Ir al Administrador de Servicios de Internet. Puede estar en alguno de estos sitios

Inicio -> Configuración -> Paneles de control

Inicio -> Programas -> Windows NT 4.0 Option Pack -> Personal Web Server

Inicio -> Configuración -> Paneles de control -> Herramientas Administrativas (en Windows 2000)


Buscamos el item de nuestro servidor Web (suele aparecer como "Sitio Web Predeterminado")


Con el botón derecho, seleccionar en el menú emergente Propiedades


Ir a la pestaña "ISAPI filters", y Añadir un nuevo filtro. Como nombre le pondremos "PHP" y como ejecutable, "C:\php\php4isapi.dll" (o dondequiera que hayamos instalado dicha dll.


Ir a la pestaña "Home Directory". En la sección de "Application Settings", pulsar el botón "Configuration...". Añadir un nuevo "Application Mapping": el ejecutable es el mismo de antes: "C:\php\php4isapi.dll". La extensión es ".php" (ojo, con un punto delante). Marcar "All verbs" (esto creo que puede variar según la versión del IIS, pero si no es esto, dejarlo como está). Verificar que esté marcado "Script Engine".


Aceptar los cambios y reinciar el servidor Web. Puede que no sea suficiente con hacerlo desde la consola, poniendo Detener y luego Iniciar. Lo mejor es ir directamente al panel de configuración "Servicios" y desde allí detener completamente el servicio de publicación en Internet, y luego reiniciarlo.

Una forma de hacer este último paso es desde la consola de Windows, escribiendo:

C:\>net stop iisadmin

para detener el servicio

C:\>net start w3svc

para volverlo a iniciar


Hacer una página de prueba y acceder a ella. Por ejemplo, abrimos un archivo nuevo con el Notepad y escribimos en él lo siguiente:


<HTML>
<HEAD>
<TITLE>Página de prueba de instalación de PHP</TITLE>
</HEAD>
<BODY>
<?
phpinfo();
?>
</BODY>
</HTML>
Guardarlo como prueba.php en la carpeta de publicación. Para probarla abrimos un navegador y en la barra de URL escribimos (suponiendo que nuestro directorio virtual se llama phphome :

http://localhost/phphome/prueba.php



Nota: Si no queremos utilizar autentificación de usuarios HTTP (HTTP-Auth) deberíamos saltarnos el paso 7 (instalación de filtros ISAPI)

Configuración de TinyMCE

Incluir este código dentro del tag <head>:

<script language="javascript" type="text/javascript" src="tinymce/jscripts/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "advanced",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left"
});
</script>