Regresar   Foros del Web > Programación para sitios web > ASP

El registro es Gratis en Foros del Web
Respuesta
 
Herramientas Buscar en Tema Desplegado
Antiguo 04/04/05, 09:43:13   #61 (permalink)
elkronos ha deshabilitado el Karma
 
Registrado: sep 2004
Mensajes: 66
elkronos is offline  
craear tabla, buscar, insertar, borrar, con Recordsets

<%
'Base de datos en oracle con dsn
Dim MM_orafin_STRING
MM_orafin_STRING = "dsn=mibasededatos;uid=miuid;pwd=mipass;"
%>
<%
'No se olvide crear la conexion con el string
'Ojo que pueden existir mas de una columnas por lo tanto columnasydatos es un array que contiene
'el nombre de la columna y el dato ejm
' Si una tabla en la base de datos tiene 2 columnas FECHA y DATO
'el array seria definico asi Dim columnasydatos(1)(1)
'donde la primera fila del array seria para la FECHA y su valor que sequiere ingresar
'columnasydatos(0,0) = "FECHA" columnasydatos(0,1) = '12/12/2001'
'y la segunda fila del array seria para el DATO y su valor que se quiere ingresar
'columnasydatos(1,0) "DATO" = columnasydatos(1,1) = 50
'Se pueden crear array mas grandes
FUNCTION InsertarDatosTabla(nombretabla , columnasydatos )
Dim RecInsertar
Dim columna
Set RecInsertar = Server.CreateObject("ADODB.Recordset")
RecInsertar.ActiveConnection = MM_orafin_STRING
RecInsertar.Source = "SELECT * FROM " & nombretabla
RecInsertar.CursorType = 0
RecInsertar.CursorLocation = 2
RecInsertar.LockType = 3
RecInsertar.Open()
RecInsertar.AddNew
Dim conttemp
for contfil = 0 to Ubound(columnasydatos,1)
conttemp = 0
for contcol = 0 to Ubound(columnasydatos,2)
conttemp = conttemp + 1
columna = columnasydatos(contfil,contcol)
dato = columnasydatos(contfil,conttemp)
contcol = Ubound(columnasydatos,2)
RecInsertar(columna) = dato
next
next
RecInsertar.Update
RecInsertar.Close()
Set RecInsertar = Nothing
END FUNCTION
FUNCTION BorrarDatosTabla(tabla , columna , datos)
Dim RecBorrar
Set RecBorrar = Server.CreateObject("ADODB.Recordset")
RecBorrar.ActiveConnection = MM_orafin_STRING
RecBorrar.Source = "SELECT * FROM " & tabla & " WHERE " & columna & "= '" & datos & "' " & " ORDER BY " & columna & " ASC"
RecBorrar.CursorType = 0
RecBorrar.CursorLocation = 2
RecBorrar.LockType = 3
RecBorrar.Open()
'Nos movemos a la primera posición
RecBorrar.MoveFirst
'Borramos
RecBorrar.Delete
'Guardamos los cambios
RecBorrar.Update
RecBorrar.Close()
Set RecBorrar = Nothing
END FUNCTION

FUNCTION BuscarDatosTabla(tabla , columna , datos)
Dim RecBuscar
Dim datobuscado
Set RecBuscar = Server.CreateObject("ADODB.Recordset")
RecBuscar.ActiveConnection = MM_orafin_STRING
RecBuscar.Source = "SELECT * FROM " & tabla & " WHERE " & columna & "= '" & datos & "' " & " ORDER BY " & columna & " ASC"
RecBuscar.CursorType = 0
RecBuscar.CursorLocation = 2
RecBuscar.LockType = 3
RecBuscar.Open()
IF RecBuscar.EOF THEN
'"NO SE ENCONTRO NADA" TAMBIEN SE PODIA HABER HECHO ASI Y SE QUITABA EL "ELSE" :
'NOT RecBuscar.EOF
ELSE
'Aqui se guarda el dato buscado
datobuscado = RecBuscar.Fields.Item(columna).Value
END IF
RecBuscar.Close()
Set RecBuscar = Nothing
BuscarDatosTabla = datobuscado
END FUNCTION

FUNCTION CrearTabla(Nombretabla)

Dim RecCreaTabla
'Se crea un recordset
Set RecCreaTabla = Server.CreateObject("ADODB.Recordset")
'Se asocia el recordset a la base de datos con el string
RecCreaTabla.ActiveConnection = MM_orafin_STRING
'Se crea una consulta en SQL ejem SELECT, CREATE, etc
RecCreaTabla.Source = "CREATE TABLE " & Nombretabla & " (FECHA DATE NULL, CANTACCIONES NUMBER NULL, VOLUMEN NUMBER NULL, PRECIOMAX NUMBER NULL, PRECIOMIN NUMBER NULL, PRECIOCIERRE NUMBER NULL)"
'Dejar esto por defecto 0
RecCreaTabla.CursorType = 0
'Cursor: 2 Server, 1 Cliente dejar por defecto 2
RecCreaTabla.CursorLocation = 2
'Opcion 3 Optimistic que no es solo lectura
RecCreaTabla.LockType = 3
'Se abre o se realiza la consulta
RecCreaTabla.Open()
END FUNCTION


%>



espero que les sirva de algo una pequeña contribución porque sus funciones me sirvieron mucho gracias
  Responder Con Cita
Antiguo 06/04/05, 11:00:36   #62 (permalink)
pablinweb tiene un saldo positivo de karma
 
