Mostrando entradas con la etiqueta tricks. Mostrar todas las entradas
Mostrando entradas con la etiqueta tricks. Mostrar todas las entradas

jueves, 19 de septiembre de 2013

Averiguar el titulo de una cancion o audio

Este programa que acabo de encontrar se llama Tunatic y básicamente sirve para saber títulos de canciones que oímos en cualquier sitio y no sabemos el titulo. Os voy a poner un ejemplo. Yo estaba viendo este vídeo.
No tengo ni idea de quien canta esta canción que sale en el vídeo y no tengo manera posible de averiguarlo. Normalmente en los vídeos de Youtube alguien suele preguntar ese tipo de cosas. Yo soy uno de ellos. Ahora viene lo bueno. Me pongo a buscar por Google y me encuentro con este programa.
DESCARGAR
Para XP/2000/Vista (También va pero no lo pone)
También lo tenéis disponible en la pagina los usuarios de MAC
Instalo el programa y lo ejecuto, le doy al PLAY del vídeo del antes y me sale esto en la pantalla de mi portátil.

domingo, 9 de junio de 2013

Algunos Scripts para monitorear SQL Server

Para monitorear el estado de los jobs que fallaron en su última ejecución:
SELECT name FROM msdb.dbo.sysjobs A, msdb.dbo.sysjobservers B 
WHERE A.job_id = B.job_id AND B.last_run_outcome = 0
Espacio en cada disco para la instancia SQL:
EXEC master..xp_fixeddrives
el resultado lo probe en mi maquina y salio lo siguiente
Para ver un listado de Jobs Deshabilitados:
SELECT name FROM msdb.dbo.sysjobs 
WHERE enabled = 0 ORDER BY name
Para ver un listado de los jobs que están actualmente en ejecución:
msdb.dbo.sp_get_composite_job_info
NULL, NULL, NULL, NULL, NULL, NULL, 1, NULL, NULL
Para ver logines que son miembros de los roles de servidor (este script funciona en SQL 2000 pero no en SQL 2005 o superiores porque la tabla master.dbo.sysxlogins no existe):
SELECT 'ServerRole' = A.name, 'MemberName' =  B.name 
FROM master.dbo.spt_values A, master.dbo.sysxlogins B 
WHERE A.low = 0 AND A.type = 'SRV' AND B.srvid IS NULL
Para ver la última vez que las bases de datos fueron backupeadas:
SELECT  B.name as Database_Name, ISNULL(STR(ABS(DATEDIFF(day, GetDate(),
 MAX(Backup_finish_date)))), 'NEVER') as DaysSinceLastBackup,
 ISNULL(Convert(char(10), MAX(backup_finish_date), 101), 'NEVER') as LastBackupDate
 FROM master.dbo.sysdatabases B LEFT OUTER JOIN msdb.dbo.backupset A
 ON A.database_name = B.name AND A.type = 'D' GROUP BY B.Name ORDER BY B.name
Para leer las ultimas entradas del archivo de log (NO el transaction log):
CREATE TABLE #Errors (vchMessage varchar(255), ID int)
CREATE INDEX idx_msg ON #Errors(ID, vchMessage)
INSERT #Errors EXEC xp_readerrorlog
SELECT vchMessage
FROM #Errors
WHERE vchMessage
NOT LIKE '%Log backed up%' AND vchMessage
NOT LIKE '%.TRN%' AND vchMessage
NOT LIKE '%Database backed up%' AND vchMessage
NOT LIKE '%.BAK%' AND vchMessage
NOT LIKE '%Run the RECONFIGURE%' AND
vchMessage NOT LIKE '%Copyright (c)%'
ORDER BY ID

DROP TABLE #Errors

[SQL-2008] Buscar texto en definiciones de Objetos MS SQL Server.

Saludos amigos en esta ocasión les dejo un ejemplo de como poder buscar “Cadenas de Texto” en la definición de nuestros Procedimientos almacenados.
En este ejemplo vamos a buscar la palabra ‘HumanResources’ en los procedimientos almacenados de la base de datos ‘AdventureWorks2008’.
Necesitamos ejecutar el siguiente script con la cadena de texto que se va a buscar.
SELECT Name
FROM sys.procedures
WHERE OBJECT_DEFINITION(OBJECT_ID) LIKE '%HumanResources%'
GO
Si se encontraron resultados, a continuación se mostrara un listado con los nombres de los procedimientos almacenados que contienen nuestra palabra.
Bien amigos, para comprobar el resultado elegiremos uno de los procedimientos para ver su definición e identificar que contiene la palabra que buscamos ‘HumanResources’.
USE AdventureWorks2008;
EXEC sp_HelpText 'uspGetManagerEmployees'
Como pueden ver el resultado es sobre un Procedimiento almacenado de los de la lista que contienen la palabra a buscar, las palabras encerradas en color morado son las que coinciden con nuestra búsqueda, de esta manera podemos buscar lo que deseemos dentro de nuestros Stored Procedures y ver su definición rápidamente.
Bueno amigos, espero les sea de ayuda, espero sus comentarios y por favor voten por este blog.

viernes, 7 de junio de 2013

Obtener número de registros de varias tablas en SQL

Mira por donde, hoy estoy encontrando solución a varias cosillas que había querido hacer antes y por tiempo no me habían salido. En este caso, lo que pretendía era obtener el número de registros de todas las tablas de una base de datos, para saber cuales son las más pesadas. La manera rápida y potente que he encontrado es usar la tabla sysindexes. En mi caso la he usado de esta forma:
select object_name(id) nombreTabla, convert(varchar(50), cast(rowcnt as money),1) nRegistros from sysindexes
Si se quiere la de una tabla en concreto, se puede poner un where indicando el nombre de tabla:
select object_name(id) nombreTabla, convert(varchar(50), cast(rowcnt as money),1) nRegistros from sysindexes where id=object_id('Nombre de tabla')

jueves, 14 de marzo de 2013

Cambiarle el nombre a un archivo en Visual Basic.NET 2008


