martes, 12 de abril de 2011

Mostrar ficheros ocultos en MacOSX

Hoy escribo un pequeño truco que me reportó Javier fernandez de Syderis para poder ver en una ventana del finder en MacOSX los ficheros y directorios ocultos. Esto es un poco más rebuscado que en sistemas como Windows y no tenemos una propiedad fácilmente modificable. Necesitamos modificar la variable AppleShowAllFiles que es un bool y ponerla a true ya que por defecto viene a false, para ello:

Abrimos un terminal y ponemos:

Mostrar ficheros ocultos:
defaults write com.apple.finder AppleShowAllFiles TRUE

killall Finder


Ocultar ficheros ocultos:
defaults write com.apple.finder AppleShowAllFiles FALSE

killall Finder

martes, 22 de marzo de 2011

Crear un fichero de cualquier tamaño

Hoy estamos configurando el NAS y necesitamos ficheros de tamaños determinados para probar cuotas de espacio en disco. Para esto es muy util poder crear un fichero de un fichero determinado. Para esto en sistemas deribados de UNIX como MacOSX o la famila Linux tenemos el comando dd que nos ayudará a esta tarea. Dejo este pequeño tip que espero le sea de utilidad a muchos de vosotros.

Nos posicionamos en la carpeta donde queramos dejar el fichero
cd /tmp

Creamos un fichero de 50MGs
dd if=/dev/zero of=archivo50megas.txt bs=1024 count=51200

if - archivo de entrada (cogemos basura del dispositivo zero)
of - archivo de salida (el nombre de nuestro fichero)
bs - tamaño de bloque bytes (1024 indica bloques de 1k)
count - Número de bloques (51200 = 50*1024(Mg))

viernes, 19 de noviembre de 2010

Lanzar aplicaciones con retraso al iniciar windows 7

Como todos sabéis Windows tiene varios mecanismos para lanzar aplicaciones en el arranque del sistema operativo. La fórmula más conocida es colocar un acceso directo en la carpeta "Inicio". Pero hoy me encuentro con el problema de lanzar una aplicación que hace uso de la tarjeta gráfica y el problema consiste es que al poner la aplicación en la carpeta de Inicio esta se lanza antes de que se cargue el servicio de DirectX por lo que la aplicación da un fallo de no estar aún enable dichas funcionalidades. La manera de resolver el problema ha sido construir un pequeño script en bacth (lenguaje de script de MS-DOS) para que espero lo necesario hasta que los servicios gráficos hayan sido cargados.

Os dejo el script:

---------------------
@echo off
timeout 30
start chrome
------------------
"@echo off" -> no imprima la salida de los comandos por la consola
"timeout 30" -> espere 30 segundos (tiempo suficiente para el arranque de todos los servicios de windows 7
"start chrome" -> arrancar la aplicación

Lo guardais como loquequerais.bat y lo colocais en la carpeta de "Inicio"


Sintasis del comando start
Syntax
      START "title" [/Dpath] [options] "command" [parameters]

Key:
   title      : Text for the CMD window title bar (required)
   path       : Starting directory
   command    : The command, batch file or executable program to run
   parameters : The parameters passed to the command

Options:
   /MIN       : Minimized
   /MAX       : Maximized
   /WAIT      : Start application and wait for it to terminate
   /LOW       : Use IDLE priority class
   /NORMAL    : Use NORMAL priority class
   /HIGH      : Use HIGH priority class
   /REALTIME  : Use REALTIME priority class

   /B         : Start application without creating a new window. In this case
                ^C will be ignored - leaving ^Break as the only way to
                interrupt the application
   /I         : Ignore any changes to the current environment.

   Options for 16-bit WINDOWS programs only

   /SEPARATE   Start in separate memory space (more robust)
   /SHARED     Start in shared memory space (default)

miércoles, 27 de octubre de 2010

Mi primera DLL

Hoy he decidido grabarme un video construyendo una dll básica en c++ y consumiendola desde una aplicación de consola en c++ porque es una tarea util cuando necesitas hacer un wrapper de una librería en c o c++ y usarla desde otros lenguajes como c#. Aunque es algo muy fácil me cuesta muchas veces recordar la nomenglatura de ahí la idea de este tutorial espero que os sea útil para arrancar vuestros proyectos.




El codigo fuente de la dll sería:


#include "stdafx.h"

#define DLL_EXPORT extern "C" __declspec(dllexport)

DLL_EXPORT double Sum(double a, double b);

double Sum(double a, double b)
{
return a+b;
}



y el de la clase en c++ que lo consume sería:


#include "stdafx.h"

#include <iostream>

extern "C" __declspec(dllimport)double Sum(double a, double b);

using namespace std;

int main(){
cout << "hola dll" << endl;
cout << "La suma de 2 + 3 es:" << Sum(2,3);

getchar();
return 0;
}


Y ahora en este segundo video creo un proyecto de consola de c# desde
el cual también consumiremos los métodos de nuestra DLL.



El código de la clase Wrapper:


namespace UseDLLCSharp
{
    class WrapperDLL
    {
        [DllImport("DLL.dll")]
        public static extern double Sum(double a, double b);
    }
}



El código de la clase principal de C#:


namespace UseDLLCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hola mundo");
            Console.WriteLine("La suma de 3 + 2 es: " + WrapperDLL.Sum(3, 2));

            Thread.Sleep(5000);
        }
    }
}