Registrado: jul 2003
Ubicación: México
Mensajes: 263
pablinweb is offline  
Importe a letras

Código:
<%
Function ImporteEnLetras(pImporte, pSepDecimal, pCharPorLinea, pDesMoneda, pDesCentavos, pDecimalesEnNumeros, pLeyenda)

Dim tmpEntero(9)
Dim tmpDecimal(2)
Dim tmpImporteEnLetras
Dim tmpLetrasFinal
Dim tmpEsDecimal
Dim tmpImporte
Dim tmpEnteros
Dim tmpDecimales
Dim tmpChar
Dim i
Dim tmpLargoImporte
Dim tmpLargoEnteros
Dim tmpPosicion
Dim tmpDigito
Dim tmpCantChar
Dim tmpPalabra

ImporteEnLetras = ""

tmpImporteEnLetras = ""
tmpLetrasFinal = ""
tmpImporte = Trim(pImporte)
tmpEsDecimal = False
tmpEnteros = ""
tmpDecimales = ""

For i = 1 To Len(tmpImporte)
  tmpChar = Mid(tmpImporte, i, 1)
  If tmpChar <> pSepDecimal And (Asc(tmpChar) < 48 Or Asc(tmpChar) > 57) Then
    Exit Function
  End If
Next

For i = 1 To 9
  tmpEntero(i) = "0"
Next

tmpLargoImporte = Len(tmpImporte)

For tmpPosicion = 1 To tmpLargoImporte
  tmpChar = Mid(tmpImporte, tmpPosicion, 1)
  If tmpChar = pSepDecimal Then
    tmpEsDecimal = True
  Else
    If tmpEsDecimal = True Then
      tmpDecimales = tmpDecimales + tmpChar
    Else
      tmpEnteros = tmpEnteros + tmpChar
    End If
  End If
Next

tmpDecimales = Left(tmpDecimales + "00", 2)
tmpLargoEnteros = Len(tmpEnteros)

For tmpDigito = tmpLargoEnteros To 1 Step -1
  tmpEntero(tmpDigito) = Mid(tmpEnteros, (tmpLargoEnteros - tmpDigito + 1), 1)
Next

If (tmpEntero(9) <> "0" Or tmpEntero(8) <> "0" Or tmpEntero(7) <> "0") Then
  tmpImporteEnLetras = tmpImporteEnLetras + ConvierteLetras(tmpEntero(9), tmpEntero(8), tmpEntero(7))
  If (tmpEntero(9) = "0" And tmpEntero(8) = "0" And tmpEntero(7) = "1") Then
    tmpImporteEnLetras = tmpImporteEnLetras + "millon "
  Else
    tmpImporteEnLetras = tmpImporteEnLetras + "millones "
  End If
End If

If (tmpEntero(6) <> "0" Or tmpEntero(5) <> "0" Or tmpEntero(4) <> "0") Then
  If (tmpEntero(6) = "0" And tmpEntero(5) = "0" And tmpEntero(4) = "1") Then
  Else
    tmpImporteEnLetras = tmpImporteEnLetras + ConvierteLetras(tmpEntero(6), tmpEntero(5), tmpEntero(4))
  End If
  tmpImporteEnLetras = tmpImporteEnLetras + "mil "
End If

tmpImporteEnLetras = tmpImporteEnLetras + ConvierteLetras(tmpEntero(3), tmpEntero(2), tmpEntero(1))
If tmpEntero(1) = "1" Then tmpImporteEnLetras = Left(tmpImporteEnLetras, Len(tmpImporteEnLetras) - 1) + "o "

If tmpImporteEnLetras = "" Then tmpImporteEnLetras = "cero "
If pDecimalesEnNumeros = True Then
   tmpImporteEnLetras = tmpImporteEnLetras + pDesMoneda + " con " + tmpDecimales + "/100 " + pDesCentavos
Else
   tmpDecimal(1) = Mid(tmpDecimales, 1, 1)
   tmpDecimal(2) = Mid(tmpDecimales, 2, 1)
   tmpImporteEnLetras = tmpImporteEnLetras + pDesMoneda + " con " + ConvierteLetras("0", tmpDecimal(1), tmpDecimal(2)) + pDesCentavos
End If

tmpImporteEnLetras = RTrim(tmpImporteEnLetras)

If Len(tmpImporteEnLetras) <= pCharPorLinea Then
  tmpLetrasFinal = tmpImporteEnLetras
Else
  tmpCantChar = 0
  tmpPalabra = ""
  For i = 1 To Len(tmpImporteEnLetras)
    tmpCantChar = tmpCantChar + 1
    tmpChar = Mid(tmpImporteEnLetras, i, 1)
    If tmpChar = " " Then
      tmpLetrasFinal = tmpLetrasFinal + tmpPalabra
      tmpPalabra = ""
      If tmpCantChar < pCharPorLinea Then tmpLetrasFinal = tmpLetrasFinal + tmpChar
    Else
      tmpPalabra = tmpPalabra + tmpChar
    End If
    If tmpCantChar > pCharPorLinea Then
      tmpCantChar = Len(tmpPalabra)
      
    If gCHARLINE Then
      tmpLetrasFinal = tmpLetrasFinal & vbCrLf
    Else
      tmpLetrasFinal = tmpLetrasFinal + Chr(10)
    End If

    End If
  Next
  tmpLetrasFinal = tmpLetrasFinal + tmpPalabra
End If

