Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas


Dicas Active Server Pages I - Apostilas - Informática Part2, Notas de estudo de Informática

Apostilas de Informática sobre Active Server Pages, Como rodar páginas ASP em um micro com Windows 95/98, Rodando ASP fora do Ambiente WINDOWS, Funcionamento, Convenção e Simbologia.

Tipologia: Notas de estudo

2013

Compartilhado em 28/08/2013

Garoto
Garoto 🇪🇸

4.6

(121)

1 / 32

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
ASPDica1.doc Página 33 de 94
' cursor, read only, and telling it that "scratch" is a table name and
' not a SQL command. If I don't specify how to open the rs, I'd get the
' default cursor type which doesn't support .RecordCount!
rsCount.Open "scratch", DB_CONNSTRING, adOpenStatic, adLockReadOnly,
adCmdTable
' Show RecordCount
' I dress it up and pop it into the middle of a sentence, but you can
' do whatever you want with it.
Response.Write "This table currently has <B><FONT COLOR=""#FF0000"">"
Response.Write rsCount.RecordCount ' This is the line that does it!
Response.Write "</FONT></B> records in it!<BR>" & vbCrLf
'======================================================================
' BEGIN TABLE DISPLAY
' Now I'm going to display the table if they requested it just so you
' have something to look at! This really doesn't pertain to the topic
' of this sample so I'm going to keep the code short but feel free to
' look it over and if you do please notice the pretty HTML it outputs!
' Ugly HTML output is a pet peeve of mine! ;)
If LCase(Request.QueryString("showtable")) = "true" Then
Dim Field ' Field Looper for display
Dim bColor ' Use for showing alternating colors
bColor = False
' Spacers and intro
Response.Write "<BR>" & vbCrLf & "They are:<BR>" & vbCrLf & "<BR>"
& vbCrLf
' Start the table
Response.Write "<TABLE BORDER=""1"">" & vbCrLf
' Write Titles
Response.Write vbTab & "<TR>" & vbCrLf
For Each Field in rsCount.Fields
Response.Write vbTab & vbTab & "<TD
BGCOLOR=""#CCCCCC""><B>" & Field.Name & "</B></TD>" & vbCrLf
Next 'Field
Response.Write vbTab & "</TR>" & vbCrLf
' Loop through records outputting data
Do While Not rsCount.EOF
Response.Write vbTab & "<TR>" & vbCrLf
For Each Field in rsCount.Fields
Response.Write vbTab & vbTab & "<TD BGCOLOR="""
' Decide what color to output
If bColor Then
Response.Write "#CCCCFF" ' Light blueish
Else
Response.Write "#FFFFFF" ' White
End If
Response.Write """>" & Field.Value & "</TD>" &
vbCrLf
Next 'Field
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20

Pré-visualização parcial do texto

Baixe Dicas Active Server Pages I - Apostilas - Informática Part2 e outras Notas de estudo em PDF para Informática, somente na Docsity!

' cursor, read only, and telling it that "scratch" is a table name and ' not a SQL command. If I don't specify how to open the rs, I'd get the ' default cursor type which doesn't support .RecordCount! rsCount.Open "scratch", DB_CONNSTRING, adOpenStatic, adLockReadOnly, adCmdTable

' Show RecordCount ' I dress it up and pop it into the middle of a sentence, but you can ' do whatever you want with it. Response.Write "This table currently has <FONT COLOR=""#FF0000"">" Response.Write rsCount.RecordCount ' This is the line that does it! Response.Write " records in it!
" & vbCrLf

' BEGIN TABLE DISPLAY

' Now I'm going to display the table if they requested it just so you ' have something to look at! This really doesn't pertain to the topic ' of this sample so I'm going to keep the code short but feel free to ' look it over and if you do please notice the pretty HTML it outputs! ' Ugly HTML output is a pet peeve of mine! ;) If LCase(Request.QueryString("showtable")) = "true" Then Dim Field ' Field Looper for display Dim bColor ' Use for showing alternating colors bColor = False

' Spacers and intro Response.Write "
" & vbCrLf & "They are:
" & vbCrLf & "
" & vbCrLf

' Start the table Response.Write "<TABLE BORDER=""1"">" & vbCrLf

' Write Titles Response.Write vbTab & "" & vbCrLf For Each Field in rsCount.Fields Response.Write vbTab & vbTab & "<TD BGCOLOR=""#CCCCCC"">" & Field.Name & "" & vbCrLf Next 'Field Response.Write vbTab & "" & vbCrLf

' Loop through records outputting data Do While Not rsCount.EOF Response.Write vbTab & "" & vbCrLf For Each Field in rsCount.Fields Response.Write vbTab & vbTab & "<TD BGCOLOR="""