martes, 19 de octubre de 2010

La evolución de un programador

Hoy encontré un artículo super divertido sobre la evolución que sufre una programador al ir ascendiendo de cargo o rango con los años, no es perdáis el final.


High School/Jr.High

  10 PRINT "HELLO WORLD"
  20 END

First year in College

  program Hello(input, output)
    begin
      writeln('Hello World')
    end.

Senior year in College

  (defun hello
    (print
      (cons 'Hello (list 'World))))

New professional

  #include <stdio.h>
  void main(void)
  {
    char *message[] = {"Hello ", "World"};
    int i;

    for(i = 0; i < 2; ++i)
      printf("%s", message[i]);
    printf("\n");
  }

Seasoned professional

  #include <iostream.h>
  #include <string.h>

  class string
  {
  private:
    int size;
    char *ptr;

  string() : size(0), ptr(new char[1]) { ptr[0] = 0; }

    string(const string &s) : size(s.size)
    {
      ptr = new char[size + 1];
      strcpy(ptr, s.ptr);
    }

    ~string()
    {
      delete [] ptr;
    }

    friend ostream &operator <<(ostream &, const string &);
    string &operator=(const char *);
  };

  ostream &operator<<(ostream &stream, const string &s)
  {
    return(stream << s.ptr);
  }

  string &string::operator=(const char *chrs)
  {
    if (this != &chrs)
    {
      delete [] ptr;
     size = strlen(chrs);
      ptr = new char[size + 1];
      strcpy(ptr, chrs);
    }
    return(*this);
  }

  int main()
  {
    string str;

    str = "Hello World";
    cout << str << endl;

    return(0);
  }