If pLeyenda = "" Then
    ImporteEnLetras = UCase(tmpLetrasFinal)
Else
    ImporteEnLetras = UCase(tmpLetrasFinal & " " & pLeyenda)
End If

End Function
Function ConvierteLetras(pDigito3, pDigito2, pDigito1)

Dim tmpLetras

ConvierteLetras = ""
tmpLetras = ""

Select Case pDigito3
  Case "0"
  Case "1"
    If pDigito2 = "0" And pDigito1 = "0" Then
      tmpLetras = tmpLetras + "cien "
    Else
      tmpLetras = tmpLetras + "ciento "
    End If
  Case "2"
    tmpLetras = tmpLetras + "doscientos "
  Case "3"
    tmpLetras = tmpLetras + "trescientos "
  Case "4"
    tmpLetras = tmpLetras + "cuatrocientos "
  Case "5"
    tmpLetras = tmpLetras + "quinientos "
  Case "6"
    tmpLetras = tmpLetras + "seiscientos "
  Case "7"
    tmpLetras = tmpLetras + "setecientos "
  Case "8"
    tmpLetras = tmpLetras + "ochocientos "
  Case "9"
    tmpLetras = tmpLetras + "novecientos "
  Case Else
    Exit Function
End Select

Select Case pDigito2
  Case "0"
  Case "1"
    Select Case pDigito1
      Case "0"
        tmpLetras = tmpLetras + "diez "
      Case "1"
        tmpLetras = tmpLetras + "once "
      Case "2"
        tmpLetras = tmpLetras + "doce "
      Case "3"
        tmpLetras = tmpLetras + "trece "
      Case "4"
        tmpLetras = tmpLetras + "catorce "
      Case "5"
        tmpLetras = tmpLetras + "quince "
      Case "6"
        tmpLetras = tmpLetras + "dieciseis "
      Case "7"
        tmpLetras = tmpLetras + "diecisiete "
      Case "8"
        tmpLetras = tmpLetras + "dieciocho "
      Case "9"
        tmpLetras = tmpLetras + "diecinueve "
      Case Else
        Exit Function
    End Select
  Case "2"
    If pDigito1 = "0" Then
      tmpLetras = tmpLetras + "veinte "
    Else
      tmpLetras = tmpLetras + "veinti"
    End If
  Case "3"
    tmpLetras = tmpLetras + "treinta "
  Case "4"
    tmpLetras = tmpLetras + "cuarenta "
  Case "5"
    tmpLetras = tmpLetras + "cincuenta "
  Case "6"
    tmpLetras = tmpLetras + "sesenta "
  Case "7"
    tmpLetras = tmpLetras + "setenta "
  Case "8"
    tmpLetras = tmpLetras + "ochenta "
  Case "9"
    tmpLetras = tmpLetras + "noventa "
  Case Else
    Exit Function
End Select
If cdbl(pDigito2) >= 3 And pDigito1 <> "0" Then tmpLetras = tmpLetras + "y "

If pDigito2 <> "1" Then
  Select Case pDigito1
    Case "0"
    Case "1"
      tmpLetras = tmpLetras + "un "
    Case "2"
      tmpLetras = tmpLetras + "dos "
    Case "3"
      tmpLetras = tmpLetras + "tres "
    Case "4"
      tmpLetras = tmpLetras + "cuatro "
    Case "5"
      tmpLetras = tmpLetras + "cinco "
    Case "6"
      tmpLetras = tmpLetras + "seis "
    Case "7"
      tmpLetras = tmpLetras + "siete "
    Case "8"
      tmpLetras = tmpLetras + "ocho "
    Case "9"
      tmpLetras = tmpLetras + "nueve "
    Case Else
      Exit Function
  End Select
End If

ConvierteLetras = tmpLetras

End Function
%>
para llamarla:

tmp = 1234.45
tmp = ImporteEnLetras(tmp, ".", 100, "PESOS", "CENTAVOS", false, "")
response.Write(tmp)


Definición:

pImporte: Monto
pSepDecimal: Separeción de decimales ("," o ".")
pCharPorLinea: Caracteres por linea para que no se salga del ancho requerido
pDesMoneda: Descripción de la moneda ("PESOS", "DOLARES ESTADOUNIDENSES", "EUROS", etc)
pDesCentavos: Descripción de los centavos ("CENTAVOS", "CENTS", etc)
pDecimalesEnNumeros: true = pone los decimales en números ej:12/100. false los pone en letras
pLeyenda: leyenda final que se le puede agregar o no al texto por ejemplo en Mexico se usa "M.N." de moneda nacional

Espero les sea útil...
Si alguien se copa podrian adaptarla para que se pueda elegir el idioma porque hay casos en los que si son dolares te lo piden en ingles.
__________________
Saludos

Última edición por pablinweb fecha: 06/04/05 a las 11:03:36.
  Responder Con Cita
Antiguo 25/04/05, 12:10:58   #63 (permalink)
Saruman tiene un saldo positivo de karma
 
Registrado: may 2003
Ubicación: Panamá
Mensajes: 1.125
Contactar con Saruman a través de MSN Contactar con Saruman a través de Yahoo
Saruman is offline  
Calcular la Edad de algo

Hola... esta función calcula la edad de una persona o algo....
Utilizacion:
fecha_nacimiento = "09/10/1981"
edad = Age(fecha_nacimiento)

response.write(edad & " años.")

Resultado: 23 años.