para este ejemplo agregamos 2 botones y en el boton examinar ponemos este codigo:
' presentar al usuario un cuadro de diálogo
        Dim openFile As New OpenFileDialog
        ' si elegimos algún archivo
        Dim result As DialogResult = openFile.ShowDialog()
        If result = DialogResult.OK Then
            TextBox1.Text = openFile.FileName
        End If
al pulsar el boton nos saldra este objeto:

Escribimos eln ombre del archivo en el textbox2 y al pulsar el boton Cambiar Nombre lo habra cambiado, para esto escribimos este codigo en el evento click del boton Cambiar Nombre
My.Computer.FileSystem.RenameFile(TextBox1.Text, TextBox2.Text)

lunes, 11 de marzo de 2013

Truco Visual Basic .NET 2008:Paginando el gridview con Lista de paises en XML

Hola, quiero mostrar como podemos hacer una paginación elegante y un poco más funcional de nuestros afamado gridview.
Muchas veces, necesitamos y queremos q nuestra interfaz de usuario sea más amigable y bonita, puesto que lo que el usuario ve es la interfaz (muchas veces no le importa lo que está por detrás)…
En ejemplo vamos a cargar un gridview desde un archivo xml el cual contiene la lista de todos los paises del mundo (si falta alguno disculpen); dicha lista contine 241 paises, lo cual haría que nuestro gridview se extendiera demasiado hacia abajo, para evitar que esto suceda vamos a usar la paginación.
La idea es disponer de un dropdownlist el cual va a contener todas las páginas del gridview, así podremos cambiar de página facilmente. Además, se visualizará cuatros imagenes las cuales tendrán la función de ir al primer, anterior, siguiente y último registro.
Es decir, al final nuestro gridview debe lucir parecido a:

Para lograr esta funcionalidad, ahi varias cosas que se deben definir.
1.Establecer la propiedad AllowPaging=”true” del gridview
2.Establecer el número de filas o registros que deseamos ver por página en el grid (ej: PageSize=”10″)
3.Personalizar el pagertemplate.
4.En el dropdownlist del pagertemplate, se ha definido el evento OnSelectedIndexChanged=”GoPage”, en este evento vamos a cambiar el la página q estamos visualizando, asi en nuestro codebehind, vamos a definir un procedimiento protected (protected para que pueda ser accedido desde el html).

Además de los pasos anteriores es necesario
1.Definir el procedimiento para cargar el gridview
2.Añadir la lógica necesaria en el evento PageIndexChanging para que nuestros botones de navegación funcionen, en este caso, con la variable e podemos acceder al numero de la página a traves de la propiedad NewPageIndex.
3.En el evento RowDataBound del gridview, se debe cargar el dropdownlist; y el label para mostrar el número total de páginas.

Los eventos que van a programar son el RowDataBound
Protected Sub GridViewDatos_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridViewDatos.RowDataBound
        If e.Row.RowType = DataControlRowType.Pager AndAlso Not GridViewDatos.DataSource Is Nothing Then
            'TRAE EL TOTAL DE PAGINAS
            Dim _TotalPags As Label = e.Row.FindControl("lblTotalNumberOfPages")
            _TotalPags.Text = GridViewDatos.PageCount.ToString

            'LLENA LA LISTA CON EL NUMERO DE PAGINAS
            Dim list As DropDownList = e.Row.FindControl("paginasDropDownList")
            For i As Integer = 1 To CInt(GridViewDatos.PageCount)
                list.Items.Add(i.ToString)
            Next
            list.SelectedValue = GridViewDatos.PageIndex + 1
        End If
    End Sub
en el evento PageIndexChanging del DataGridView ponemos este codigo
Protected Sub GridViewDatos_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridViewDatos.PageIndexChanging
        GridViewDatos.PageIndex = e.NewPageIndex
        Call CargaGridView()
    End Sub
y la funcion CargaGridView tendra este codigo
Private Sub CargaGridView()
        Try
            Dim oDataSet As New DataSet
            oDataSet.ReadXml(Server.MapPath("~/App_Data/Paises.xml"))

            GridViewDatos.DataSource = oDataSet
            GridViewDatos.DataBind()
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub
para los que deseen el codigo completo aqui tienen el link

Descarga del ejemplo !

jueves, 7 de marzo de 2013

El efecto “Halo” truco SEO

El efecto Halo es más o menos así: posicionar una palabra en número 1 (o en posiciones elevadas en los resultados del motor de búsqueda) provoca que para el resto de palabras clave de la web o blogger aumenten también sus posiciones.
A esto se le conoce como efecto Halo, y se puede entender como que las palabras clave que mejoran su ranking en los buscadores y llevan al resto de las palabras clave, haciéndolas subir también en su posicionamiento.
Por este motivo es aconsejable centrarse en pocas palabras clave para posicionar (unas 15 estará bien, pero no superar las 25), haciendo un especial esfuerzo en posicionar unos términos antes que en otros, dejando para más adelante la mejora de posición de términos menos provechosos. Lo que podría pasar es más o menos esto, mejorar el posicionamiento únicamente por una sola palabra clave:

Un muy buen dato para mejorar tu posicionamiento en los principales navegadores como Google, Yahoo o Bing, el Efecto “Halo”.

sábado, 15 de diciembre de 2012

Validación con expresiones regulares en C#.NET