Master Programmer

  [
  uuid(2573F8F4-CFEE-101A-9A9F-00AA00342820)
  ]
  library LHello
  {
      // bring in the master library
      importlib("actimp.tlb");
      importlib("actexp.tlb");

      // bring in my interfaces
      #include "pshlo.idl"

      [
      uuid(2573F8F5-CFEE-101A-9A9F-00AA00342820)
      ]
      cotype THello
   {
   interface IHello;
   interface IPersistFile;
   };
  };

  [
  exe,
  uuid(2573F890-CFEE-101A-9A9F-00AA00342820)
  ]
  module CHelloLib
  {

      // some code related header files
      importheader(<windows.h>);
      importheader(<ole2.h>);
      importheader(<except.hxx>);
      importheader("pshlo.h");
      importheader("shlo.hxx");
      importheader("mycls.hxx");

      // needed typelibs
      importlib("actimp.tlb");
      importlib("actexp.tlb");
      importlib("thlo.tlb");

      [
      uuid(2573F891-CFEE-101A-9A9F-00AA00342820),
      aggregatable
      ]
      coclass CHello
   {
   cotype THello;
   };
  };


  #include "ipfix.hxx"

  extern HANDLE hEvent;

  class CHello : public CHelloBase
  {
  public:
      IPFIX(CLSID_CHello);

      CHello(IUnknown *pUnk);
      ~CHello();

      HRESULT  __stdcall PrintSz(LPWSTR pwszString);

  private:
      static int cObjRef;
  };


  #include <windows.h>
  #include <ole2.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include "thlo.h"
  #include "pshlo.h"
  #include "shlo.hxx"
  #include "mycls.hxx"

  int CHello::cObjRef = 0;

  CHello::CHello(IUnknown *pUnk) : CHelloBase(pUnk)
  {
      cObjRef++;
      return;
  }

  HRESULT  __stdcall  CHello::PrintSz(LPWSTR pwszString)
  {
      printf("%ws
", pwszString);
      return(ResultFromScode(S_OK));
  }


  CHello::~CHello(void)
  {

  // when the object count goes to zero, stop the server
  cObjRef--;
  if( cObjRef == 0 )
      PulseEvent(hEvent);

  return;
  }

  #include <windows.h>
  #include <ole2.h>
  #include "pshlo.h"
  #include "shlo.hxx"
  #include "mycls.hxx"

  HANDLE hEvent;

   int _cdecl main(
  int argc,
  char * argv[]
  ) {
  ULONG ulRef;
  DWORD dwRegistration;
  CHelloCF *pCF = new CHelloCF();

  hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

  // Initialize the OLE libraries
  CoInitializeEx(NULL, COINIT_MULTITHREADED);

  CoRegisterClassObject(CLSID_CHello, pCF, CLSCTX_LOCAL_SERVER,
      REGCLS_MULTIPLEUSE, &dwRegistration);

  // wait on an event to stop
  WaitForSingleObject(hEvent, INFINITE);

  // revoke and release the class object
  CoRevokeClassObject(dwRegistration);
  ulRef = pCF->Release();

  // Tell OLE we are going away.
  CoUninitialize();

  return(0); }

  extern CLSID CLSID_CHello;
  extern UUID LIBID_CHelloLib;

  CLSID CLSID_CHello = { /* 2573F891-CFEE-101A-9A9F-00AA00342820 */
      0x2573F891,
      0xCFEE,
      0x101A,
      { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 }
  };

  UUID LIBID_CHelloLib = { /* 2573F890-CFEE-101A-9A9F-00AA00342820 */
      0x2573F890,
      0xCFEE,
      0x101A,
      { 0x9A, 0x9F, 0x00, 0xAA, 0x00, 0x34, 0x28, 0x20 }
  };

  #include <windows.h>
  #include <ole2.h>
  #include <stdlib.h>
  #include <string.h>
  #include <stdio.h>
  #include "pshlo.h"
  #include "shlo.hxx"
  #include "clsid.h"

  int _cdecl main(
  int argc,
  char * argv[]
  ) {
  HRESULT  hRslt;
  IHello        *pHello;
  ULONG  ulCnt;
  IMoniker * pmk;
  WCHAR  wcsT[_MAX_PATH];
  WCHAR  wcsPath[2 * _MAX_PATH];

  // get object path
  wcsPath[0] = '\0';
  wcsT[0] = '\0';
  if( argc > 1) {
      mbstowcs(wcsPath, argv[1], strlen(argv[1]) + 1);
      wcsupr(wcsPath);
      }
  else {
      fprintf(stderr, "Object path must be specified\n");
      return(1);
      }

  // get print string
  if(argc > 2)
      mbstowcs(wcsT, argv[2], strlen(argv[2]) + 1);
  else
      wcscpy(wcsT, L"Hello World");

  printf("Linking to object %ws\n", wcsPath);
  printf("Text String %ws\n", wcsT);

  // Initialize the OLE libraries
  hRslt = CoInitializeEx(NULL, COINIT_MULTITHREADED);

  if(SUCCEEDED(hRslt)) {


      hRslt = CreateFileMoniker(wcsPath, &pmk);
      if(SUCCEEDED(hRslt))
   hRslt = BindMoniker(pmk, 0, IID_IHello, (void **)&pHello);

      if(SUCCEEDED(hRslt)) {

   // print a string out
   pHello->PrintSz(wcsT);

   Sleep(2000);
   ulCnt = pHello->Release();
   }
      else
   printf("Failure to connect, status: %lx", hRslt);

      // Tell OLE we are going away.
      CoUninitialize();
      }

  return(0);
  }

Apprentice Hacker

  #!/usr/local/bin/perl
  $msg="Hello, world.\n";
  if ($#ARGV >= 0) {
    while(defined($arg=shift(@ARGV))) {
      $outfilename = $arg;
      open(FILE, ">" . $outfilename) || die "Can't write $arg: $!\n";
      print (FILE $msg);
      close(FILE) || die "Can't close $arg: $!\n";
    }
  } else {
    print ($msg);
  }
  1;

Experienced Hacker

  #include <stdio.h>
  #define S "Hello, World\n"
  main(){exit(printf(S) == strlen(S) ? 0 : 1);}

Seasoned Hacker

  % cc -o a.out ~/src/misc/hw/hw.c
  % a.out

Guru Hacker

  % echo "Hello, world."

New Manager

  10 PRINT "HELLO WORLD"
  20 END

Middle Manager

  mail -s "Hello, world." bob@b12
  Bob, could you please write me a program that prints "Hello, world."?
  I need it by tomorrow.
  ^D

Senior Manager

  % zmail jim
  I need a "Hello, world." program by this afternoon.

Chief Executive

  % letter
  letter: Command not found.
  % mail
  To: ^X ^F ^C
  % help mail
  help: Command not found.
  % damn!
  !: Event unrecognized
  % logout



(Lo encontre en fuente)

martes, 3 de agosto de 2010

Renombrar ficheros desde Java

Hoy tuve que hacer un programita muy tonto pero que me quitó muchas horas
de trabajo de monos, así que os dejo el código por si a alguien le sirve
del mismo modo que a mí.

El programa lo que hace es renombrar todos los ficheros de un directorio
desde java. Este directorio estaba lleno de imagenes en formato png y lo
que tuve que hacer es añadir al final del nombre la coletilla "_thumb" que
viene de thumbnail.

Código


package renombradodeficheros;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
*
* @author Jorge
*/
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        
        String path = "resources/directory/";

        File directory = new File(path);
        String[] files = directory.list();
        File f1,f2;
        String filename, filenameModif;
        int cutindex;
        for (int i = 0; i < files.length; i++) {

            filename = files[i];
            f1 = new File(path+"/"+filename);
            cutindex = filename.indexOf(".png");
            if (cutindex != -1)
            {
                filenameModif = filename.substring(0, cutindex)+"_thumb.png";
                f2 = new File(path+"/"+filenameModif);
                if (f1.renameTo(f2))
                    System.out.println("Renombrado");
                else
                    System.out.println("Fallo al renombrar");
            }
        }
    }
}