Código:
Function Age(strBirthDate)
	If IsNull(strBirthDate) then Age = 0: Exit Function
	
	varAge = DateDiff("yyyy", strBirthDate, Now)
	If Date < DateSerial(Year(Now), Month(strBirthDate), Day(strBirthDate)) Then
		varAge = varAge - 1
	End If
	Age = CInt(varAge)
End Function
__________________
Saruman

One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them.
  Responder Con Cita
Antiguo 25/04/05, 12:15:15   #64 (permalink)
Saruman tiene un saldo positivo de karma
 
Registrado: may 2003
Ubicación: Panamá
Mensajes: 1.125
Contactar con Saruman a través de MSN Contactar con Saruman a través de Yahoo
Saruman is offline  
Signo Zodiacal

Saber el signo zodiacal de alguien...

Utilización:

fecha_nacimiento = "09/10/1981"
mi_signo = PutSignoZodiacal(fecha_nacimiento)

response.write("Mi Signo Zodiacal es: " & mi_signo)

Resultado: Mi Signo Zodiacal es: Virgo

Código:
Function PutSignoZodiacal(strFechaNacimiento)
	strDia = day(strFechaNacimiento)
	strMes = month(strFechaNacimiento)
		
	select case strMes
		case 1
			if strDia <= 19 then strSigno = "Capricornio"
			if strDia >= 20 then strSigno = "Acuario"
		case 2
			if strDia <= 18 then strSigno = "Acuario"
			if strDia >= 19 then strSigno = "Piscis"
		case 3
			if strDia <= 20 then strSigno = "Piscis"
			if strDia >= 21 then strSigno = "Aries"
		case 4
			if strDia <= 20 then strSigno = "Aries"
			if strDia >= 21 then strSigno = "Tauro"
		case 5
			if strDia <= 20 then strSigno = "Tauro"
			if strDia >= 21 then strSigno = "Geminis"
		case 6
			if strDia <= 21 then strSigno = "Geminis"
			if strDia >= 22 then strSigno = "C&aacute;ncer"
		case 7
			if strDia <= 22 then strSigno = "C&aacute;ncer"
			if strDia >= 23 then strSigno = "Leo"
		case 8
			if strDia <= 22 then strSigno = "Leo"
			if strDia >= 23 then strSigno = "Virgo"
		case 9
			if strDia <= 22 then strSigno = "Virgo"
			if strDia >= 23 then strSigno = "Libra"
		case 10
			if strDia <= 22 then strSigno = "Libra"
			if strDia >= 23 then strSigno = "Escorpion"
		case 11
			if strDia <= 21 then strSigno = "Escorpion"
			if strDia >= 22 then strSigno = "Sagitario"
		case 12
			if strDia <= 21 then strSigno = "Sagitario"
			if strDia >= 22 then strSigno = "Capricornio"
		case else
			strSigno = ""
	end select
		
	PutSignoZodiacal = strSigno
End Function
__________________
Saruman

One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them.
  Responder Con Cita
Antiguo 25/04/05, 12:25:49   #65 (permalink)
Saruman tiene un saldo positivo de karma
 
Registrado: may 2003
Ubicación: Panamá
Mensajes: 1.125
Contactar con Saruman a través de MSN Contactar con Saruman a través de Yahoo
Saruman is offline  
Calcular el Raiting

Esta función permite culcular el raiting de un producto, artículo o lo que queramos valorar... ESTILO AMAZON.COM

Utilización:

voto1 = 2
voto2 = 3
voto3 = 1
voto4 = 6
voto5 = 8

Total de votos = 20

total = RateIt(voto1, voto2, voto3, voto4, voto5)

response.write(total)

Resultado: 4

<img src="estrella_<%=(total)%>.gif" border="0">


Código:
Function RateIt(strEstrella1, strEstrella2, strEstrella3, strEstrella4, strEstrella5)
	strFullEstrella = 0
	strTotal_Estrellas = strEstrella1 + strEstrella2 + strEstrella3 + strEstrella4 + strEstrella5
	if strEstrella1 > 0 then strEstrella1 = strEstrella1 * 1
	if strEstrella2 > 0 then strEstrella2 = strEstrella2 * 2
	if strEstrella3 > 0 then strEstrella3 = strEstrella3 * 3
	if strEstrella4 > 0 then strEstrella4 = strEstrella4 * 4
	if strEstrella5 > 0 then strEstrella5 = strEstrella5 * 5
		
	if strTotal_Estrellas > 0 then
		strFullEstrella = (strEstrella1 + strEstrella2 + strEstrella3 + strEstrella4 + strEstrella5) / strTotal_Estrellas
		strFullEstrella = round(strFullEstrella,0)
		if strFullEstrella > 5 then strFullEstrella = 5
	end if
		
	RateIt = strFullEstrella
End Function
__________________
Saruman

One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them.

Última edición por Saruman fecha: 03/05/05 a las 10:28:04.
  Responder Con Cita
Antiguo 29/04/05, 09:20:17   #66 (permalink)
Muzztein tiene un saldo positivo de karma
 
Registrado: nov 2002
Ubicación: Hangar 18
Mensajes: 1.189
Muzztein is offline  
Alegría estas sonviejas

Un par de funciones viejas mas refinadas


Esta funcion da la opcion de checar por la existencia de una variable, segun un tipo de dato requerido, en el caso de que no cumpla con la regla a validar, asigna un valor por defecto.

