Dado el uso del lenguaje ASP el tratamiento de cadenas es muy importante, existen bastantes funciones para el manejo de cadenas, a continuación explicaremos las más usadas.
<!-- Manual de ASP -->
<html>
<head>
<title>Ejemplo de ASP</title>
</head>
<body>
<%
Dim palabras,i
Response.Write(len("12345") & "<br>")
i=0
palabras=split("Esto es una prueba"," ")
Response.Write(palabras(0)&"<br>")
Response.Write(palabras(1)&"<br>")
Response.Write(palabras(2)&"<br>")
Response.Write(palabras(3)&"<br><br>")
Response.Write(mid("Devuelve una subcadena de otra",9,3) & "<br><br>")
if trim(" Cadena ") = "Cadena" then
Response.Write("Iguales<br><br>")
end if
Response.Write(instr("Busca la palabra dentro de la frase", "palabra") & "<br><br>")
Response.Write(replace("Un pez de color verde, como verde es la hierba.","verde","rojo") & "<br>")
%>
</body>
</html>
Me tomé la libertad de hacer una traducción libre (con algunos comentarios míos agregados) de “ 20 Tips to Improve ASP.net Application Performance “:
When you run your ASP.NET application by using the ASP.NET process model, it is even more important to have buffering enabled. The ASP.NET worker process first sends responses to IIS in the form of response buffers. After the ISAPI filter is running, IIS receives the response buffers. These response buffers are 31 KB in size., After IIS receives the response buffers, it then sends that actual response back to the client. With buffering disabled, instead of using the entire 31-KB buffer, ASP.NET can only send a few characters to the buffer. This causes extra CPU processing in both ASP.NET as well as in IIS. This may also cause memory consumption in the IIS process to increase dramatically.
Consider using the HttpResponse.IsClientConnected property to verify if the client is still connected before processing a request and performing expensive server-side operations. However, this call may need to go out of process on IIS 5.0 and can be very expensive. If you use it, measure whether it actually benefits your scenario .
Script en ASP para montar un lector de RSS. El ejemplo lee el RSS de digg, que presenta la siguiente estructura:
<item>
<title></title>
<link></link>
<description></description>
<pubDate></pubDate>
<guid isPermaLink="true"></guid>
<digg:diggCount></digg:diggCount>
</item>
Esta información es la que puede variar y sólo tendríamos que recoger el nodo adecuado a nuestros propósitos con objItem.childNodes(), de acuerdo a la estructura del XML que deseasemos recoger.
CSS
.titulo_rss a{
font: bold 13px "Trebuchet MS", Verdana, Arial;
color: #676D46;
text-decoration:none;
display:block;
margin-top:30px;
}
.titulo_rss a:hover{
color: #666;
}
.descripcion_rss {
font: 11px Verdana, Arial, Helvetica, sans-serif;
color: #888;
display:block;
margin-top:10px;
}
.fecha_rss {
font: 10px "Lucida Sans Unicode", Verdana, Arial, Georgia;
color: #CC6633;
}
ASP
<%
Response.Charset = "iso-8859-1"
Dim objXML
Dim objItemList
Dim objItem
Dim strHTML
Set objXML = Server.CreateObject("MSXML2.FreeThreadedDOMDocument")
objXML.async = False
objXML.setProperty "ServerHTTPRequest", True
objXML.Load("http://www.digg.com/rss/index.xml")
If objXML.parseError.errorCode <> 0 Then
Response.Write "<pre>" & vbCrLf
Response.Write "<strong>Error:</strong> " & objXML.parseError.reason
Response.Write "<strong>Linea:</strong> " & objXML.parseError.line & vbCrLf
Response.Write "<strong>Texto:</strong> " & Server.HTMLEncode(objXML.parseError.srcText) & vbCrLf
Response.Write "</pre>" & vbCrLf
End If
'OBTENEMOS TODOS LOS ITEM
Set objItemList = objXML.getElementsByTagName("item")
Set objXML = Nothing
For Each objItem In objItemList
'OBTENEMOS LOS DISTINTOS NODOS
TituloRSS = objItem.childNodes(0).text
LinkRSS = objItem.childNodes(1).text
DescripcionRSS = objItem.childNodes(2).text
FechaRSS = objItem.childNodes(3).text
Response.Write ("<span class=""titulo_rss""><a"
href='" & LinkRSS & "'>" & TituloRSS & "</a></span>")"
Response.Write ("<span class=""fecha_rss"">" & FechaRSS & "</span>")
Response.Write ("<span class=""descripcion_rss"">" & DescripcionRSS & "</span>")
Next
Set objItemList = Nothing
Application.Lock
Application("LectorRSSContenido") = strHTML
Application("LectorRSSActualizado") = Now()
Application.UnLock
%>
<%= Application("LectorRSSContenido") %>
<%= Application("LectorRSSActualizado") %>
Un archivo XML puede ser creado fácilmente desde cualquier editor de texto, hasta Notepad. Pero, ¿que hacemos cuando necesitamos generarlo dinámicamente?
Si no necesitamos guardar una copia en disco duro, podemos simplemente enviar el contenido XML desde nuestra página ASP, estableciendo antes el tipo de contenido a enviar como XML, como en el siguiente ejemplo:
<%
Response.ContentType="text/xml"
Response.Write("<?xml version='1.0' ?>")
Response.Write("<nota>")
Response.Write("<de>Jorge</de>")
Response.Write("<a>Jose</a>")
Response.Write("<mensaje>Hola!</mensaje>")
Response.Write("</nota>")
%>
La razón mas común para generar un XML dinámicamente es que necesitamos extraer datos desde una base de datos, como lo ilustra el siguiente ejemplo:
<%
Response.ContentType = "text/xml"
set conn=Server.CreateObject("ADODB.Connection")
conn.provider="Microsoft.Jet.OLEDB.4.0;"
conn.open server.mappath("BaseDeDatos.mdb")
sql="select nombre, apellido from Clientes"
set rs = Conn.Execute(sql)
rs.MoveFirst()
response.write("<?xml version='1.0' ?>")
response.write("<clientes>")
while (not rs.EOF)
response.write("<cliente>")
response.write("<nombre>" & rs("nombre") & "</nombre>")
response.write("<apellido>" & rs("apellido") & "</apellido>")
response.write("</cliente>")
rs.MoveNext()
wend
rs.close()
conn.close()
response.write("</clientes>")
%>
Finalmente, si lo que necesitamos es grabar el archivo XML en disco duro, podemos hacerlo con el objeto Microsoft.XMLDOM:
<%
Dim objDom
Dim objRaiz
Dim objHijo1
Dim objHijo2
Dim objCabecera
'instanciamos el XMLDOM
Set objDom = Server.CreateObject("Microsoft.XMLDOM")
'instanciamos el elemento raiz y lo agregamos al objeto XMLDOM
Set objRaiz = objDom.createElement("ElementoRaiz")
objDom.appendChild objRaiz
'instanciamos el elemento Hijo1 y lo agregamos al elemento raiz
Set objHijo1 = objDom.createElement("childElement1")
objRaiz.appendChild objHijo1
'instanciamos el elemento Hijo2 y lo agregamos al elemento raiz
Set objHijo2 = objDom.createElement("childElement2")
objRaiz.appendChild objHijo2
'instanciamos la cabecera
Set objCabecera = objDom.createProcessingInstruction("xml","version='1.0'")
'agregamos la cabecera antes del elemento raiz
bjDom.insertBefore objCabecera, objDom.childNodes(0)
'finalmente grabamos el XML en disco duro
objDom.Save "c:\MiArchivoXML.xml"
%>
Así hemos revisado las distintas formas de generar XML desde ASP. En próximas entregas veremos como manipular nodos con el objeto XMLDOM.
Este script, bastante sencillo, nos permite negar o no el acceso a una página privada. Para ello se utiliza un formulario con dos casillas, una para el usuario y la otra para el password (formulario.htm), y la página que queremos protejer, en este caso paginaprivada.asp.
formulario.htm
<form method="POST" action="paginaprivada.asp">
Usuario: <input type="text" name="usuario" size="10"><br>
Password: <input type="password" name="password" size="10"><br>
<input type="submit" value="Enviar" name="privado"></p>
</form>
El formulario envía los datos ingresados a paginaprivada.asp para su proceso.
paginaprivada.asp
<%Este ejemplo es muy útil cuando hay información en nuestro sitio, que queremos que sea visto por unas determinadas personas. O también cuando se trata de una listado desde una base de datos, que solo nosotros queremos mirar.
' Recojemos los datos ingresados en el formulario
usuario = Request.Form(sñ·0000·ñs)
password = Request.Form(sñ·0001·ñs)
' Comparamos a ver si son correctos
if usuario ="tuuser" and password="tupass" then
valido="si"
else
valido="no"
end if
%>
<html>
<head>
<title>Pagina privada</title>
</head>
<body>
<% if valido="si" then%>
' A continuación todo el contenido de nuestra pagina privada
<p>BIENVENIDO A LA PAGINA PRIVADA</p>
<%else%>
<p>USUARIO O CONTRASEÑA INCORRECTA</p>
<% end if%>
</body>
</html>
Hola amigos aquí esta una función que te devuelve una tabla con el calendario del día que le mandes o sino del día actual.
Checalo Si tienes alguna duda sobre este tutorial visita el foro.
<%
function calendar(today)
if isnull(today) then
today = date
end if
today = DateValue(today)
todays_day = day(today)
todays_month = month(today)
todays_year = year(today)
month_names = Array("January", _
"February", _
"March", _
"April", _
"May", _
"June", _
"July", _
"August", _
"September", _
"October", _
"November", _
"December")
this_month = datevalue(todays_month & "/1/" & todays_year)
next_month = datevalue(dateadd("m", 1, todays_month & "/1/" & todays_year))
'Find out when this month starts and ends.
first_week_day = weekday(this_month) - 1
days_in_this_month = datediff("d", this_month, next_month)
calendar_html = "<table style=""background-color:666699; color:ffffff;"">"
calendar_html = calendar_html & _
"<tr><td colspan=""7"" align=""center"" style=""background-color:9999cc; color:000000;"">" & _
month_names(todays_month - 1) & " " & todays_year & "</td></tr>"
calendar_html = calendar_html & "<tr>"
'Fill the first week of the month with the appropriate number of blanks.
for week_day = 0 to first_week_day - 1
calendar_html = calendar_html & "<td style=""background-color:9999cc; color:000000;""> </td>"
next
week_day = first_week_day
for day_counter = 1 to days_in_this_month
week_day = week_day mod 7
if week_day = 0 then
calendar_html = calendar_html & "</tr><tr>"
end if
'Do something different for the current day.
if todays_day = day_counter then
calendar_html = calendar_html & "<td align=""center""><b>" & day_counter & "</b></td>"
else
calendar_html = calendar_html & _
"<td align=""center"" style=""background-color:9999cc; color:000000;""> " & _
day_counter & " </td>"
end if
week_day = week_day + 1
next
calendar_html = calendar_html & "</tr>"
calendar_html = calendar_html & "</table>"
Calendar = calendar_html
end function
%>
Descarga el ejemplo abajo.
Lee todas las lineas de un archivo de texto
<%
Set fs = CreateObject("scripting.FileSystemObject")
Set wfile = fs.openTextFile("c:Mydirmyfile.txt")
counter=0
do while not wfile.AtEndOfStream
counter=counter+1
singleline=wfile.readline
response.write (counter & singleline & "<br>")
loop
wfile.close
Set wfile=nothing
Set fs=nothing
%>veamos como escribir los IP de los visitantes en un archivo de texto
<%
VisitorsIP=Request.ServerVariables ("REMOTE_ADDR")
Set fs = CreateObject("scripting.FileSystemObject")
Set wfile = fs.openTextFile("c:Mydirmylog.txt", forappending)
wfile.WriteLine (VisitorsIP)
wfile.close
Set wfile=nothing
Set fs=nothing
response.write("IP registered")
%>Codigo que elimina un folder del servidor.
<%
Set fs = CreateObject("scripting.FileSystemObject")
fs.DeleteFolder("d:rameworld")
%>Elimina un archivo utilizando FSO
<%
Set fs = CreateObject("scripting.FileSystemObject")
fs.DeleteFile "d:ramesh.htm", true
%>