Trabajar con XML y C#

Hola a todos,

Hace tiempo que no escribo en el blog pero es que últimamente ando muy muy liado con los diferentes proyectos que estamos desarrollando en Syderis. Hoy os pongo un pequeño ejemplo de como leer y escribir XML con la API de .NET framework y C#.

Dado el xml:

<?xml version="1.0" encoding="utf-8" ?>
<sample>
<equipments>
   <equipment type="tipo1">
     <point x="1900" y="1000">
       <title>Titulo</title>
       <image >DSCN2903</image>
       <description>Esta es la descripción del primer punto</description>    
     </point>
     <point x="1000" y="2300">
       <title>Titulo</title>
       <image />DSCN2903
       <description>mirador2</description>    
     </point>
   </equipment>
</equipments>
</sample>



Código del lector:


public void Read(string filename)
       {
           XmlDocument xml = new XmlDocument();
           try
           {
               xml.Load(filename);
               XmlNodeList nodeEquipments = xml.GetElementsByTagName("Equipments");

               //Equipamientos
               XmlNodeList equipmentsNodes = ((XmlElement)nodeEquipments[0]).GetElementsByTagName("equipment");
               string sfilename;
               string stitle;
               string sdescription;
               string sx, sy;
               foreach (XmlElement equipment in equipmentsNodes)
               {
                   string stype = equipment.GetAttribute("type");
                   XmlNodeList pointsNodes = equipment.GetElementsByTagName("point");
                            
                          
                   foreach (XmlElement pointNode in pointsNodes)
                   {
                       sx = pointNode.GetAttribute("x");
                       sy = pointNode.GetAttribute("y");
                       stitle = pointNode.GetElementsByTagName("title")[0].InnerText;
                       sfilename = pointNode.GetElementsByTagName("image")[0].InnerText;
                       sdescription = pointNode.GetElementsByTagName("description")[0].InnerText;                      
                       Console.Writeline("type:"+stype+" coord:"+sx+sy+" filename"+sfilename+" title:"stitle+" description:"+sdescription);

                   }
              
               }
          
           }
           catch (XmlException e)
           {
               Console.WriteLine("XML file load Failure." + e.ToString());
           }
}




Código escritor:


public void Write(string filename)
       {
           XmlTextWriter xmlWriter = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
           xmlWriter.Formatting = Formatting.Indented;
           xmlWriter.WriteStartDocument();

           xmlWriter.WriteStartElement("Sample");

           //Equipments
           xmlWriter.WriteStartElement("Equipments");

           foreach (string etype in equipments.keys)
           {
               xmlWriter.WriteStartElement("equipment");
               xmlWriter.WriteAttributeString("type", etype);

               foreach (Equipment e in equipments[etype])
               {
                   //<point x="100" y="100">
                   xmlWriter.WriteStartElement("point");
                   xmlWriter.WriteAttributeString("x", e.Point.X.ToString());
                   xmlWriter.WriteAttributeString("y", e.Point.Y.ToString());

                   xmlWriter.WriteStartElement("title");
                   xmlWriter.WriteString(e.Title);
                   xmlWriter.WriteEndElement();

                   //<image />filename
                   xmlWriter.WriteStartElement("image");
                   xmlWriter.WriteString(e.Image);
                   xmlWriter.WriteEndElement();

                   //<description>mirador</description>
                   xmlWriter.WriteStartElement("description");
                   xmlWriter.WriteString(e.Description);
                   xmlWriter.WriteEndElement();

                   xmlWriter.WriteEndElement(); // End point
               }
               xmlWriter.WriteEndElement(); //End equipment
           }

           xmlWriter.WriteEndElement(); //End Equipments

           xmlWriter.WriteEndElement(); //End Sample

           xmlWriter.Flush();
           xmlWriter.Close();

       }