Código:
function checa_cadena(cadena,tipo_de_dato_a_chequear,valor_por_defecto)

	'tipo_de_dato_a_chequear = 0 cadena deberia ser una cadena de largo no igual a cero
	'tipo_de_dato_a_chequear = 1 cadena deberia ser numerico
	'tipo_de_dato_a_chequear = 2 cadena deberia ser fecha
	
	Select Case tipo_de_dato_a_chequear
    Case 0
		if len(cadena) = 0 then
			salida = valor_por_defecto
		else
			salida = cstr(cadena)
		end if
	Case 1
		if isnumeric(cadena) = false then
			salida = valor_por_defecto
		else
			salida = cadena
		end if
	Case 2
		if isdate(cadena) = false then
			salida = valor_por_defecto
		else
			salida = cadena
		end if
    Case Else 
		salida = cadena 
	End Select

	checa_cadena = salida

end function

Esta funcion unifica los modos de limpiar que puede presentar una variable.
permitiendo anexar mas formas de limpiar una cadena.

Código:
function limpia_cadena(str_a_limpiar,modo_de_limpiar)

	'modo_de_limpiar = 0 prepara str_a_limpiar para insert 
	'modo_de_limpiar = 1 Prepara str_a_limpiar para insert evitando, ademas, la entrada de HTML
	'modo_de_limpiar = 2 Prepara str_a_limpiar para un login y evita sql injection
	
	str = trim(str_a_limpiar)
	
	Select Case modo_de_limpiar
    Case 0
		str = replace(str,"'","''")
	Case 1
		str = replace(str,"'","''")
		str = replace(str,"<","&lt;")
		str = replace(str,">","&gt;")
	Case 2
                          str = lcase(str)
                          str = replace(str,"=","")
                          str = replace(str,"'","")
                          str = replace(str,"""""","")
                          str = replace(str," or ","")
                          str = replace(str," and ","")
                          str = replace(str,"(","")
                          str = replace(str,")","")
                          str = replace(str,"<","[")
                          str = replace(str,">","]")
                          str = replace(str,"having ","")
                          str = replace(str,"group by","")
                          str = replace(str,"union select sum","")
                          str = replace(str,"union select min","")
                          str = replace(str,"--","")
                          str = replace(str,"select ","")
                          str = replace(str,"insert ","")
                          str = replace(str,"update ","")
                          str = replace(str,"delete ","")
                          str = replace(str,"drop ","")
                          str = replace(str,"-shutdown","")
    Case Else 
        str = str_a_limpiar
	End Select

	limpia_cadena = str

end function


ahi sip


Un ejemplo de uso!

Código:
	iws_login		= checa_cadena(request.Form("iws_login"),0,false)
	iws_password	= checa_cadena(request.Form("iws_password"),0,false)
	
	if iws_login = false or iws_password = false then termina
	
	iws_login	 = limpia_cadena(iws_login,2)
	iws_password = limpia_cadena(iws_password,2)
__________________
On Error Resume Thinking

Última edición por Muzztein fecha: 29/04/05 a las 14:11:27.
  Responder Con Cita
Antiguo 10/05/05, 13:41:25   #67 (permalink)
drmkace tiene un saldo positivo de karma
 
Registrado: feb 2005
Mensajes: 26
drmkace is offline  
Esta es una funcion para Obtener un campo de una tabla determinada dada un acondicion en otor campo


Function ObtenerValorCampo(strTabla,strCampoResult,strCampo Donde,strValorDonde,cnn)

dim rst,sReturnValue,sSql

sSql="SELECT DISTINCT " & strCampoResult & " FROM " & strTabla & " WHERE " & strCampoDonde & "=" & strValorDonde
Set rst = CreateObject("ADODB.RecordSet")
with rst
.Open sSql,cnn
if not (.EOF and .BOF) then
ObtenerValorCampo=.Fields(strCampoResult)
Else
ObtenerValorCampo=""
End iF
.close
End With
set rst=Nothing
End function

PARAMETROS:
--------------

strTabla : Tabla
strCampoReult : CAmpo que Se desea devolver su Valor
strCampoDonde : Campo por el cual se desea filtrar / Buscar
strValorDonde : Valor para filtrar / Buscar en strCampoDonde
cnn : ADODB.Connection (Valida)
  Responder Con Cita
Antiguo 11/05/05, 09:25:42   #68 (permalink)
perrogrun tiene un saldo positivo de karma
 
Registrado: ene 2004
Mensajes: 266
perrogrun is offline  
Funcion que nos dice si una url tiene contenido o no

Imaginemos que tenemos una base de datos con enlaces y queremos checkear si éstos todavía existen, ¿Cómo podemos hacerlo desde asp con cierto éxito?

Código:
function enlace(url)
		set http_obj = createObject("Microsoft.XMLHTTP")
		ulr=request("url")
		http_obj.Open "GET",url,false
		On Error Resume Next
		http_obj.Send()
		if err.number <> 0 then
			enlace=false
		else
			codigo = Server.HTMLEncode(http_obj.responseText)
			if instr(codigo,"&lt;title&gt;No se encuentra la p&amp;aacute;gina&lt;/title&gt;")<>0 then
				enlace=false
			else
				enlace=true
			end if
			
			if instr(codigo,"El sistema no puede hallar el archivo especificado")<>0 then
				enlace=false
			else
				enlace=true
			end if
			
			if instr(codigo,"&lt;title&gt;Error&lt;/title&gt;")<>0 then
				enlace=false
			else
				enlace=true
			end if
		end if
		end function