' Decide what color to output If bColor Then Response.Write "#CCCCFF" ' Light blueish Else Response.Write "#FFFFFF" ' White End If

Response.Write """>" & Field.Value & "" & vbCrLf Next 'Field

Response.Write vbTab & "" & vbCrLf

' Toggle our colors bColor = Not bColor rsCount.MoveNext Loop

' End the table Response.Write "" & vbCrLf Response.Write "
<A HREF=""db_count.asp"">Hide the table" & vbCrLf Else Response.Write "
<A HREF=""db_count.asp?showtable=true"">Show the table" & vbCrLf End If ' END TABLE DISPLAY - Now back to our regularly scheduled code! '======================================================================

' Close and dispose of recordset object rsCount.Close Set rsCount = Nothing %>

I wrote this sample to answer the question that I'm sure has been on everyone's mind: "How long can an ASP reference site go before putting up a sample hit counter script?" Well whatever the old record was I think we probably shattered it! I've finally broken down and decided to write one. It's pretty simplistic and doesn't really show off the power of ASP, but what do you want... after all it is just a counter!

It stores it's value in a textfile and counts each request. I didn't bother with a session count. If you're interested in that see my article "Counting Active Users!" and just remove the line that decrements the count!

What I did do is take into account some of the things that you might want in a hit counter. First of all you can use this script two different ways. You can cut and paste it into the page you want the count to appear on or you can use it as an include file and just place one line of text in the document where you want the count to appear. The text should look something like this:

One thing to note about using this syntax is that the count file it creates will be wherever the file doing the including is located and this is not necessarily where the script is located! This may be confusing at first, but it allows you to include the same file and run multiple independent counters on different pages with only one set of the code!

Another thing to note is that it'll create it's own file to keep track of the count if it doesn't find one. This makes it pretty darn easy to install. The main problem you might run into is if NTFS permissions don't allow the anonymous internet user to write to the counter.txt file. Once you get any NTFS issues straightened out all should be right with the world!

The last thing that bears mentioning is that, as it stands, the script will let you choose either plain text or a set of images. You can toggle this by setting the images querystring parameter to true or false. If you always use one or the other it probably makes sense to hard code the value in, but for illustration and flexability I let you change it on the fly. And for those of you who actually care (and are still reading this) the default is to use text. <% ' Declare our vaiables Dim objFSO, objCountFile ' object vars for FSO and File Dim strCountFileName ' filename of count text file

' We're all done with the hard part ' All that's left is to display the results If bUseImages Then ' Loop through the count integer showing each digit ' You can grab the images one at a time or get the zip ' http://www.asp101.com/samples/download/counter_imgs.zip For I = 1 to Len(iCount) ' Output the IMG tag using the right digit Response.Write "<IMG SRC=""./images/digit_" Response.Write Mid(iCount, I, 1) Response.Write ".gif"" ALT=""" Response.Write Mid(iCount, I, 1) Response.Write """ WIDTH=""20"" HEIGHT=""27"">" Next 'I Else ' No image wanted just show the variable Response.Write iCount End If %>

P/ adionar um cookies

Cookie to add:

Cookie Name:

Cookie Value:

Set Cookie

HTML gerado pelo ASP

Cookie to add:
Cookie Name:
Cookie Value:
<% If Request.QueryString("CookieName") <> "" Then Response.Cookies(Request.QueryString("CookieName")) = Request.QueryString("CookieValue") If Request.QueryString("ToDo")= "add" Then

Response.Cookies(Request.QueryString("CookieName")).Expires = Date() + 1 Else

Response.Cookies(Request.QueryString("CookieName")).Expires = Date() - 1 End If End If Response.Redirect("./cookie.asp") %>

This table lists all of our cookies on your computer.

Cookie Name Cookie Value

Add a cookie to your machine. Delete a cookie from your machine.

Sample HTML Code generated by the ASP:

This table lists all of our cookies on your computer.

Cookie Name Cookie Value

Cookie

Value

ASP Source Code:

This table lists all of our cookies on your computer.

<% Dim Item %> <% For Each Item in Request.Cookies %> " & vbCrLf Response.Write vbTab & vbTab & "" & vbCrLf Response.Write vbTab & "" & vbCrLf

If Not objRecordset.EOF Then objRecordset.MoveFirst 'Show data Do While Not objRecordset.EOF Response.Write vbTab & "

" & vbCrLf For I = 0 To objRecordset.Fields.Count - 1 Response.Write vbTab & vbTab & "" & vbCrLf iRecordAdded = objRecordset.Fields("id") Next Response.Write vbTab & "" & vbCrLf objRecordset.MoveNext Loop End If Response.Write "
Cookie Name Cookie Value
<% = Item %>

Sort By:

ID Ascending

Run Query

Sample HTML Code generated by the ASP:

Results of SELECT Salesmen.* FROM Salesmen WHERE (Sales <> 0) ORDER BY [Last Name];


ASP Source Code:

<% Dim DataConn, cmdDC, rsDC Dim Item Dim iFieldCount, iLoopVar Dim strLTorGT, iCriteria, strSortBy, strOrder

' Retrieve QueryString Variables and convert them to a usable form strLTorGT = Request.QueryString("LTorGT") Select Case strLTorGT Case "LT" strLTorGT = "<" Case "GT" strLTorGT = ">" Case Else strLTorGT = "<>" End Select

iCriteria = Request.QueryString("criteria") If IsNumeric(iCriteria) Then iCriteria = CLng(iCriteria) Else iCriteria = 0 End If

strSortBy = Request.QueryString("sortby") If strSortBy = "" Then strSortBy = "last_name"

strOrder = Request.QueryString("order") ' Finally we've got all our info, now to the cool stuff

' Create and establish data connection Set DataConn = Server.CreateObject("ADODB.Connection") DataConn.ConnectionTimeout = 15 DataConn.CommandTimeout = 30

'Access connection code 'DataConn.Open "DBQ=" & Server.MapPath("database.mdb") & ";Driver={Microsoft Access Driver (*.mdb)};DriverId=25;MaxBufferSize=8192;Threads=20;", "username", "password"

'Our SQL Server code - use above line to use sample on your server DataConn.Open Application("SQLConnString"), Application("SQLUsername"), Application("SQLPassword")

' Create and link command object to data connection then set attributes and SQL query Set cmdDC = Server.CreateObject("ADODB.Command") cmdDC.ActiveConnection = DataConn cmdDC.CommandText = "SELECT * FROM sample WHERE (Sales " & strLTorGT & " " & iCriteria & ") ORDER BY " & strSortBy & strOrder & ";" cmdDC.CommandType = 1

' Create recordset and retrieve values using command object Set rsDC = Server.CreateObject("ADODB.Recordset") ' Opening record set with a forward-only cursor (the 0) and in read-only mode (the 1) rsDC.Open cmdDC, , 0, 1 %>

Results of <%= cmdDC.CommandText %>


ID Last Name First Name Sales
4 Buchanan Steven 3245
7 Callahan Laura 3670
2 Davolio Nancy 2750
8 Dodsworth Anne 4385
11 Franken Peter 4050
1 Fuller Andrew 5000
9 King Robert 5290
10 Labrune
<% For Each Item in rsDC.Fields %> <% Next %> <% ' Loop through recordset and display results If Not rsDC.EOF Then rsDC.MoveFirst

' Get the number of fields and subtract one so our loops start at 0 iFieldCount = rsDC.Fields.Count - 1

' Continue till we get to the end, and while in each

loop through fields Do While Not rsDC.EOF %> <% For iLoopVar = 0 to iFieldCount %>

<% Next %> <% rsDC.MoveNext Loop %>
<%= Item.Name %>
<%= rsDC.Fields(iLoopVar) %>

' Close Data Access Objects and free DB variables rsDC.Close Set rsDC = Nothing ' can't do a "cmdDC.Close"! Set cmdDC = Nothing DataConn.Close Set DataConn = Nothing %>


Build your own query:

Sales: Less Than Greater Than

<%' Defining some constants to make my life easier! ' Begin Constant Definition

' DB Configuration constants ' Fake const so we can use the MapPath to make it relative. ' After this, strictly used as if it were a Const. Dim DB_CONNECTIONSTRING DB_CONNECTIONSTRING = "DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" & Server.Mappath("./db_scratch.mdb") & ";" ' We don't use these, but we could if we neeeded to. 'Const DB_USERNAME = "username" 'Const DB_PASSWORD = "password"

'Now we override the above settings to use our SQL server. 'Delete the following line to use the sample Access DB. DB_CONNECTIONSTRING = Application("SQLConnString") & "UID=" & Application("SQLUsername") & ";PWD=" & Application("SQLPassword") & ";"

' ADODB Constants ' You can find these in the adovbs.inc file ' Do a search for it and it should turn up somewhere on the server ' If you can't find it you can download our copy from here: ' http://www.asp101.com/samples/download/adovbs.inc ' It may not be the most recent copy so use it at your own risk. %>

<% ' End Constant Definition %>

<% Dim I ' Standard looping var Dim iRecordAdded ' Id of added record Dim iRecordCount ' Used only to keep a current count of records for DB Clean Up

'We're going to keep this as simple as we can. ' 1. Create a Recordset object ' 2. Connect the Recordset to the table ' 3. Add a new record to the Recordset ' 4. Set the values of the Recordset ' 5. Update the table ' 6. Close the Recordset

'Step 1: Dim objRecordset Set objRecordset = Server.CreateObject("ADODB.Recordset")

' The following syntax is also acceptable if you move it outside of the ' script delimiters. I prefer to Dim and then set it like any other ' variable, but it really doesn't make too big a difference.

'

'Step 2: ' The syntax for the open command is ' recordset.Open Source, ActiveConnection, CursorType, LockType, Options ' ' Source ' In this case it's our Table Name. It could also be a SQL statement, a ' command object, or a stored procedure. ' ActiveConnection ' We use a string which contains connection information. It could also ' be a connection object which is faster if you need to open multiple ' recordsets. ' CursorType ' Doesn't matter too much in this case since I'm not going to be doing ' much with the records. I'm opening it as a static so I can get a ' recordcount. ' LockType ' Specifies how the provider should lock the data. We'll use pessimistic ' so that it'll lock as soon as we start editing and basically ensure a ' successful update. ' Options ' Tells what type of source we're using if it's not a command object ' ' Most of the above are optional to some degree. It's usually better ' to set them so you know what their settings are. It'll avoid the ' defaults coming back to haunt you when you try and do something they ' don't allow.

' This is the way I normally would open this RS: objRecordset.Open "scratch", DB_CONNECTIONSTRING, adOpenStatic, adLockPessimistic, adCmdTable

' You could also do it step by step if you want: 'objRecordset.Source = "table_name" 'objRecordset.ActiveConnection = DB_CONNECTIONSTRING 'objRecordset.CursorType = adOpenStatic 'objRecordset.LockType = adLockPessimistic 'objRecordset.Open

'Step 3: ' To add a new record to the current recordset we naturally call the ' AddNew Method. objRecordset.AddNew

Response.Write vbTab & vbTab & "

integer_fielddate_time_field
" & objRecordset.Fields(I) & "
" & vbCrLf

Response.Write "Record id " & iRecordAdded & " added!"

'Now back to our regularly scheduled program!

'Step 6: ' Finally we close the recordset and release the memory used by the ' object variable by setting it to Nothing (a VBScript keyword) objRecordset.Close Set objRecordset = Nothing

' This is the end of the sample! '********************************

' Now this is REALLY behind the curtain!

' Normally I'd cut you off right here and do the rest behind the scenes; however, ' since this has to do with the DB you were just writing to, I'll give you a ' treat and let you see some of our administative / housekeeping code!

' Now we clean up! ' Basically, to keep things manageable, I'm checking the DB to keep it under ' a dozen or so records. If iRecordCount >= 12 Then Dim objCleanUpRS Set objCleanUpRS = Server.CreateObject("ADODB.Recordset")

objCleanUpRS.Open "scratch", DB_CONNECTIONSTRING, adOpenDynamic, adLockPessimistic, adCmdTable

For I = 1 to 10 objCleanUpRS.MoveFirst objCleanUpRS.Delete Next

objCleanUpRS.Close Set objCleanUpRS = Nothing End If %>

Sample HTML Code generated by the ASP:

'Const DB_USERNAME = "username" 'Const DB_PASSWORD = "password"

'Now we override the above settings to use our SQL server. 'Delete the following line to use the sample Access DB. DB_CONNECTIONSTRING = Application("SQLConnString") & "UID=" & Application("SQLUsername") & ";PWD=" & Application("SQLPassword") & ";"

' ADODB Constants ' You can find these in the adovbs.inc file ' Do a search for it and it should turn up somewhere on the server ' If you can't find it you can download our copy from here: ' http://www.asp101.com/samples/download/adovbs.inc ' It may not be the most recent copy so use it at your own risk. %>

<% ' End Constant Definition %>

Dim I ' Standard looping var Dim iRecordDeleted ' Id of deleted record Dim iRecordCount ' Used only to keep a current count of records for DB Clean Up

'We're going to keep this as simple as we can. ' 1. Create a Recordset object ' 2. Connect the Recordset to the table ' 3. Find the record to delete ' 4. Delete It! ' 5. Update the table ' 6. Close the Recordset

'Step 1: Dim objRecordset Set objRecordset = Server.CreateObject("ADODB.Recordset")

'Step 2: ' The syntax for the open command is ' recordset.Open Source, ActiveConnection, CursorType, LockType, Options objRecordset.Open "scratch", DB_CONNECTIONSTRING, adOpenStatic, adLockPessimistic, adCmdTable

'Step 3: ' Not really much to do here! ' We're looking to delete the oldest record from the current recordset. ' Since we add them in order, the first one is the one to delete.

' Note: If the data was a little more important (or of any value at all ' to us!), we'd probably check some other criteria or at least check to see ' if it's the oldest record in the recordset. Since it's not and we really

' don't care, here goes!

'Step 4: 'Get and store for later Administrative Clean Up iRecordCount = objRecordset.RecordCount

'Only delete if they press the delete link! If Request.QueryString("action") = "delete" Then If Not objRecordset.EOF Then objRecordset.MoveFirst iRecordDeleted = objRecordset.Fields("id") objRecordset.Delete adAffectCurrent ' You can also delete groups of records which satisfy the filter ' property setting if you're doing this in batch mode. For this ' situation we're just killing the one record so we don't bother. End If End If

'Step 5: ' We don't need to do the update unless we batch it like mentioned above! 'objRecordset.UpdateBatch

' I do this just to be sure we don't display the deleted record! ' It's really not needed. The records gone from the DB, but may still ' be hanging around in our RS. objRecordset.Requery

'Show Table ' Feel free to skip this area. (Ignore the man behind the curtain!) ' I'm just showing the RS so you have something to look at when ' you view the sample.

'Get and store for later Administrative Clean Up iRecordCount = objRecordset.RecordCount

Response.Write "<TABLE BORDER=""1"" CELLSPACING=""2"" CELLPADDING=""2"">" & vbCrLf Response.Write vbTab & "

" & vbCrLf Response.Write vbTab & vbTab & "" & vbCrLf Response.Write vbTab & vbTab & "" & vbCrLf Response.Write vbTab & vbTab & "" & vbCrLf Response.Write vbTab & vbTab & "" & vbCrLf Response.Write vbTab & "" & vbCrLf If Not objRecordset.EOF Then objRecordset.MoveFirst 'Show data Do While Not objRecordset.EOF Response.Write vbTab & "" & vbCrLf

id text_field integer_field date_time_field
132 Tuesday 19 1/19/99 7:56:35 PM
133 Tuesday 19 1/19/99 7:56:36 PM
134 Tuesday 19 1/19/99 7:56:37 PM
135 Tuesday 19 1/19/99 7:57:02 PM
136 Tuesday 19 1/19/99 8:04:36 PM
137 Tuesday 19 1/19/99 8:05:14 PM
idtext_fieldinteger_fielddate_time_field