Las expresiones regulares son modelos que describen las combinaciones de caracteres en el texto. Se podrían definir como una serie de carácteres que forman un patrón, que representan a otro grupo de carácteres mayor, de tal forma que podemos comparar el patrón con otros conjuntos de carácteres para ver las coincidencias. Las expresiones regulares pueden utilizarse en múltiples lenguajes de programación pero en esta entrada vamos a ver un ejemplo de validación de formularios mediante Javascript y haciendo uso de expresiones regulares.
Un buen tutorial para iniciarse en el manejo de expresiones regulares lo podemos encontrar en Desarrolloweb. Para realizar el ejemplo siguiente no hay porque conocer en profundidad su manejo. A continuación muestro una serie de tablas a modo de chuleta para que podamos utilizarlas con un simple corta y pega.
La tabla siguiente contiene los caracteres especiales de las expresiones regulares.
Carácter Texto buscado
^ Principio de entrada o línea.
$ Fin de entrada o línea.
* El carácter anterior 0 o más veces.
+ El carácter anterior 1 o más veces.
? El carácter anterior una vez como máximo (es decir, indica que el carácter anterior es opcional).
. Cualquier carácter individual, salvo el de salto de línea.
x|y x o y.
{n} Exactamente n apariciones del carácter anterior.
{n,m} Como mínimo n y como máximo m apariciones del carácter anterior.
[abc] Cualquiera de los caracteres entre corchetes. Especifique un rango de caracteres con un guión (por ejemplo, [a-f] es equivalente a [abcdef]).
[^abc] Cualquier carácter que no esté entre corchetes. Especifique un rango de caracteres con un guión (por ejemplo, [^a-f] es equivalente a [^abcdef]).
\b Límite de palabra (como un espacio o un retorno de carro).
\B Cualquiera que no sea un límite de palabra.
\d Cualquier carácter de dígito. Equivalente a [0-9].
\D Cualquier carácter que no sea de dígito. Equivalente a [^0-9].
\f Salto de página.
\n Salto de línea.
\r Retorno de carro.
\s Cualquier carácter individual de espacio en blanco (espacios, tabulaciones, saltos de página o saltos de línea).
\S Cualquier carácter individual que no sea un espacio en blanco.
\t Tabulación.
\w Cualquier carácter alfanumérico, incluido el de subrayado. Equivalente a [A-Za-z0-9_].
\W Cualquier carácter que no sea alfanumérico. Equivalente a [^A-Za-z0-9_].
La tabla siguiente contiene algunos de los patrones más utilizados a la hora de validar formularios. Si alguien conoce alguna expresión regular más -que pueda ser útil en la validación de formularios- la puede poner en los comentarios y yo la incorporaré a esta tabla.
Cualquier letra en minuscula [a-z]
Entero ^(?:\+|-)?\d+$
Correo electrónico /[\w-\.]{3,}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}/
URL ^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)( [a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$
Contraseña segura (?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$(Entre 8 y 10 caracteres, por lo menos un digito y un alfanumérico, y no puede contener caracteres espaciales)
Fecha ^\d{1,2}\/\d{1,2}\/\d{2,4}$(Por ejemplo 01/01/2007)
Hora ^(0[1-9]|1\d|2[0-3]):([0-5]\d):([0-5]\d)$(Por ejemplo 10:45:23)
Número tarjeta de crédito ^((67\d{2})|(4\d{3})|(5[1-5]\d{2})|(6011))(-?\s?\d{4}){3}|(3[4,7])\ d{2}-?\s?\d{6}-?\s?\d{5}$
Número teléfono ^[0-9]{2,3}-? ?[0-9]{6,7}$
Código postal ^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$
Certificado Identificación Fiscal ^(X(-|\.)?0?\d{7}(-|\.)?[A-Z]|[A-Z](-|\.)?\d{7}(-|\.)? [0-9A-Z]|\d{8}(-|\.)?[A-Z])$
Valida sólo números del 1 al 12 (ideal para meses) ^([0-1]?[0-2]|[0-9])$
Valida de 0.1 a 9.9 ^([0-9].[1-9])$
Valida desde 10.01 hasta 99.99 con 2 decimales máximo ^[0-9][0-9](.[0-9][0-9])$
Valida desde 0.01 hasta 99.99 con sólo 2 decimales máximo ^[0-9]?[0-9](.[0-9][0-9])$
Aquí les dejo el código:
private void txtcodigo_KeyUp(object sender, KeyEventArgs e)
        {
            if (es_numero(txtcodigo))
            {
                errorProvider1.SetError(txtcodigo, String.Empty);
                txtcodigo.BackColor = Color.Honeydew;
            }
            else
            {
                errorProvider1.SetError(txtcodigo, "Solo numeros");
                txtcodigo.BackColor = Color.MistyRose;
            }
        }

        private void txtemail_KeyUp(object sender, KeyEventArgs e)
        {
            if (es_email(txtemail))
            {
                errorProvider1.SetError(txtemail, String.Empty);
                txtemail.BackColor = Color.Honeydew;
            }
            else
            {
                errorProvider1.SetError(txtemail, "ejemplo@ejemplo.com");
                txtemail.BackColor = Color.MistyRose;
            }
        }


        private void txtnombre_KeyUp(object sender, KeyEventArgs e)
        {
            if (es_cadena(txtnombre))
            {
                errorProvider1.SetError(txtnombre, String.Empty);
                txtnombre.BackColor = Color.Honeydew;
            }
            else
            {
                errorProvider1.SetError(txtnombre, "Solo letras");
                txtnombre.BackColor = Color.MistyRose;
            }
        }

        private void txttelf_KeyUp(object sender, KeyEventArgs e)
        {
            if (es_telefono(txttelf))
            {
                errorProvider1.SetError(txttelf, String.Empty);
                txttelf.BackColor = Color.Honeydew;
            }
            else
            {
                errorProvider1.SetError(txttelf, "Formato: 999-9999");
                txttelf.BackColor = Color.MistyRose;
            }
        }

        private void txtweb_KeyUp(object sender, KeyEventArgs e)
        {
            if (es_url(txtweb))
            {
                errorProvider1.SetError(txtweb, String.Empty);
                txtweb.BackColor = Color.Honeydew;
            }
            else
            {
                errorProvider1.SetError(txtweb, "www.example.com");
                txtweb.BackColor = Color.MistyRose;
            }
        }

        private void txtsueldo_KeyUp(object sender, KeyEventArgs e)
        {
            if (es_decimal(txtsueldo))
            {
                errorProvider1.SetError(txtsueldo, String.Empty);
                txtsueldo.BackColor = Color.Honeydew;
            }
            else
            {
                errorProvider1.SetError(txtsueldo, "Formato: 00,00");
                txtsueldo.BackColor = Color.MistyRose;
            }
        }

        private static bool es_numero(Control mitextbox)
        {

            Regex regex = new Regex(@"^[0-9]+$");
            return regex.IsMatch(mitextbox.Text);

        }

        private static bool es_cadena(Control mitextbox)
        {

            Regex regex = new Regex(@"^[^ ][a-zA-Z ]+[^ ]$");
            return regex.IsMatch(mitextbox.Text);

        }

        private static bool es_telefono(Control mitextbox)
        {

            Regex regex = new Regex(@"^([0-9]{3})[-. ]?([0-9]{4})$");
            return regex.IsMatch(mitextbox.Text);
            
        }

        private static bool es_decimal(Control mitextbox)
        {

            Regex regex = new Regex(@"^[0-9]{1,9}([\.\,][0-9]{1,3})?$");
            return regex.IsMatch(mitextbox.Text);
            
        }

        private static bool es_url(Control mitextbox)
        {

            Regex regex = new Regex(@"^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)$");
            return regex.IsMatch(mitextbox.Text);
        }

        private static bool es_email(Control mitextbox)
        {
            
            Regex regex = new Regex(@"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$");

            // Resultado: 
            //       Valid: david.jones@proseware.com 
            //       Valid: d.j@server1.proseware.com 
            //       Valid: jones@ms1.proseware.com 
            //       Invalid: j.@server1.proseware.com 
            //       Invalid: j@proseware.com9 
            //       Valid: js#internal@proseware.com 
            //       Valid: j_9@[129.126.118.1] 
            //       Invalid: j..s@proseware.com 
            //       Invalid: js*@proseware.com 
            //       Invalid: js@proseware..com 
            //       Invalid: js@proseware.com9 
            //       Valid: j.s@server1.proseware.com

            return regex.IsMatch(mitextbox.Text);

        }
Este codigo va para el boton Nuevo
txtcodigo.Text = String.Empty;
            txtcodigo.BackColor = Color.White;
            errorProvider1.SetError(txtcodigo,String.Empty);

            txtnombre.Text = String.Empty;
            txtnombre.BackColor = Color.White;
            errorProvider1.SetError(txtnombre, String.Empty);

            txttelf.Text = String.Empty;
            txttelf.BackColor = Color.White;
            errorProvider1.SetError(txttelf, String.Empty);

            txtweb.Text = String.Empty;
            txtweb.BackColor = Color.White;
            errorProvider1.SetError(txtweb, String.Empty);

            txtemail.Text = String.Empty;
            txtemail.BackColor = Color.White;
            errorProvider1.SetError(txtemail, String.Empty);

            txtsueldo.Text = String.Empty;
            txtsueldo.BackColor = Color.White;
            errorProvider1.SetError(txtsueldo, String.Empty);
y este codigo va en el boton Grabar
if (es_numero(txtcodigo) == true && es_cadena(txtnombre) == true && es_telefono(txttelf) == true &&
                es_url(txtweb) == true && es_email(txtemail) == true && es_decimal(txtsueldo) == true)
            {
                MessageBox.Show("OK");
            }
            else
            {
                MessageBox.Show("Complete todos los campos.");
            }

Truco:Pasar Texto a Binario en Visual Basic.Net

Simple aplicación que convierte un texto a binario. Espero pronto cargar esta misma aplicación con la funcion de convertir binario a texto… Pero mientras, el fomulario quedaría así:
Su código es el siguiente y puedes descargar la aplicación desde AQUI
Private Sub btnaBinario_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnaBinario.Click
        Dim Val As String = Nothing
        Dim Resultado As New System.Text.StringBuilder

        For Each Character As Byte In System.Text.ASCIIEncoding.ASCII.GetBytes(TextBox1.Text)
            Resultado.Append(Convert.ToString(Character, 2).PadLeft(8, "0"))
            Resultado.Append("")
        Next

        Val = Resultado.ToString.Substring(0, Resultado.ToString.Length - 1)
        TextBox2.Text = Val

    End Sub

Deshabilitar boton Cerrar en winforms en Visual Basic.NET


Aqui les dejo este codigo que encontre navegando por Internet, este codigo lo ponen debajo de Public Class:
Dim _enabledcerrar As Boolean = False
     _
    Public Property enabledcerrar() As Boolean
        Get
            Return _enabledcerrar
        End Get
        Set(ByVal value As Boolean)
            If _enabledcerrar <> value Then
                _enabledcerrar = value
            End If
        End Set
    End Property
    Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
        Get
            Dim cp As CreateParams = MyBase.CreateParams
            If _enabledcerrar = False Then
                Const CS_NOCLOSE As Integer = &H200
                cp.ClassStyle = cp.ClassStyle Or CS_NOCLOSE
            End If
            Return cp
        End Get
    End Property

lunes, 3 de diciembre de 2012

domingo, 11 de noviembre de 2012

Agregar y Grabar en datagridview para guardar en SQL con Transacciones en Visual Basic .NET

Crearemos una forma con los objetos como aparece en la imagen, ademas agregaremos la libreria de sqlclient

Imports System.Data.SqlClient
para el ejemplo crearemos una base de datos con el nombre DBPRUEBA, que nos permita almacenar los datos.
CREATE DATABASE DBPRUEBA
USE DBPRUEBA
CREATE TABLE datos(  
id_datos INT PRIMARY KEY IDENTITY(1,1),  
nombre VARCHAR(50),  
deporte VARCHAR(50),  
fecha_inscripcion datetime    )
Ahora crearemos 4 columnas dentro del datagrid. que nos permitan agregar los datos ingresados.
Ahora para agregar los datos, hemos determinado un textbox para un nombre un combobox con unos deportes y por ultimo un datetimepicker para una fecha. tenemos un boton agregar que nos permitira, agregar un row al datagridview.
Este es el codigo para el boton agregar
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        If Me.TextBox1.Text <> String.Empty Then
            If Me.ComboBox1.Text <> String.Empty Then                  'agregamos la informacion a un row o fila del datagrid                  
                Me.DataGridView1.Rows.Add(Me.TextBox1.Text, Me.ComboBox1.Text, Me.DateTimePicker1.Value.ToShortDateString)                  'limpiamos los controles
                Me.TextBox1.Text = String.Empty
                Me.ComboBox1.SelectedItem = String.Empty
                Me.DateTimePicker1.Value = Today.Date
            Else
                MessageBox.Show("Ingrese un deporte", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        Else
            MessageBox.Show("Ingrese un nombre", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
una vez tenemos datos dentro de nuestro datagrid, si deseamos eliminar uno de nuestros rows o filas damos click en el boton eliminar, la cual quitara la fila del datagrid.
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
        'se puede hacer referencia al nombre de la columna para saber donde hicieron click o solo con el e.columnindex sabiendo la posicion de la columna          
        'yo lo manejo asi por que se daran cuenta que en algun caso las columnas pueden aumentar o disminuir           
        'y se complicaria la cosa por que si cambia el numero de columnas habria que corregir siembre el indice            
        'si hicieron clic en la columna eliminar          
        If DataGridView1.Columns(e.ColumnIndex).Name = "Eliminar" Then              'eliminar row
            DataGridView1.Rows.RemoveAt(e.RowIndex)
        End If
    End Sub
Ahora podremos guardar nuestra informacion al hacer click en el boton guardar, aqui se validara que existan datos o mejor filas en el datagrid, ahora recorreremos nuestro datagrid por medio de un For. tendremos una varia de tipo string (SqlString ) donde agregaremos la sentencia para guardar en la base de datos (INSERT INTO), ademas de un araylist para agregar las sentencias.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If DataGridView1.Rows.Count > 0 Then
            Dim SqlString As String = String.Empty ' variable a la que asignaremos la sentencia              
            Dim ListSqlStrings As New ArrayList  'arregla donde ingresaremos las sentencias              
            'recorremos el datagrid como ya sabemos siempre se toma desde cero
            For i As Integer = 0 To DataGridView1.Rows.Count - 1                  'creamos la sentencia el row siempre tendra el valor de i para ir pasando de row en row                  
                'el campo .cells(0) indica la columna que esta ese dato, tambien puede hacerlo con el nombre de la celda .cells("Nombre")
                SqlString = "INSERT INTO datos (nombre,deporte,fecha_inscripcion) VALUES ('" + DataGridView1.Rows(i).Cells(0).Value.ToString() + "','" + DataGridView1.Rows(i).Cells(1).Value.ToString() + "','" + DataGridView1.Rows(i).Cells(2).Value.ToString() + "')"
                'agregamos la sentencia a la lista                  
                ListSqlStrings.Add(SqlString)
            Next
            If EjecutarTransaccion(ListSqlStrings) Then
                MessageBox.Show("Info. guardada correctamente")
                Close()
            Else
                MessageBox.Show("La Info. no se guardo")
            End If
        Else
            MessageBox.Show("No hay informacion para guardar")
        End If
    End Sub
Ahora una vez hallamos recorrido el datagrid y tengamos nuestras sentencias, podremos ejecutar nuestra transaccion SQl para guardar en la base de datos. En este punto haciendo un parentesis igualmente podra ejecutar una a una las sentencias si lo desea por medio de un executenonquery, pero para mi lo mas optimo es una transaccion. Volviendo al evento guardar la funcion Public Function EjecutarTransaccion(ByVal ListaSentencias As ArrayList) As Boolean recibira el arraylist y retornara un valor booleano para identificar si se realizo la transaccion. para ejecutar nuestra transaccion necesitamos una conexion como la siguiente.
Public Connection1 As New SqlConnection("Data Source=XSaint;Initial Catalog=DBPRUEBA;Integrated Security=SSPI")
Ahora la funcion ejecutartransaccion se ejecutara, si es correcta la transaccion retornara true de ser incorrecta podremos ver un mensaje y retornara un false
Public Function EjecutarTransaccion(ByVal ListaSentencias As ArrayList) As Boolean
        Dim band As Boolean = False
        If AbrirConexion() Then
            Dim command As SqlCommand = Connection1.CreateCommand()
            Dim transaction As SqlTransaction
            Dim strSentencia As Object
            Dim sentencia As String = ""
            transaction = Connection1.BeginTransaction()
            command.Connection = Connection1
            command.Transaction = transaction
            Try
                For Each strSentencia In ListaSentencias
                    sentencia = strSentencia.ToString()
                    command.CommandText = sentencia.ToString()
                    command.ExecuteNonQuery()
                Next
                transaction.Commit()
                band = True
            Catch ex As Exception
                MessageBox.Show(ex.Message)
                Try
                    transaction.Rollback()
                Catch ex2 As Exception
                    MessageBox.Show(ex2.Message)
                End Try
            Finally
                CerrarConexion()
            End Try
        End If
        Return band
    End Function
Si la transaccion es satisfactoria veremos un mensaje de satisfaccion. la clase transaccion utiliza dos funciones dicionales de abrir y cerrar conexion que nos permite establecer si la conexion es correcta o no.
Public Function AbrirConexion() As Boolean
        Dim band As Boolean = False
        Connection1.Open()
        Try

            band = True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        Return band
    End Function
    Public Function CerrarConexion() As Boolean
        Dim band As Boolean = False
        Connection1.Close()
        Try
            band = True
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
        Return band
    End Function
ahora podremos ver nuestra informacion, en la base de datos.

sábado, 27 de octubre de 2012

Email phrase bank: Useful expressions and phrases

Commercial: Request for information (customer)
Saying how you got the contact
We met last Thursday on your stand at the Munich Trade Fair.
I am emailing you off your website, which I found through Google.
Giving reason for writing
We are a manufacturer / supplier / provider of ... We are interested in ...
We are a Turkish company exporting to the EU, and we need ...
General requests
We would be grateful for some information about ...
Please send us information about your product range and prices.
Specific requests
In particular, we would like to know ...
Please send full details of your prices, discounts, terms of payment and delivery times.
Could you also say whether there is any minimum order.
Close
An early reply would be greatly appreciated.
I look forward to an early reply, and am sure that there is a market for your products here in Hungary.

Giving information (supplier)
Thanks
Thank you for your email of 4 June inquiring about ...
Giving factual information
We can quote a price of ... CIF / FOB Istanbul.
We can delivery by ... (date) / within ... (period of time)
The goods will be shipped 3 days from receipt of a firm order.
We can offer a discount of ... on orders over ... .
We require payment by bank transfer / letter of credit.
Our normal procedure is to ...
Our normal terms for first-time customers are ...
We can supply the items you require directly from stock.
Saying what you are attaching
I am attaching a document that gives full details of ...
I am attaching our current catalogue and price list as a pdf file.
Highlighting one or two key points
You will see that ...
You will note that our line of .... is on special offer.

Answering specific questions
You will also note that ... Our experience in this field includes ...
We dispatch the goods within 24 hours of a firm order, and for first-time customers our minimum order is $ 1,000.
I am afraid that model is no longer available. However, ...
Close
We feel sure that ... May I suggest that I call you at your convenience to discuss the matter further?
If you need any further information, please do not hesitate to contact me. My direct line is...

Making an order (customer)
Open
Thank you for your recent email, and we accept your quotation. Our completed order form is attached, and we give full bank details below.
Close
Please acknowledge receipt of this order.

Confirming an order (supplier)
Open
Your order has been received.
We can confirm that your goods have been shipped.
You can track shipping details on our website.
Due to exceptional demand these items are temporarily out of stock. We hope to be able to ship your order within ... days and will keep you fully informed. We apologize for any inconvenience this may cause.
Close
We are confident that the goods will meet your expectations. Should there be any questions, please do not hesitate to contact me, either by email or phone

Asking for payment (supplier)
First reminder – open
We are writing concerning a payment of $12,600 for invoice number KJ678 which is now overdue. A copy of the invoice is attached.
According to our records, the sum of $4,500 is still outstanding on your account
First reminder – action
Please send a bank transfer to settle the account, or an explanation of why the balance is still outstanding. If you have already dealt with this matter, please disregard this email.
We could appreciate your cooperation in resolving this matter as soon as possible.
Second/third reminder – open
On (date) I wrote to you regarding your company’s unpaid account , amounting to $4,500. May we please remind you that this amount is still outstanding.
I wish to draw your attention to my previous emails of (dates) about the overdue payment on your account. We are very concerned that the matter has not yet receive your attention.
Second/third reminder – action
We need a bank transfer in full settlement without further delay.
Clearly, this situation cannot be allowed to continue, and we must ask you to take immediate action to settle your account.
If you have any queries on this mater, please do not hesitate to contact me. Thank you for your cooperation.
Final demand – open
Following my emails of (dates) I must inform you that we have still not received payment for the outstanding sum of $4,500.
I wrote to you on (dates) regarding the balance of $12,600 on your account. I attach copies of both emails. This sum is now two months overdue. We are very concerned that the matter has not yet received your attention.
Final demand – action
Unless we receive payment within seven days, we shall have no alternative but to take legal action to recover the money.
In the meantime, your existing credit facilities have been suspended.

Complaints and Apologies
Complaining (customer)
Open
I am writing ...
in connection with my order FS690 which arrived this morning.
to complain about the quality of a product I bought from your website.
to complain about the poor service we received from your company.
to draw your attention to the negative attitude of some people in your customer services section
Complaint
Our order dated 16 September clearly stated that we wanted 1,000 items, however you ...
The goods were faulty / damaged / in poor condition.
There seems to be an error in the invoice /a misunderstanding.
The equipment I ordered has still not been delivered, despite my phone call you last week to say that it is needed urgently.
The product I received was well below the standard expected.
To make matters worse, when I called your company staff ...
Request for action
Please replace the faulty goods as soon as possible.
We must insist on an immediate replacement / full refund.
Unless I receive the goods by the end of this week, I will have no choice but to cancel my order.
Close
I hope that you will deal with this matter promptly as it is causing me considerable inconvenience.

Apologizing (supplier)
Open
I am writing in relation to your recent complaint.
Apologizing I was very concerned to learn about ... Please accept my sincere apologies.
I would like to apologize for the inconvenience you have suffered.
Denying responsibility
We appreciate that this has caused you considerable inconvenience, but we cannot accept any responsibility in this matter.
Promising action
Can you leave it with me? I’ll look into the matter and get back to you tomorrow.
I have looked into the matter and ...
I have spoken to the staff involved, and ...
We will send replacement items / give you a refund immediately.
I can assure you that this will not happen again.
We’re having a temporary problem with ... . We’re doing everything we can to sort it out.
Compensation
To compensate for the inconvenience, we would like to offer you ...
Close
Thank you for bringing this matter to my attention. Please accept my assurance that it will not happen again.
Once again, I hope you will accept my apologies for the inconvenience caused.
I very much hope you will continue to use our services in the future.
If you have any further queries, please do not hesitate to contact me on my direct line...

Personal
Friendly
You heard something, but you are not sure
It seems that ... Apparently, ...
Something is true, but surprising
Actually, ... In fact, ...
Something is obvious or already known
Obviously, ... Of course ...
Good/ bad fortune
Unfortunately, ... Luckily, ...
Saying what you really think
To be honest, ... Frankly, ...
Going back to a topic
Well, ... So, ... Anyway, ...
Changing the topic
Anyway, ... So, ... By the way, ...
Summarizing with the most important point
Anyway, ... Basically, ...
Asking for advice
Formal/Neutral
Informal
OpenI’d like your advice about a problem I have
I’ve got a bit of a problem.
Asking for adviceI was wondering if you had any ideas about ...?
What would you advise me to do?
Do you have any ideas about ...?
What should I do?
ClosePlease write back when you have the time and let me know what you think.Please email me when you get the chance.

Giving
Formal/NeutralInformal
OpenI was sorry to hear about your current difficulties.I’m sorry you’re having such a hard time at the moment.
Giving adviceI think it might be a good idea to ...
Have you thought of ... (+ing)?
I think you should ...
What about ... (+ing)?
ResultThis would mean that ...That way, ...
OptionsI think this option would be preferable to ... (+ing)I think it’s better than ... (+ing)
CloseI hope I have been of some help.I hope I’ve helped a bit.

Suggestions
Making a suggestion
I think we should / I suggest that we / Let’s go to ...
Shall we / Perhaps we could/Why don’t we go to ...?
I suggest... /How about going to ...?
Accepting
It’s a great idea!
I think your idea would work really well.
It might be worth trying.
Rejecting
I’m not so sure about your idea.
It sounds like a good idea, but I don’t think it would work in practice.
It sounds like a good idea, but I can see one or two problems.
Special situations
Thanks
Just a quick note to say many thanks for ...
I really appreciate everything that you have done.
Good luck
Good luck with ...I would like to take this opportunity to wish you every success in the future.
Congratulations
Many congratulations on your promotion / new job.
I was delighted to hear the news about ...
Well done!
Best wishes
Please give my best wishes/regards to ...
Bad news
I was so sorry to hear about ...
I was really sorry to hear you’re not well ...Hope you feel better soon.
If there’s anything I can do to help, let me know.

Job Application
Greeting
Dear Sir/Madam
Reason for writing
With reference to your advertisement on the ... website, I am interested in applying for the post of...
Your background and experience
I am 26 years old and am currently studying for a degree in ... at ... University.
For the last two months I have been working as a ... at ... .
The job itself
I am interested in this job because ...
I feel that I would be well-suited for this job/have a lot of experience in ...
Referring to your CV
I have attached my CV as a Word document. You will notice that I ... as well as ... . You will also notice that ... .
Final comments
I would be grateful if you would consider my application.
You will see from my CV that two people can be contacted as references, one is ... and the other is from ... .
I am available for interview in .../ by phone any weekday afternoon, and you can email me or telephone me on the number below.
Close
I look forward to hearing from you soon.
Yours faithfully
Reports
Report structure

Introduction / Background
As requested at the Board meeting of 18 April, here is my report.
The report will discus / consider / describe / analyze / review ...
The report is based on ...
I have divided the report into three sections.
Findings
The findings / figures / results / investigations show that ...
It appears that ... . This has led to a situation where ...
The graph/table shows that ...
Signposts
As can be seen in table 1 / section 2 / figure 3, ...
As mentioned above, ... / ..., see below.
...and I will discuss this in more detail below /in section 3.2.
Conclusion / Recommendations
I (would like to) suggest /recommend that ...
My specific recommendations are as follows.
Closing comments
Please have a look at the report and let me have your comments.
Please feel free to contact me if you have any questions.
Linking words
Sequence
Firstly / secondly / finally
Talking generally
In general / usually / on the whole
Contrast
However / nevertheless / on the other hand
Adding another point
In addition / moreover / on another point
Examples
For example / for instance / e.g.
Alternatives
Either ... or ... / alternatively / instead of ...
Real (surprising) situation
In fact, / actually, / as a matter of fact
Something is obvious
Clearly / obviously / of course
Most important point
Especially / above all / in particular
Rephrasing
In other words / that is to say / i.e.
Result/consequence
As a result / therefore / for this reason
New topic
In relation to / regarding / with reference to
Careful, balanced style
Giving both sides of an argument
In general ..., however ...
On the whole ..., but ...
Making a statement less general
Many / some ...
Usually / typically / often ...
Making a statement less certain
It is possible / probable that ...
It seems / appears that ...
... tends to be...
Making a comparison less strong
Substantially / considerably / much (+ comparative adjective)
Significantly / relatively (+ comparative adjective)
Marginally / slightly (+ comparative adjective)
Concluding
On balance, ...
Taking all the above points into consideration, ...

sábado, 6 de octubre de 2012

Llenar combobox con campos concatenados de una base de datos en C#

En este ejemplo utilizare la Base de Datos Northwind y concatenare los campos Nombre de Contacto y Compañia en un combobox.
El codigo es el siguiente:

public void llenarProfesor()
        {
            string enlace="Data Source=XSaint;Database=Northwind;Integrated Security=SSPI";
            string conect;            
            //enlace con la base de datos
            SqlConnection conexion = new SqlConnection();
            conexion.ConnectionString = enlace;
            conect = conexion.ConnectionString;
            //se declara el DataSet
            DataSet ds3 = new DataSet();
            //se indica la consulta e sql donde se elige el ID_Profesor
            //y se concatenan los campos Nombre y Apellido_P
            //en una variable llamada Name_Full
            SqlDataAdapter da3 = new SqlDataAdapter("Select CustomerID,(ContactName + \' \' + CompanyName) as Name_Full FROM Customers", conect);
            //se especifica la tabla
            da3.Fill(ds3, "Customers");
            comboBox1.DataSource = ds3.Tables[0].DefaultView;
            //el valor real será el ID_Profesor
            comboBox1.ValueMember = "CustomerID";
            //lo que mostrará sera la variable Name_Full la cual tiene concatenados los campos Nombre y Apellido_P
            comboBox1.DisplayMember = "Name_Full";
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            llenarProfesor();
        }

Como poner letra capital de todas las palabras de un string en C#

A menudo necesitamos capitalizar la primera letra de algunas palabras o algun texto(por ejemplo cuando queremos mostrar nombres completos de personas o ciudades, nombres, etcetera).
Como la clase string no tiene un metodo para hacer esto nosotros podemos pensar que no hay una solucion built-in en C# para este problema.
Bueno en realidad hay 2 formas de hacer esto:
Para este proyecto agregaremos 2 textbox y un boton:
Solucion 1
public static string Capitalize(string value)
        {
            return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox2.Text = Capitalize(textBox1.Text);            
        }

public static string CapitalizeWords(string value)
        {
            if (value == null)
                throw new ArgumentNullException("value");
            if (value.Length == 0)
                return value;

            StringBuilder result = new StringBuilder(value);
            result[0] = char.ToUpper(result[0]);
            for (int i = 1; i < result.Length; ++i)
            {
                if (char.IsWhiteSpace(result[i - 1]))
                    result[i] = char.ToUpper(result[i]);
            }
            return result.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox2.Text = CapitalizeWords(textBox1.Text);            
        }

Usando Regex matches para comprobar si un String es alphanumerico en C#

El metodo regex.match de C# es tipicamente usado para validar un string o para asegurar que un string esta conformado de un patron particular sin necesidad de manipularlo. Abajo utilizo un metodo de extension de strings que usa regex matches en C# para comprobar si el string es alphanumerico. Retornara verdadero si el string dado contiene solo numeros y letras del alfabeto.
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static class CheckString
        {
            public static bool IsAlphanumeric(string source)
            {
                Regex pattern = new Regex("[^0-9a-zA-Z]");
                return !pattern.IsMatch(source);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string testString = textBox1.Text;

            if (CheckString.IsAlphanumeric(testString))
                textBox2.Text="Yes string is Alphanumeric!";
            else
                textBox2.Text="No string is not Alphanumeric!";

            
        }

viernes, 5 de octubre de 2012

AutoCompletar TextBox desde base de datos con Northwind y VB.NET

Hay que tener en cuenta que para utilizar esta opción, debes asignar las siguientes propiedades:
AutoCompleteMode: que sirve para indicar cómo queremos que se muestren los datos que encuentra mientras se escribe en el control.
AutoCompleteSource: que sirve para indicarle de dónde se obtendrán los datos que se usarán mientras se escribe.
En este ejemplo se utiliza AutoCompleteSource asignado a CustomSource debido a que la fuente de datos la obtenemos desde una ruta personalizada.
En el evento Load del formulario, se llama a la función AutoCompletar como se muestra debajo, asignándole el control TextBox.
Imports System.Data.SqlClient
Public Class Form1

    Dim myCommand As SqlCommand
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AutoCompletar(Me.TextBox1)
        Me.ActiveControl = TextBox1
    End Sub
Esta es la función AutoCompletar que se deberá utilizar asignándole el control TextBox.
Public Function AutoCompletar(ByVal Control As TextBox) As AutoCompleteStringCollection
        Dim Coleccion As New AutoCompleteStringCollection
        Dim Comando, Coneccion As String
        'Dim myConnection As SqlConnection
        Comando = "select LastName from Employees"
        'Creamos una nueva cadena de coneccion 
        Coneccion = "Data Source=XSaint;Initial Catalog=Northwind;Integrated Security=SSPI"
        'myConnection = New SqlConnection(Coneccion)
        Using myConnection As New SqlConnection(Coneccion)
            Dim Ejecutar As New SqlClient.SqlCommand(Comando, myConnection)
            'Abrimos la coneccion
            myConnection.Open()
            Dim Lector As SqlDataReader = Ejecutar.ExecuteReader()
            ' Realizamos un Loop mientras se est‚ leyendo.
            While Lector.Read()
                Coleccion.AddRange(New String() {Lector(0)})
            End While
            'Cerramos el SqlReader
            Lector.Close()
            'Cerramos la coneccion
            myConnection.Close()
        End Using
        'Ajustamos el control TextBox o ComboBox para recibir los datos de la siguiente manera.
        With Control
            .AutoCompleteMode = AutoCompleteMode.Suggest
            .AutoCompleteSource = AutoCompleteSource.CustomSource
            .AutoCompleteCustomSource = Coleccion
        End With
        'Devolvemos los datos recuperados de la base de datos
        Return Coleccion
    End Function
End Class

Cambiar color de filas en un dataGridView con CheckBox en VB.NET

Ejemplo para alternar mediante la propiedad backcolor del objeto alternatingrowsdefaultcellstyle , el color de filas en un control datagridview
CONTROLES
  1. Un DataGridview ( DataGridView1 )
  2. un CheckBox
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        With ListBox1.Items
            .Add("1")
            .Add("2")
            .Add("3")
            .Add("1")
            .Add("2")
            .Add("3")
            ListBox1.SelectedIndex = 0
        End With
        Button1.Text = "Eliminar duplicados "
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        MsgBox(Eliminar(ListBox1), MsgBoxStyle.Information, "Elementos duplicados en el List ")
    End Sub
    Function Eliminar(ByVal LB As ListBox) As Int32
        Dim i As Int32
        Dim j As Int32
        Dim n As Int32           ' Recorre los items ( compara empezando desde el primero , de abajo hacia arriba)         
        For i = 0 To LB.Items.Count - 2
            For j = LB.Items.Count - 1 To i + 1 Step -1                 ' ... si es el mismo                 
                If LB.Items(i).ToString = LB.Items(j).ToString Then
                    LB.Items.RemoveAt(j) ' elimina el elemento indicando el índice                     
                    n += 1 'lleva la cuenta de los duplicados                 
                End If
            Next
        Next
        Return n ' retorna los eliminados     End Function End Class 
    End Function

domingo, 30 de septiembre de 2012

Truco:Abrir una dirección URL o un Programa con C++

Para abrir enlaces a través de un programa en c++ , se debe utiliza la función ShellExecute de la API de Windows.
Una sencilla aplicación que pregunte al usuario si desea visitar mi nuevo blog sería:
#include <windows.h>
#include <iostream>

using namespace std;
int main()
{
int val = MessageBox(NULL,"Quieres Visitar mi nuevo Blog?","Ventantita",MB_YESNO);
cout<<"Valor Retornado: "<<val;

if(val==6)
 {
        ShellExecute(NULL, "open", "http://www.elnaufragodelared.com/",NULL, NULL, SW_SHOWNORMAL);

 }
return 0;
}
De igual manera si deseo Ejecutar un programa externo como el Emule sería así:
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
        ShellExecute(NULL, "open", "C:/Archivos de programa/eMule/emule.exe",NULL, NULL, SW_SHOWNORMAL);
        return 0;
}

NOTA:
El ejemplo fue compilado utilizando el IDE , Codeblocks.