Por ejemplo si ponemos
<%=enlace("http://www.instruccionesymanuales.com")%>
nos devuelve "true"
si ponemos
<%=enlace("http://www.manualesangle.com.es")%>
no devuelve "false"

Ya se que se puede mejorar añadiendo más posibles mensajes de error y por eso os animo a que juntos lo hagamos.

Un saludo y suerte a todos

*Nota: la función tarda un poco en ejecutarse porque tiene que recoger todo el código html de la web que buscamos, por lo que si queremos checkear toda una base de datos sugiero que pongáis un Server.ScriptTimeout bastante alto
__________________
Programador de Nicenova Consulting, posicionamiento en buscadores, alta en buscadores y Google Maps

Última edición por perrogrun fecha: 11/05/05 a las 09:46:35.
  Responder Con Cita
Antiguo 17/05/05, 05:03:20   #69 (permalink)
Bravenap tiene un saldo positivo de karma
 
Registrado: nov 2002
Ubicación: Madrid
Mensajes: 1.890
Send a message via Skype™ to Bravenap
Bravenap is offline  
Clave aleatoria (modificación)

Hola, esta es un pequeña modificación del código de pempas para generar una clave aleatoria (http://www.forosdelweb.com/showthrea...rio#post893965). La modificación es porque entre los caracteres ASCII que van desde el 48 al 90 se nos cuelan los siguientes indeseables:

58: :
59: ;
60: <
61: =
62: >
63: ?
64: @

Código:
function aleatorio()
	randomize
	car = Int((90 - 48 + 1) * Rnd + 48)
	aleatorio = car
end function

Dim clave
Dim tamano = 15

do while Len(clave) < tamano
	n = aleatorio()
	if n < 58 or n > 64 then
		clave = clave & chr(n)		
	end if
loop

Response.Write(clave)
Un saludo.
__________________
¡¡NO A LA GUERRA!!
Si ponemos a nuestros mensajes títulos adecuados, la gente se animará más a abrirlos y resultarán más útiles en las busquedas. ¡No a los ayuuudaaa, urgenteee y similares!
  Responder Con Cita
Antiguo 19/05/05, 13:52:27   #70 (permalink)
Muzztein tiene un saldo positivo de karma
 
Registrado: nov 2002
Ubicación: Hangar 18
Mensajes: 1.189
Muzztein is offline  
Parpadear Seguridad

Siguiendo con las funciones de seguridad.

Esta funcion compara la procedencia del usuario contra la procedencia que el programador especificó para que determinado script se pudiera ejecutar de manera segura.

Util para asegurarse, por ejemplo ,que una pagina del tipo eliminar.asp?id=12 sea accionada de su correcto formulario y no de manera directa, impidiendo así a un usuario mal intensionado hacer acciones que no esta autorizado a hacer.



Código:
function checa_procedencia(procedencia_autorizada,dominio_autorizado)

	aux = Request.ServerVariables("HTTP_REFERER")
	
	if len(aux) = 0 or aux = "" then 
		checa_procedencia = false
		exit function
	end if
	
	arreglo			 = split(aux,"/")
	dominio_real	 = arreglo(2)
	procedencia_real = arreglo(ubound(arreglo))
	
	if lcase(procedencia_real) = lcase(procedencia_autorizada) and lcase(dominio_real) = lcase(dominio_autorizado) then
		checa_procedencia = true
	else
		checa_procedencia = false
	end if
end function

Donde procedencia_autorizada es el nombre del archivo ASP que DEBE invocar a nuestro script a ejecutar, y donde dominio_autorizado es el dominio o nombre de la web de donde el script se esta ejecutando. ej : "www.misitio.com"

Modo de uso

Código:
if checa_procedencia("1.asp","localhost") = true then 
	escribe "eres bienvenido" 
else
	escribe "no eres binevenido"
end if

Consumala a discrecion

__________________
On Error Resume Thinking
  Responder Con Cita
Antiguo 30/05/05, 13:36:47   #71 (permalink)
Neuron_376 tiene un saldo positivo de karma
 
Registrado: abr 2005
Mensajes: 1.046
Neuron_376 is offline  
Variable inicializada

Funcion para asegurarnos completamente si si una variable ha sido inicializada y si contiene datos

Código HTML:
function Inicializada(Var)

  Inicializada = False

  if ((NOT isEmpty(Var)) and (NOT isNULL(Var)) and (Len(Trim(Expr)) > 0)) then 
    Inicializada = TRUE
  end if

END FUNCTION
if Inicializada(Session("Var"))
//Tienes acceso
else
//No tienes acceso
end if

Aplica para cualquier variable.

Es como Isset de PHP

Suerte!!
__________________
NeuronaNet.com... la idea correcta.
http://www.NeuronaNet.com
  Responder Con Cita
Antiguo 30/05/05, 16:26:41   #72 (permalink)
Saruman tiene un saldo positivo de karma
 
Registrado: may 2003
Ubicación: Panamá
Mensajes: 1.125
Contactar con Saruman a través de MSN Contactar con Saruman a través de Yahoo
Saruman is offline  
De acuerdo Super Fast String Concatenation

Función para concatenar miles de variables en una sola y rápidamente...
normalmente se utiliza:

for I = 1 to 10000
mivariable = mivariable & I
next

y esto nos arroja timeout en nuestras páginas de asp y además es super lento

Esta clase reemplaza eso y lo hace super rápido (segundos)

aquí les va:

Código:
Class StringBuilder
	Private Sub Class_Initialize()
		growthRate = 50
		itemCount = 0
		ReDim arr(growthRate)
	End Sub
	
	Public Sub Append(ByVal strValue)
		If itemCount > UBound(arr) Then
			ReDim Preserve arr(UBound(arr) + growthRate)
		End If
	
		arr(itemCount) = strValue
		itemCount = itemCount + 1
	End Sub
	
	Public Function ToString() 
		ToString = Join(arr, "")
	End Function
End Class
UTILIZACIÓN:

Código:
Dim objBuilder, i
Set objBuilder = new StringBuilder

For i = 0 To 5000
variable = "este es el número: " & i & "<br>" & vbcrlf
objBuilder.Append(variable) Next Response.Write objBuilder.ToString()

está super cool esta función...
__________________
Saruman

One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them.
  Responder Con Cita
Antiguo 02/06/05, 13:01:31   #73 (permalink)
mariano_donati tiene un saldo positivo de karma
 
Registrado: mar 2005
Mensajes: 1.084
mariano_donati is offline  
Función de validación genérica de los campos comunes de un formulario:


function isIt_Valid(Var, len_allowed, numbers_allowed, text_allowed)

Dim intruders_symbols
Dim valid_state

intruders_symbols = array("insert","select","drop","database","'","""" ,"*","--","-","delete","update","true","<",">")
Var = Lcase(Var)

valid_state = true

For i=0 To UBound(Intruders_symbols)
If Instr(Var, Intruders_symbols(i)) > 0 then
valid_state = "intruder"
isIt_Valid = valid_state
exit function
end if
next

if numbers_allowed = true And text_allowed = true then
For i = 1 To Len(Var)
If(Mid(Var, i, 1) < "a" Or Mid(Var, i, 1) > "z") And _
(Mid(Var, i, 1) < "0" Or Mid(Var, i, 1) > "9") then
valid_state = false
isIt_Valid = valid_state
exit function
End If
next

elseif numbers_allowed = true And text_allowed = false then
For i = 1 To Len(Var)
If(Mid(Var, i, 1) < "0" Or Mid(Var, i, 1) > "9") then
valid_state = false
isIt_Valid = valid_state
exit function
end if
next

elseif numbers_allowed = false And text_allowed = true then
For i = 1 To Len(Var)
If(Mid(Var, i, 1) < "a" Or Mid(Var, i, 1) > "z") then
valid_state = false
isIt_Valid = valid_state
exit function
end if
Next
end if

if Len(Var) > len_allowed OR Var = "" then
valid_state = false
isIt_Valid = valid_state
exit function
end if

isIt_Valid = valid_state

end function


En donde Var sería el campo a validar, len_allowed el máximo permitido de caracteres, numbers_allowed una propiedad boleana que especifica si el campo podrá contener números o no, text_allowed lo mismo que la anterior, pero especificando en true o false si podrá o no contener letras respectivamente.

Un ejemplo de su uso:

Dim FieldName
FieldName = "Mariano"

state = isIt_Valid(FieldName, 12, false, true)

El resultado obviamente sería TRUE.
Saludos y espero que le sirva a alguien.
Suerte!.
  Responder Con Cita
Antiguo 09/06/05, 07:41:35   #74 (permalink)
mariano_donati tiene un saldo positivo de karma
 
Registrado: mar 2005
Mensajes: 1.084
mariano_donati is offline  
Función que sirve para ordenar un array, no me acuerdo de que página lo extraje ni quien es el autor, ya uqe hace tiempo que conseguí esta función en la red. Si alguien ha visto esta función en alguna página, que cite el autor y la página asi somos justos.


FUNCTION SortArray(varArray)
For i = UBound(varArray, 2) - 1 To 1 Step - 1
MaxVal = varArray(1, i)
MaxIndex = i

For j = 0 To i
If varArray(1, j) > MaxVal Then
MaxVal = varArray(1, j)
MaxIndex = j
End If
Next

If MaxIndex < i Then
varArray(1, MaxIndex) = varArray(1, i)
varArray(1, i) = MaxVal
End If
Next
END FUNCTION

Con esto se puede probar:

REDIM arrSORT(1, 8)

arrSORT(0,0)= 1
arrSORT(0,1)= 20
arrSORT(0,2)= 49
arrSORT(0,3)= 74
arrSORT(0,4)= 23
arrSORT(0,5)= 73
arrSORT(0,6)= 21
arrSORT(0,7)= 4
arrSORT(1,0)= "Argentina"
arrSORT(1,1)= "Mexico"
arrSORT(1,2)= "Brazil"
arrSORT(1,3)= "España"
arrSORT(1,4)= "Chile"
arrSORT(1,5)= "Guatemala"
arrSORT(1,6)= "Italia"
arrSORT(1,7)= "Groenlandia"
arrSORT(1,8)= "Nicaragua"

Response.write "<TABLE BORDER=1 WIDTH=100% ><TR><TD><B>UNSORTED</B></TD><TD><B>SORTED</B></TD></TR>"
Response.write "<TR><TD>"

FOR i = 0 TO UBOUND(arrSORT,2) - 1
Response.write "<B>arrSORT(" & i & ") value: </B>" & arrSORT(1, i) & "<BR>"
NEXT

Response.write "</TD><TD>"

SortArray arrSORT

FOR i = 0 TO UBOUND(arrSORT,2) - 1
Response.write "<B>arrSORT(" & i & ") value: </B>" & arrSORT(1, i) & "<BR>"
NEXT


Response.write "</TD></TR></TABLE>"
%>
  Responder Con Cita
Antiguo 11/07/05, 12:47:04   #75 (permalink)
Saruman tiene un saldo positivo de karma
 
Registrado: may 2003
Ubicación: Panamá
Mensajes: 1.125
Contactar con Saruman a través de MSN Contactar con Saruman a través de Yahoo
Saruman is offline  
Proósito: Convertir los los links e emails en links de html.

Utilización:

Código:
 
texto = "www.forosdelweb.com"
texto = InsertHyperlinks(texto) 
response.write(texto)

Funciones:

Código:
 
'Convierte los E-Mail's y los Links en enlaces
Function InsertHyperlinks(strInText, strEstilo)
Dim objRegExp, strBuf
Dim objMatches, objMatch
Dim Value, ReplaceValue, iStart, iEnd
 
strBuf = ""
iStart = 1
iEnd = 1
 
Set objRegExp = New RegExp
 
objRegExp.Pattern = "\b(www|http|\S+@)\S+\b"
objRegExp.IgnoreCase = True
objRegExp.Global = True
Set objMatches = objRegExp.Execute(strInText)
 
For Each objMatch in objMatches
iEnd = objMatch.FirstIndex
strBuf = strBuf & Mid(strInText, iStart, iEnd-iStart+1)
 
If InStr(1, objMatch.Value, "@") Then
	strBuf = strBuf & GetHref(objMatch.Value, "email", "_blank", strEstilo)
Else
	strBuf = strBuf & GetHref(objMatch.Value, "web", "_blank", strEstilo)
End If
 
iStart = iEnd+objMatch.Length+1
Next
 
strBuf = strBuf & Mid(strInText, iStart)
InsertHyperlinks = strBuf
End Function
 
 
Function GetHref(url, urlType, Target, strEstilo)
Dim strBuf
 
if strEstilo <> "" then strEstilo = "class=""" & strEstilo & """"
 
strBuf = "<a href="""
 
If urlType = "web" Then
If LCase(Left(url, 3)) = "www" Then
	strBuf = "<a href=""http://" & url & """ target=""" & Target & """ " & strEstilo & ">" & url & "</a>"
Else
	strBuf = "<a href=""" & url & """ target=""" & Target & """ " & strEstilo & ">" & url & "</a>"
End If
 
ElseIf UCase(urlType) = "email" Then
strBuf = "<a href=""mailto:" & url & """ target=""" & Target & """ " & strEstilo & ">" & url & "</a>"
End If
 
GetHref = strBuf
End Function
__________________
Saruman

One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them.
  Responder Con Cita
Antiguo 19/07/05, 12:07:36   #76 (permalink)
dobled ha deshabilitado el Karma
 
Registrado: nov 2002
Ubicación: 34°10'55.23S70°42'22.83W
Mensajes: 1.258
Contactar con dobled a través de MSN Send a message via Skype™ to dobled
dobled is offline  
Funcion para Redireccionar con mensajeBox

Código:
Sub Redirecciona(pagina,mensaje)
If pagina="" Then
pagina="window.history.back();"
ElseIf isNumeric(pagina) Then
pagina="window.history.go(-"&pagina&")"
Else pagina="location.href='"&pagina&"';"
End If

Response.Write("<script language=""javascript"">")

If mensaje<>"" Then
Response.Write("alert('"&Mensaje&"');")
End If

Response.Write (pagina&"</script>")
Response.End
End Sub
se utiliza asi

Código:
<%
Call Redirecciona("form_ingreso_cursos.asp","El curso "&nom_curso&" se ingreso correctamente.")
%>
o

Código:
<%
    Call Redirecciona("","Los datos son erroneos.")
%>
__________________
Usa títulos específicos y con sentido
En las listas de correo o en los grupos de noticias, la cabecera del mensaje es tu oportunidad de oro para atraer la atención de expertos cualificados en aproximadamente 50 caracteres o menos. No los desperdicies en balbuceos como "Por favor ayúdame" (de "POR FAVOR AYÚDAME!!!" ya ni hablamos). No intentes impresionarnos con lo profundo de tu angustia; mejor usa ese preciado espacio para una descripción lo más concisa posible del problema.
  Responder Con Cita
Antiguo 23/07/05, 14:29:55   #77 (permalink)
mariano_donati tiene un saldo positivo de karma
 
Registrado: mar 2005
Mensajes: 1.084
mariano_donati is offline  
Sacar el máximo valor de un array

Código:
function GetMax(param_arr)
 
Dim endLoop, maxValue
endLoop = UBound(param_arr) - 1
maxValue = 0 
   
   for i=0 to endLoop
	   if param_arr(i) > param_arr(i+1) and param_arr(i) => maxValue then
	   maxValue = param_arr(i)
	elseif arr(i + 1) > maxValue then 
	   maxValue = param_arr(i+1)
	end if
   next
  
   GetMax = maxValue
end function
Así se llama:

Dim arr(4)
arr(0) = 50392
arr(1) = 239023
arr(2) = 493
arr(3) = 4892
arr(4) = 4095

Response.Write(GetMax(arr)) ' Devuelve 239023

Espero que sea útil.
Saludos!.
__________________
En el este y el oeste, en el Norte y en el sur, brilla la blanca y celeste, la academia Racing Club
  Responder Con Cita
Antiguo 25/07/05, 00:38:17   #78 (permalink)