Sunteți pe pagina 1din 40

Friday, April 01, 2011 2:21 PM

What is ASP? ASP stands for Active Server Pages. It is a server side technology which is used to display dynamic content on web pages. For example you could write code that would give your visitors different information, different images or even a totally different page depending on what browser version they are using. Below is an example of 2 links which both go to the same page "choice.ASP" but different backgrounds will be displayed depending on the link you click. Which do you prefer? blue red This is a very basic example. To learn what other things ASP comes in handy for have a look at our 'what can ASP do' tutorial. ASP in itself isn't a language it is more a technology developed by Microsoft. ASP can be used with various scripting languages such as Perl or JScript though we will use VBscript as it is the default scripting language. What do we mean by ASP is run server-side? Well, when you request a page with the extension .ASP the web server looks for and locates the page on its hard drive. When located it then executes the ASP script contained in the page and sends back to your browser a pure HTML page. This ensures that an ASP page will work with any browser. This is what we mean when we say its a server side technology. All the ASP code is processed first of all on the server before being sent back to be displayed by your browser. Have a look at the 'how ASP works' tutorial which includes diagrams for a more detailed explanation. ASP needs a Server ASP is short for Active Server Pages. As the name suggests once you request a page the request is sent off to another computer that acts as the server. The server can be a computer on the internet, or on a local intranet at your office. You can even use your own computer as a server! When you request a web page the server will locate the page and process the ASP code and then send the page back as a pure HTML page. If you haven't got a web server then you won't be able to see your ASP page. You cannot view an ASP page in the way you open a HTML page in your browser by clicking on file>open> and browsing to the page. The page must be run through a server. The two most popular servers are IIS and its 'little brother' PWS. If you are not running your ASP page on an external hosting company's server then have a look at my tutorial on 'installing ASP on your own PC'. If you do not want to run your ASP scripts on your own computer even for development purposes then I would suggest using Brinkster.com. It offers free web space where you can run your scripts. There are also excellent forums. So in summary ASP files must be processed by a server either IIS (Internet Information Services) or PWS (Personal Web Server). You can either install a server on your own machine or use your hosting company's. Text Editors and Software to Write ASP When you are writing ASP there are many environments where you can do your work. I use and recommend using Ultradev 4, other ones include Dreamweaver 2 and 3 and Visual Interdev (though these can be a little daunting for the beginner). There are many packages such as Interdev which will assist you in writing code. This may make ASP easier to write but I strongly suggest that you learn to write ASP yourself, in the long run this will make it easier for you to debug. Hand writing code will stand you in good stead and help you when you come to debug your code, so learn to use a text editor like notepad or wordpad and then move on to something that will speed up your coding. The first site I ever made took an enormous amout of time, I wrote it all in notepad. Once I had learnt
Unfiled Notes Page 1

your coding. The first site I ever made took an enormous amout of time, I wrote it all in notepad. Once I had learnt how to hand code I moved on to Dreamweaver. The same site to do now would probably take me a couple of weeks. Nevertheless I am still grateful that I used notepad and still have a soft spot for it! Just one point, look out for editors that munch your code. I found out that Dreamweaver couldn't cope with large amounts of ASP code but worked fine with a few lines. Frontpage doesn't have many backers so avoid it like the plague! I now use Dreamweaver MX. (Updated, I now use Dreamweaver 8) Below are some other text editors that you may wish to try out. TextPad http://www.textpad.com/ Ultraedit http://www.ultraedit.com/ Friday, April 01, 2011 9:21 AM Getting Started with OneNote Page 16 http://www.ultraedit.com/ CuteEditor http://www.cutesoft.net/ASP/ ASPExpress http://aspexpress.com/aspexpress.asp HapEdit http://hapedit.free.fr/ FCKEditor http://www.fckeditor.net/ Pasted from <http://www.codefixer.com/tutorials/editors.asp> ASP, What can it do? With ASP you can create online forms that once filled in and submitted can return the information to the site owner's email address. This can be great for feedback forms amongst other things. ASP makes it easy to access databases and present the results on your web site. Think of a search engine that finds all the records that match your keywords and then presents the results, sometimes with 10 results displayed on a page. You can create login and password protected sites, which come in handy if you would like to do a membership site or have a membership section on your site. Other things include creating customized pages that display only things that will be of interest to a particular user, display different pages for different browsers, or if you see yourself as an internet millionaire you can build an online shop. MembersPro PayPaland MembersProare both examples of ASP database driven membership applications. You can make polls. PollProis an example of ASP polling software. You can have pictures that display randomly (Look at the partner buttons on the left hand side. If you were to refresh this page, they should change.) You can display the date and time in various different formats. Note that the date on our page will change every day without the page having to be updated. You can keep track of things like the number of visitors or number of page hits. These are just some of the reasons that will make learning ASP worthwhile and fun. ASP offers loads of possibilities. Pasted from <http://www.codefixer.com/tutorials/what_can_it_do.asp>
Unfiled Notes Page 2

Pasted from <http://www.codefixer.com/tutorials/what_can_it_do.asp> How ASP works -ASP needs a server to process the code! When you incorporate ASP into your Web page, here's what happens: The internet user brings up a web page which has the the extension .asp. When the browser requests the ASP file from the web server, instead of processing the page like a normal .html or.htm page, the ASP is processed on the server. ASP processes the requested file from top to bottom, executing any script commands contained in the file, and produces pure 100% HTML code. The resultant HTML is then sent back to the brower for the user to view. Because your script runs on the server, the web server does all of the processing and standard HTML pages can be generated and sent back to the browser. The good news is that ASP pages are thus browser independent, so a web page with the .asp extension can be viewed by all browsers. Have a look at the diagrams below. They are pretty simplistic and self-explanatory. Getting Started with OneNote Page 17 Pasted from <http://www.codefixer.com/tutorials/how_asp_works.asp> Installing ASP on your own computer To run ASP on your computer you will need the Personal Web Server or Internet Information Services component installed on your machine. To Install PWS on Windows 95, 98 & Windows NT If you run Windows 95, Windows 98 or Windows NT 4.0 Workstation you can install Personal Web Server (PWS). PWS is a smaller scale little brother of Internet Information Services (IIS) though still fully functional. As Personal Web Server (PWS) is not shipped with Windows NT or with Windows 95 you will have to download "Windows NT 4.0 Option Pack" from Microsoft. To download the Windows NT Option Pack, see the following Microsoft Web site: Windows NT Option Pack http://www.microsoft.com/ntserver/nts/downloads/recommended/NT4OptPk and select the appropriate operating system. If you have Windows 98 there are two ways you can install PWS either from the Windows NT Option Pack or from the Windows 98 installation CD. If you have Windows 98 and decide to download from the net remember to choose Windows 95 as the operating system even if you're running windows 98. If you don't want what can be a long download (Over 30Mb) then you can install the PWS from the Windows 98 CD. To Install PWS from the Windows 98 CD First run the CD Rom and click on 'Browse This CD' Then double click on the folder 'add-ons' Then double click on 'PWS' Next click on the 'Setup.exe' and follow the steps to install Once you restart your machine you should see a new added icon for your PWS in the task bar. On installation an Inetpub folder should have been created on your harddrive with the sub folder wwwroot. To test that PWS is working. First of all to test PWS make sure that your web server is running. Check your task bar for the newly added PWS icon. Double click on it and press the 'Start' button if this isn't already on. Next type into your browser one of the following 3; a) http://localhost/ b) http://127.0.0.1 c) http://YourComputerName You should see some Microsoft information on PWS if it's working correctly. To Install IIS on Windows XP Professional Insert the Windows XP Professional CD-Rom into your CD-Rom Drive From your Start Button, go to Settings, and then Control Panel In the Control Panel window select Add/Remove Programs In the Add/Remove window select Add/Remove Windows Components In the Windows Component Wizard check Internet Information Services, click next and follow the onUnfiled Notes Page 3

In the Add/Remove window select Add/Remove Windows Components In the Windows Component Wizard check Internet Information Services, click next and follow the onscreen instructions. To test that IIS is working. First of all to test IIS make sure that your web server is running. Check your task bar for the newly added IIS icon. Double click on it and press the 'Start' button if this isn't already on. Next type into your browser one of the following 3; a) http://localhost/ b) http://127.0.0.1 c) http://YourComputerName You should see some Microsoft information on IIS if it's working correctly. Unfortunately, the XP Home edition doesn't have this capability and you'll have to upgrade to XP professional. [How to install ASP on Windows XP (Tutorial with images)] To Install IIS on Windows 2000 ASP version 3.0 is included with all versions of the Microsoft Windows 2000 operating system. Place the Getting Started with OneNote Page 18 ASP version 3.0 is included with all versions of the Microsoft Windows 2000 operating system. Place the Windows 2000 CD-Rom into your CD-Rom Drive. From your Start Button, go to Settings, and Control Panel In the Control Panel window select Add/Remove Programs In the Add/Remove window select Add/Remove Windows Components In the Windows Component Wizard check Internet Information Services, click next and follow the onscreen instructions. To test that IIS is working. First of all to test IIS make sure that your web server is running. Check your task bar for the newly added IIS icon. Double click on it and press the 'Start' button if this isn't already on. Next type into your browser one of the following 3; a) http://localhost/ b) http://127.0.0.1 c) http://YourComputerName You should see some Microsoft information on IIS if it's working correctly. Alternatively rather than install PWS or IIS on your computer you can rent web space from an ASP enabled host (some ASP hosts are free). Have a look at the tutorials main page for a list of free ASP hosts. I used and can recommend www.brinkster.com, its a great online ASP community, with a great forum. If you have Linux or another UNIX OS you can buy ChiliASP Pasted from <http://www.codefixer.com/tutorials/installation.asp> Operating systems that come with Internet Information Services or Personal Web Server Below is a list of Windows operating systems and the versions of IIS or PWSthat they support. Windows Operating System Version of IIS or PWS Windows 95, 98 Personal Web Server Windows NT 4 Server IIS 4.0 Windows NT 4 Workstation Personal Web Server Windows 2000 Professional IIS 5.0 (limited version) Windows 2000 Server (all versions) IIS 5.0 Windows XP Professional IIS 5.1 Windows Server 2003 IIS 6.0
Unfiled Notes Page 4

IIS 6.0 Pasted from <http://www.codefixer.com/tutorials/iis_pws_operating_systems.asp> How easy is ASP to learn? I have read and heard alot of people saying that learning ASP is easy. For me that's slightly off the mark. ASP might be easy to learn if you have come from another programming language or know a bit about computers, but for me all I had was a few months of HTML and little knowledge of computers. For those of you in the same position then it will be hard and frustrating. Nevertheless with hard work and perserverance you'll get there. Learn from forums, post and ask questions on forums. One forum I found particularly useful was www.brinkster.com. Keep your code and reuse it. You could even document your code in a folder. Use your favourites to keep a record of sites you found useful. Have a look at the sites that I recommend in 'link directory'. Try computer related chat rooms. Just a word of advice don't spend too much time in these rooms or even on the computer. Here are some tips that I would give. For those of you that know other programming languages, well yes no doubt ASP will seem like a breeze! Though maybe not for the rest of us. :-( Pasted from <http://www.codefixer.com/tutorials/how_easy.asp> Where do I save my ASP files? When you create an ASP page, you cannot view it by simply clicking on it or clicking file open on your browser and locating the file. Although this works for a HTML file this will not give the server the chance to parse any of the code in your ASP page. IIS or PWS on installation creates a folder on your hard drive that is by default called Inetpub. Under Inetpub there is another folder called wwwroot. The wwwroot folder is the root folder for your website. You can place your site (your folders and files) in here giving your web server access. By default the folders are placed on your C drive, C:\Inetpub\wwwroot. Save your files and folders here. Have a look at the page below. I created a folder called 'mysite' and placed it within the wwwroot folder (ie C:\inetpub\wwwroot\mysite). Next I created and placed a file in that folder called default.asp. I wrote the file with all the ASP and HTML, then went to my address bar and typed in http://localhost/mysite/default.ASPand hey Getting Started with OneNote Page 19 all the ASP and HTML, then went to my address bar and typed in http://localhost/mysite/default.ASPand hey presto! Example 1 shows the results. Example 1 The code for this example is; <%@ Language="VBScript" %> <html> <head> <title>hello page</title> </head> <body> <% response.write "hello, notice the url above http://localhost/mysite/default.asp" %> </body> </html> Remember that your PWS or IIS must be running and installed properly for this example to work. Related Tutorial 'ASP needs a Server' Related Tutorial 'Installing ASP on your own computer '
Unfiled Notes Page 5

Related Tutorial 'Installing ASP on your own computer ' Pasted from <http://www.codefixer.com/tutorials/where_to_put.asp> What is an ASP file? Your ASP file will invariably be a mixture of text, ASP, and HTML tags. Have a look at the code below. In black is the HTML, in red is the text and in blue is the ASP(VBscript) code. Just in case you haven't noticed ASP pages end with the file extension .asp as opposed to HTML files that have the .html or .htm extension. <html> <head> <title>What is an ASP file</title> </head> <body> <p>The time currently is<%= Time %><br> and the date is<%= Date %></p> </body> </html> An ASP file can also contain Javascript and XML. Read our related tutorial on 'How ASP works' Pasted from <http://www.codefixer.com/tutorials/asp_and_html.asp> ASP Comments -Comment Out Code in ASP Just to point out to those beginners that using an apostrophe at the start of a line or anywhere in a line of ASP code comments out that code. It will not be processed. The reason I am telling you this is that I spent many's an hour looking at other peoples code thinking what the f*** is that ' for. Commenting comes in handy because when you come back to look at your code whether 2 weeks or 3 months later, you invariably have difficulty reading and understanding it especially if it is complicated. So if its difficult for you, remember that commenting could also help others who have the misfortune of having to rewrite your code. <% 'This is a comment, below I will write out my name Getting Started with OneNote Page 20 'This is a comment, below I will write out my name response.write "Michael Wall" %> Or this <% response.write "Michael Wall" ' This will write out my name Michael Wall 'note that the apostrophe above didn't start on a new line and it doesn't have too %> You will also come across fancy ways that people write comments, they all just do the same thing. ie. the apostrophe is all that is needed. <% '###### This code Belongs to Michael Wall ########## '======Script Title HERE======= %> Pasted from <http://www.codefixer.com/tutorials/comments.asp> Test if your server supports ASP Copy the code below and paste it into a text editor such as notepad or wordpad. Save the file as 'test.asp'. Do Not save this with an .html or .htm or .txt file extension.With Notepad select "All Files" in the "Save as type" drop-down menu to avoid having your file renamed to test.asp.txt. Next simply FTP the file to your web server. Type the URL address into your browser, this will be a URL like http://www.yourwebsite.com/test.asp. If the page displays the current system date and time without any error messages then your server supports ASP. <%@ Language="VBScript" %> <html>
Unfiled Notes Page 6

<html> <head> <title>ASP Test Page</title> </head> <body> <% 'Display the current system date and time Response.write "Today's date and time is " & Now() %> </body> </html> Your page should look like the screenshot below. Pasted from <http://www.codefixer.com/tutorials/test_server_supports_asp.asp> Free ASP Hosts Below is a list of hosting companies that offer free ASP hosting. www.brinkster.com www.7host.com www.somee.com www.websamba.com www.maxipointservers.net www.1asphost.com www.aspspider.net www.coldplater.com-ColdPlater offers free subdomains with banner ad Getting Started with OneNote Page 21 Pasted from <http://www.codefixer.com/tutorials/free_asp_hosts.asp> Recommended ASP/ASP.NET Hosts Below is a list of recommended companies that offer ASP hosting. DiscountASP.NET 3 MONTHS FREE On Developer-Ready ASP/.NET Web Hosting -FREE ASP Components Including ASPJpeg, ASPEmail, and ASPUpload -MS SQL 2005/2000 with Real-Time Backups -SQL Restore and Shrink SQL DB Tools -FREE Automated Attach .MDF Tool -ASP.NET AJAX Support -FREE SETUP!! WebHost4Life.com Free 2gig of SQL2008 $9.95/mo special! Windows 2008 ASP.NET 3.5 SP1 & Ajax and more Dailyrazor.com 3 Months FREE Hosting. FREE Setup! FREE Domain Name! FREE Components! Up to 6 GB Disk Space! Up to 100 GB Bandwidth! Unlimited Web Apps! Multiple Domain Hosting! MS SQL, MS Access, MySQL Support! 30 Days Money Back Guarantee! 24/7 tech support! All starting at just $3.95/month! Pasted from <http://www.codefixer.com/tutorials/recommended_asp_hosts.asp> Getting Started with OneNote Page 22

Unfiled Notes Page 7

Friday, April 01, 2011 2:35 PM

Write 'Hello World' with your First ASP Script First lets use a text editor such as Notepad to write this script. Go to Start > Programs > Accessories > Notepad and copy the code in blue and the comments in green and paste them into notepad. Remember that anything after the ' is commented out and thus not processed. <%@ Language="VBscript" %> <% Dim I ' declare a variable I which will act as our loop counter variable ' Start the loop which will loop from 1 to 5 incrementing I by one each time For I = 1 To 5 ' FONT TAG's SIZE attribute will be determined by the value of I ' so on the first loop the font tag's size will be 1 and on the last loop it will be 5. %> <font size="<% response.write(I) %>">Hello World</font> <br> <% Next ' repeat the loop again only if it hasn't passed through 5 yet. %> To test this script on your own computer you should remember than when you installed PWS or IIS an 'Inetpub' folder should have been created on your harddrive with the sub folder 'wwwroot'. Locate this folder ie 'wwwroot' and inside it create a new folder called 'ASP'. Save the file as Helloworld.asp in your C:\inetpub\wwwroot\ASP folder (you may need to change the drive letter if Inetpub is not on your C drive). Next open your browser and type http://localhost/asp/helloworld.aspin the address/url box and hit enter. You should see the output below provided you have PWS or IIS installed correctly. If you are not running the script on your own local computer but on your hosting company's web space then just simply save the file, upload and run the script. Related Tutorial 'Looping' (The For Next loop explained in more detail) Related Tutorial 'Installing ASP on your own computer' Pasted from <http://www.codefixer.com/tutorials/first_script.asp> ASP/VBScript delimiters ASP code is opened and closed with the use of delimiters. When you are going to write ASP code use the opening tag <% and when you have finished writing your code use the closing tag %> Note for our purposes it isn't important that you understand the following code example: <% If request.form("name") <>"michael" then response.write "your name is not michael" End if %> the delimiters do not need to be on the same line, the following code is the same as the above <% If request.form("name") <>"michael" then response.write "your name is not michael" End if %> To print out code use <%= or response.write <%= "michael" %> or <% response.write "michael" %> You will notice a similarity between the use of these delimiters and the opening < and > closing tags in HTML, Friday, April 01, 2011 9:29 AM
Unfiled Notes Page 8

9:29 AM Getting Started with OneNote Page 23 You will notice a similarity between the use of these delimiters and the opening < and > closing tags in HTML, well atleast I hope you do! :-) Pasted from <http://www.codefixer.com/tutorials/delimiters.asp> Parsing strings in ASP using VBscript functions First of all a string is a group of characters. These characters can be letters, numbers or even special characters like the exclamation mark or the ampersand. This group of characters encapsulated within quotations are stored in a variable. Our example code below sets our variable myString equal to the string of characters "Good day!" <% 'Declare variable Dim myString myString ="Good day!" %> Using some of the VBScript functions below we can manipulate and work with the strings that variables hold. InStr function Left and Right functions Len function Replace function LCase and UCase functions Mid function Trim LTrim and RTrim functions Learn how to Concatenate Strings Pasted from <http://www.codefixer.com/tutorials/parsing_strings.asp> If Then Else Statements The If Then control structure can be used to run a line or block of code within your script when a certain condition is met. Below are 4 ways to use the If Then control structure. 1) syntax: If Condition Then statement End If Example 1: <% Dim A, B ' declare our variables A=2 B=2 If A=B Then response.write "A is equal to B" End If %> What we have done in example 1 is declared 2 variables A and B and assigned them values. We have used the If Then control structure and if our Condition ie A=B is true then the text A is equal to B will be written out. As is obvious 2 is equal to 2 so the condition is true and our text is written. In our example 1 what would have happened if B had equalled 3. The condition would not have been true. To accomodate this scenario you could introduce the optional Else clause as in the syntax below. 2) syntax: If Condition Then statement Else statement End If Example 2:
Unfiled Notes Page 9

Example 2: <% Dim A, B ' declare our variables A=2 B=3 If A=B Then response.write "A is equal to B" Else response.write "A is not equal to B" End If %> In example 2 we have declared 2 variables A and B and assigned them values. As our Condition ie A=B is false our Else clause comes into play and the text A is not equal to B will be written out. Let's now introduce the Elseif clause. 3) syntax: If Condition1 Then statement ElseIf Condition2 Then Getting Started with OneNote Page 24 ElseIf Condition2 Then statement ElseIf Condition3 Then statement Else statement End If Example 3: <% Dim A, B, C, D ' declare our variables A=2 B=3 C=4 D=5 If A=B Then response.write "A is equal to B" ElseIf A=C response.write "A is equal to C" ElseIf A=D response.write "A is equal to D" Else response.write "A doesn't equal any of them" End If %> In our example 3 we introduce the ElseIf clause which lets us test a series of conditions. If one of the conditions is met (true) then its statement will be executed. As in example 3 none of the conditions are met so our 'catchall' using the Else clause comes into play. This will write out A doesn't equal any of them. 4) syntax: If Condition Then Statement Example 4: <% Dim A, B ' declare our variables A=2 B=2 If A=B Then Response.write "A is equal to B"
Unfiled Notes Page 10

If A=B Then Response.write "A is equal to B" %> In Example 4 we can leave out the End If clause if we only have one statement to perform and you don't want to run any statement at all if the condition is false. It's similar to example 1 though there is no End if and the code is written on the one line. Rather than use ElseIf in example 3 many programmers will choose to use 'Select Case' if there are alot of options. Read more about Select Case. Pasted from <http://www.codefixer.com/tutorials/If_then_else.asp> Select Case Select Case does a similar job to If..Then..Else.. Below is an example using a variable called Name. Depending on whether Name equals Michael, Gavan, Fred or none of these names a different line of code is run. <% SELECT CASE Name Case Michael Response.write Name is Michael Case Fred Response.write Name is Fred Case Gavan Response.write Name is Gavan 'It is possible that none of the case statements equal the value of variable Name 'so in this scenario -use Case Else Case Else Response.write "The name is something else" END SELECT %> The above example applies to text. The example below applies to a number. <% SELECT CASE Number Case 1 Response.write Number is equal to 1 Case 2 Response.write Number is equal to 2 Case 3 Getting Started with OneNote Page 25 Case 3 Response.write Number is equal to 3 'It is possible that none of the case statements equal the value of variable Number 'so in this scenario -use Case Else Case Else Response.write "The number is not equal to any of the values above " END SELECT %> (Read the second part of this tutorial that will introduce posting form variables and provide a slightly more complicated example select case.) Pasted from <http://www.codefixer.com/tutorials/select_case.asp> Sending Form Values to an email Copy the 2 pages below and paste them into the same folder and then run form.html on your webserver (this won't work on your personal webserver, must be an internet server and support the CDONTS mail object). If you fill in the text boxes on the form.html page and click submit then the values entered will be sent to form_ac.asp. Form_ac.asp will be the page that will receive and process the values entered into the text boxes. In our example once the variables have been received by form_ac.asp an email will then be sent which holds the variables. The comments in the pages should explain the code.
Unfiled Notes Page 11

holds the variables. The comments in the pages should explain the code. Call this page form.html <html> <head> <title>form to email script</title> </head> <body> <div align="center"> <form method="POST" action="form_ac.asp" name="form1"> <table width="75%" border="0" cellspacing="0" cellpadding="0"> <tr> <td>name:</td> <td colspan="2"> <input type="text" name="name"> </td> </tr> <tr> <td>email:</td> <td colspan="2"> <input type="text" name="email"> </td> </tr> <tr> <td>message:</td> <td colspan="2"> <textarea name="message" cols="40" rows="5"></textarea> </td> </tr> <tr> <td>&nbsp;</td> <td colspan="2"> <input type="submit" name="Submit" value="Submit"> <input type="reset" name="Reset" value="Reset"> </td> </tr> </table> </form> </div> </body> </html> Call this page form_ac.asp (the ac is short for acquire as it will be receiving values) <%@ Language="VBscript" %> <% Option Explicit %> <html> <head> <title>Message Sent</title> </head> <body> Getting Started with OneNote Page 26 <body> <% 'declare the variables that will receive the values 'receive the values sent from the form and assign them to variables 'note that request.form("name") will receive the value entered into the textfield 'called name, and so with email and message
Unfiled Notes Page 12

'note that request.form("name") will receive the value entered into the textfield 'called name, and so with email and message Dim name, email, message, NewMailObj name=request.form("name") email=request.form("email") message=request.form("message") 'create the mail object and send the details Set NewMailObj=Server.CreateObject("CDONTS.NewMail") NewMailObj.From = "michael@codefixer.com" NewMailObj.To = "whoever_you_want_to_send_it_to@hotmail.com" NewMailObj.Subject = "New message sent.." NewMailObj.Body = "the name you entered was " & name & _ "<br>the email was " & email & _ "<br>the message was " & message 'you need to add the following lines FOR the mail to be sent in HTML format NewMailObj.BodyFormat = 0 NewMailObj.MailFormat = 0 NewMailObj.Send 'Close the email object and free up resources Set NewMailObj = nothing Response.write "The email was sent." %> </body> </html> You may be interested in reading our tutorial 'Insert form content into a database' Learn how to text format an email Pasted from <http://www.codefixer.com/tutorials/sample_form_email_script.asp> Pass Hidden form values in ASP Below highlighted in red is what the HTML for a hidden form value looks like. As you can see it's almost the same as the HTML form textbox below it. The major difference is that the hidden form value isn't visible to the user. <input type="hidden" name="hasdonelogin" value="true"> <input type="text" name="textfield" value=""> Using a hidden form value comes in handy for such things as logins, where you have a username and password textbox. If the forms action is to send its values to the same page (ie self referencing) then by using a hidden form value you can monitor whether the user has clicked on the submit button and thus filled in the form. If it is the first time a user has accessed your page, hasdonelogin will have no value, it will be empty. If they have just submitted your form, hasdonelogin will have a value of true, and in that scenario you don't need to show the login form again with the username and password textfields. <% 'If the hasdonelogin form value equals nothing the form has not been submitted If Request.Form("hasdonelogin")="" Then 'make sure the username and password textboxes are displayed %> <form name="form1" method="post" action=""> <input type="hidden" name="hasdonelogin" value="true"> <input type="text" name="username" value=""><br> <input type="text" name="password" value=""><br> <input name="submit" type="submit" value="submit"> </form> <% Else'run this code if hasdonelogin has a value of true 'don't show the username and password textboxes response.write "You clicked on the form and the hidden value has been sent" End If
Unfiled Notes Page 13

End If %> Have a look at the tutorial ASP Password Protectfor a more detailed explanation and example. Pasted from <http://www.codefixer.com/tutorials/hidden_form_values.asp> Option Explicit When writing your ASP pages, there is one very important step many developers unfortunately forget to do or Getting Started with OneNote Page 27 When writing your ASP pages, there is one very important step many developers unfortunately forget to do or in some cases are too lazy to do. Always put the effort in and avoid writing sloppy code, use Option Explicit. Option Explicit requires that all variable names be declared (with the Dim statement). Using Option Explicit to force variable declaration is good for a number of reasons. First, let's look at this code example: <% MyName = "michael" Response.Write(MyNam) %> As I have mispelt MyName and written MyNam nothing will be printed out, ASP will create a new variable MyNam and assign an empty string to it. If your code is long then finding this typing mistake can take you hours.Trust me!! <% Option Explicit 'Always, always, always! 'declare your variables Dim MyName MyNam = "Michael" Response.Write(MyName) %> Note that If you write the code in the style above using Option Explicit you will get an ASP error informing you that MyNam is undefined. You must first use the Dim statement. Debugging becomes alot easier! Below is a section of code with an example of a spelling mistake. We have declared our variables but unfortunately mispelled one of our variables ie MyNam. Using Option Explicit the undefined variable will be picked up and the error message 'Variable is undefined' will be displayed. This can truely save you an awful lot of time when debugging your code. Just note that the Option Explicit must come before any HTML code. <%@ Language="VBScript" %> <% Option Explicit %> <html> <head> <title>Using Option Explicit</title> </head> <body> <% 'declare your variables dim MyName, MyAddress, MyfootballTeam MyNam= "michael" Response.Write(MyName) MyAddress = "16 Marki Street" Response.Write(MyAddress) MyfootballTeam ="Spurs" Response.Write(MyfootballTeam) %> </body> </html>
Unfiled Notes Page 14

</body> </html> The above code will produce this error message. Getting Started with OneNote Page 28 To sum up, using Option Explicit forces you to declare all your variables before you use them. If you use a variable you haven't declared then an error will be generated much like the one in the example above. Read our related tutorial on 'Variables' Pasted from <http://www.codefixer.com/tutorials/option_explicit.asp> Server Variables Sometimes you might want to find out more information on your visitors. We can do this using the server variables. These are environment variables that tell us about the environment that your application is running in. Server variables can tell us everything from what browser the visitor is using, to the visitor's ip address, or the last page the visitor came from. For example I can tell that you are using the Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; BRI/2) browser, and the IP (Internet Protocol) address of your internet connection is 113.199.217.144 Server Variables can be called with the following syntax; <% Request.ServerVariables("Variable Name") %> Below are a list of some of the more common server variables and how you use them: This tells us the page the visitor came from <% = Request.ServerVariables("HTTP_REFERER") %> The last page you came from:http://www.codefixer.com/tutorials/ This is a simple way to display a go back link on a page get a visitors IP address <% =Request.ServerVariables("REMOTE_ADDR")%> Your IP address is:113.199.217.144 Find host name of client <%=Request.ServerVariables("REMOTE_HOST")%> The result:113.199.217.144 Find the server domain name <% =Request.ServerVariables("SERVER_NAME")%> Server domain name is:www.codefixer.com This returns the software running on the server <% Request.ServerVariables("SERVER_SOFTWARE")%> The Server software is:Microsoft-IIS/7.5 Getting Started with OneNote Page 29 Display the virtual path to the script or application being executed <% =Request.ServerVariables("SCRIPT_NAME") %> The result:/tutorials/servervariables.asp Find out what browsers / Operating System a user has Display users browser and opertaing system <% = Request.ServerVariables("HTTP_USER_AGENT") %> Your browser is:Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; BRI/2) To get a list of all the ServerVariables you can simply copy paste and run this script. <% For each item in Request.Servervariables tempvalue=Request.Servervariables(item) Response.write item & "=" & tempvalue Response.write "<br>" Next %> Here's an example of using one of the ServerVariables to create a self referencing form Pasted from <http://www.codefixer.com/tutorials/servervariables.asp> How to Stop an ASP page caching Put this near the top of your script. <% Response.Expires = 0 Response.Expiresabsolute = Now() -1 Response.AddHeader "pragma","no-cache"
Unfiled Notes Page 15

Response.Expiresabsolute = Now() -1 Response.AddHeader "pragma","no-cache" Response.AddHeader "cache-control","private" Response.CacheControl = "no-cache" %> Or if thats too long winded then <% Response.Expires = -1000 %> Pasted from <http://www.codefixer.com/tutorials/stop_caching.asp> SQL explained: What is SQL| Select Statement| Select Where| Insert| Update/Edit| Delete| Order By| Select Between What is SQL? SQL is a language used to talk to and communicate with most databases. You can use SQL to access, define, delete and edit the data in a database system like Oracle, Microsoft SQL Server, Access and others. A database is a collection of data stored in an organised fashion. The data is usually stored in structured tables. Tables contain Columns and Rows of data. Diagram 1 illustrates an example of a Table called "Members_tbl". Diagram 1 FirstName, LastName, Address, and City are table Columns. The Rows contain 3 records with personal details about 3 people. As you can gather from the table above Henry lives in the lovely city of 'Dublin', and Dave's address is '32 Donki Park'. SQL is an important part of using ASP. We use SQL to determine what records we retrieve or manipulate from the database. Pasted from <http://www.codefixer.com/sql/tutorials/what_is_sql.asp> The Apostrophe Bug In an SQL statement text is enclosed by an apostrophe at the start and an apostrophe at the end. Consider the SQL Insert statement below. INSERT INTO TableName(TableFieldName) VALUES ('Hi folks, I'm a developer') On the face of it this looks a perfectly formed SQL statement. Look more closely and you'll notice the apostrophe in I'm. SQL will interpret this as the end of the string. When it encounters the following text and another ' an error will occur. To allow an apostrophe mark to be inserted into a database, simply double-up all occurences of the apostrophe mark. SQL will see two apostrophes together and treat them as a single apostrophe and at the same time realise that this doesn't signify the end of the string. Below our example uses the Replace function to search the variable MyVariable for all occurrences of the Getting Started with OneNote Page 30 Below our example uses the Replace function to search the variable MyVariable for all occurrences of the apostrophe. If it finds a single apostrophe it will double it up. <% Dim MyVariable MyVariable="My name is Michael, I'm a developer" MyVariable =Replace(MyVariable,"'","''") 'its hard to read this so " ' " , " ' ' " %> So once you have doubled up the apostrophe you could use the value of MyVariable in an SQL statement such as the following without producing an error message. <% Dim MyVariable, SQL MyVariable="My name is Michael, I'm a developer" MyVariable =Replace(MyVariable,"'","''") SQL = "INSERT INTO TableName(TablefieldName) VALUES ('" & MyVariable & "')" 'you could then add code here to open a connection to your database and execute 'the SQL statement. %>
Unfiled Notes Page 16

%> Here's a common scenario. Suppose you create a form with a textbox called Message that visitors can enter text into. When your visitor enters text you want your code that will receive the text and store in your database to be able to handle an apostrophe. The solution is to receive the textbox value and assign to a variable and then use the Replace function to double-up all apostrophes. This is demonstrated in our code below. <% Dim MyVariable, SQL MyVariable=Request.Form("Message") MyVariable =Replace(MyVariable,"'","''") SQL = "INSERT INTO TableName(TablefieldName) VALUES ('" & MyVariable & "')" 'you could then add code here to open a connection to your database and execute 'the SQL statement %> Pasted from <http://www.codefixer.com/tutorials/apostrophe.asp> Variables in ASP (VBScript) A variable acts as a container holding or storing a value in the server computer's memory. We can then use or change the value of the variable throughout our code. Thus we could create a variable myFavouriteTeam that holds my favourite football team namely 'Spurs' and print out the value of the variable on our page. Note that to declare a variable in ASP/VBScript we use the Dim statement. Example <% Option Explicit 'declare your variable Dim myFavouriteTeam 'assign a value to our variable myFavouriteTeam="Spurs" 'the above variable myFavouriteTeam holds the value Spurs response.write myFavouriteTeam 'the output will be Spurs %> In ASP/VBScript there is only one datatype, and that is variant. A variant can hold either strings or numbers, and will act as a number if its numeric, and as a string for string values. In ASP/VBScript, it is not necessary to declare your variables before using them though it is good practice. You must use the Dim statement to declare variables as shown in the example below. You should also have a look at the Option Explicittutorial which relates to variable declaration. Here is an example where we assign a value to a couple of variables and then use them in the script. <%@ Language="VBScript" %> <% Option Explicit %> <% 'Commented lines starting with an apostrophe are not executed 'Declare your variables Dim temperature, country temperature=28 country="Ireland" response.write "The temperature is " & temperature & " in " & country %> The output is: The temperature is 28 in Ireland The variable value will be kept in memory for the life span of the current page and will be released from memory when the page has finished executing. In naming variables in VBScript you must be aware of these rules; Getting Started with OneNote Page 31 Variables must begin with a letter not an underscore or a number
Unfiled Notes Page 17

Variables must begin with a letter not an underscore or a number They cannot have more than 255 characters They cannot contain a period (full stop) , a space or a dash You can use an underscore though not as the first character If you use VBscript then case sensitivity is not important. 9variable 'is not a valid variable name as it begins with a number _variable 'is not a valid variable name as it begins with an underscore variable.'is not a valid variable as there is a period (full stop) variable'both these variables in red are the same when using VBscript VARIABLE If the name of your variable breaks the rules then you'll encounter a fairly obvious error message like the one below. Also note in the case above that Strings require quotes and numeric values don't. With the example above you can see that tempature=28 doesn't have quotes whereas country="Ireland" does. Read our related tutorial on Variables and Constants Pasted from <http://www.codefixer.com/tutorials/variable.asp> Read and write Cookies A cookie is a small text file written to the visitors hard drive that stores user specific information. (Sometimes known as a persistent cookie) Why use cookies? Amongst other things Cookies are used to store information about a user, to store usernames and passwords, visited pages, favourites, last visits etc. They allow us to personalize web pages. How to write a cookie To write the cookie to the visitors computer we use the Response.Cookies command. syntax:Response.Cookies(CookieName)=value How to retrieve a cookie The "Request.Cookies" command is used to retrieve a cookie value syntax:Request.Cookies(CookieName) Thats all very basic, Heres an example of how this website uses a cookie. If you vote in our poll a cookie is written to your computer that stores the poll ID. Our cookie also has an attribute, in this case a date when the cookie will expire. It's 60 days from now. <% 'Lets assume for our example that the current poll ID is 19 and assign the value to intPollID intPollID=19 Response.Cookies("PollId")=intPollID Response.Cookies("PollId").Expires=Now+60 %> So this snippet of code above will write a cookie to our visitor's computer if they vote in our poll. IntPollID is a variable that will have been assigned a poll ID value. In this case 19. How do we retrieve a cookie which will let us know if the visitor has already voted in the current poll when they return to this page? Below is our code which will let us check if the visitor has already voted in this poll. <% IntPollID= 19 'Again Lets say for argument sake the current Poll ID is 19 'Check value of the PollID cookie on visitors computer '& assign it's value to our variable intVoteCastAlready intVoteCastAlready= Request.Cookies("PollID") 'Check if intVoteCastAlready equals IntPollID If Cint(intVoteCastAlready)=Cint(IntPollID) Then Response.write "You have already voted in this current poll" Else
Unfiled Notes Page 18

Response.write "You have already voted in this current poll" Else 'you could run code to show poll and let visitor pick an option End If %> Getting Started with OneNote Page 32 %> What this code is doing is retrieving the current poll ID and storing it in a variable IntPollID, which in the code above is 19. We then try and retrieve the PollID cookie and assign it to the variable intVoteCastAlready. If intVoteCastAlready equals IntPollID then the visitor has already voted in this current poll and we can run code that won't show any poll options just the results for the pole. This will bar the visitor from voting more than once. Vote in our pole and you'll see how this works in practice. If you do not set the Expires attribute like the example below sets it, the cookie will expire when the user closes their browser. <% Response.Cookies(cookieName)="This cookie will last for a year" Response.Cookies(cookieName).Expires = Now() + 365 %> Note: The Response.Cookies command must appear BEFORE the <html> tag or if it doesn't you must use <% response.buffer = true %>at the top of your page. Here's an example of using cookies to see if our visitor has been before. Another example of using cookies would be a login script. If a user has entered the correct username and password and ticked the 'remember me' checkbox then you could store these in cookies. The next time the visitor came to the login page you could automatically fill in the username and password textboxes with the correct details so that all the visitor would have to do was click the 'submit' button to login. Here's this scenario in practice. A downside of cookies is that not everyone allows cookies to be written to their computer so just be wary of using them to store critical information and don't let your application be over reliant on them. Learn how to store mulitple values in a cookie with our 'Cookies with Keys' tutorial. Pasted from <http://www.codefixer.com/tutorials/cookies.asp> Session Variables in ASP Session variables are stored in the server's computers memory. They are deleted once the visitor closes his browser or after a period of inactivity, usually 20 minutes by default. Below is the syntax for creating a session variable and assigning a value to it. syntax:Session(SessionName)=value Why use session variables? Session variables come in very handy for tracking purposes. Some e-commerce sites use session variables to store items in memory that have been placed into a shopping basket. Heres another example of how to use session variables. The comments in green should explain what the code is trying to achieve. <% 'In this example we are retrieving the username and password that a visitor 'enters into the username and password text boxes Username=Request.Form("Username") Password=Request.Form("Password") If Username="MyAdminUserName" AND Password="MyAdminPassword" Then 'If the visitor has logged in using the correct Admistrator details 'we know it's the administrator logging in and set BlnAdminLoggedIn to true Session("BlnAdminLoggedIn")=True End If %> Now If we wanted to create secure pages that only admin could access we could place the code in Example 1 at the top of newly created pages. This would check to see if the visitor has logged in properly with the admin username and password because if they have the Session("BlnAdminLoggedIn") will hold a value of true in their computers memory. If not then redirect the visitor to another page called
Unfiled Notes Page 19

a value of true in their computers memory. If not then redirect the visitor to another page called 'noaccess.asp'. Example 1: <% If Session("BlnAdminLoggedIn") <>True Then reponse.redirect "noaccess.asp" End If %> Pasted from <http://www.codefixer.com/tutorials/session_variables.asp> Getting the number of Active Users on your Website with ASP This is a neat little script that will tell you how many active users you have on your site. It can be somewhat disheartening if you don't get any though! What is required is somewhere to store the number of people which will be a variable i.e. amount of people on your site will vary. You will need to create a separate file in which to store this variable. For this purpose we use the global.asa. I am not going to go into too much detail about this file other than to tell you to cut and paste the code below into the file called global.asa <script language="vbscript" runat="server"> Sub Application_OnStart Getting Started with OneNote Page 33 Sub Application_OnStart Application("Active")=0 End Sub Sub Application_OnEnd 'no code is needed here End Sub Sub Session_OnStart Session.Timeout=20 Session("Start")=Now Application.Lock Application("Active")=Application("Active")+1 'this adds 1 to the number of active users when a new user hits Application.unlock End Sub Sub Session_OnEnd Application.Lock Application("Active")=Application("Active")-1 'this subtracts 1 from the number of active users when a new user leaves Application.unlock End Sub </script> The above is your global.asa file, below the code that you should cut and paste into another file. You can call the file whatever you like, though I'll call it 'active_users.asp' <html> <head> <title>active users</title> </head> <body> You are one of <%= Application("Active")%> current users. </body> </html> Upload both files on to the net making sure that the 'global.asa' is in the root directory. Run the file 'active_users.asp' and you'll discover how many active users you have. Pasted from <http://www.codefixer.com/tutorials/current_users.asp> Password Protect your pages using ASP Download the code
Unfiled Notes Page 20

Download the code Have a look at the code for 'login.asp' and then I'll talk you through it. Points to note are that we will be using 2 subroutines, CheckLoginForm and ShowloginForm, and that once the form details are submitted they are sent to the same page to be checked and processed. You could send the form details to another page to be checked and processed but why use an extra page! The code below is for a simple login that checks for a single username and password. In the following code the username and password are 'mic' and 'pass'. The 'submit' form button called 'submit' will play an important part in in letting us track whether the form has been submitted. If the form has been submitted then we can use the Request.Form command to collect the values entered in the form textfields and importantly the value sent in the form button 'submit'. Code for 'login.asp' <% Response.Expires = -1000 'Make sure the browser doesn't cache this page Response.Buffer = True 'enables our response.redirect to work %> <html> <head><title>Password Protect your ASP pages</title> </head> <body> <% If Request.Form("submit") ="Login" Then CheckLoginForm Else ShowLoginForm End If Getting Started with OneNote Page 34 End If %> <% Sub CheckLoginForm 'check if the value of the text field 'username' and 'password' are correct If Request.Form("username") = "mic" AND Request.Form("password") = "pass" Then Session("BlnLoggedIn") = True Response.Redirect "memberspage.asp" Else 'if the values entered are incorrect then display the message below Response.Write "<div align='center'>You are not logged in.</div><br>" ShowLoginForm End If End Sub %> <% Sub ShowLoginForm %> <div align='center'> <!--start the HTML login form --> <form name="form" action="login.asp" method="post"> <table> <tr><td>User Name :</td><td><input type="text" name="username"></td></tr> <tr><td>Password : </td><td><input type="password" name="password"></td></tr> <tr><td colspan="2"><input type="submit" name="submit" value="Login"></td></tr> </table> </form> <!--end the HTML login form --> </div> <% End Sub%>
Unfiled Notes Page 21

</div> <% End Sub%> </body> </html> Now lets break down the code into a series of blocks. <% Response.Expires = -1000 'Make sure the browser doesnt cache this page Response.Buffer = True 'enables our response.redirect to work If Request.Form("submit") ="Login" Then ' check if the value Login has been sent CheckLoginForm ' calls the subroutine checkloginform if Submit is equal to Login Else ShowLoginForm ' call the subroutine showloginform if Submit isn't equal to Login End If %> This block of code at the top of the page checks to see if the submit button has been clicked. If request.form("submit")="Login" then the value Login has been passed and we know that the visitor has clicked and submitted the form. In this scenario the subroutine CheckLoginForm is called and its code executed. CheckLoginForm will check to see if the username and password equal the values the visitor has entered. If they are correct then a Session variable 'BlnLoggedIn' will be created and set to True and the visitor will then be redirected to the 'memberspage.asp' <% Sub CheckLoginForm 'check if the value of the text field 'username' and 'password' are correct If Request.Form("username") = "mic" AND Request.Form("password") = "pass" Then Session("BlnLoggedIn") = True Response.Redirect "memberspage.asp" Else Response.Write "<div align='center'>You are not logged in.</div><br>" ShowLoginForm 'call the sub showloginform and display the login form again End If End Sub %> If the visitor has not clicked the submit button then no value will be passed i.e. request.form("submit") will not equal Login and in that case the subroutine ShowLoginFrom will be called. <% Sub ShowLoginForm %> <div align='center'> <!--start the HTML login form --> <form name="form" action="login.asp" method="post"> <table> <tr><td>User Name :</td><td><input type="text" name="username"></td></tr> <tr><td>Password : </td><td><input type="password" name="password"></td></tr> <tr><td colspan="2"><input type="submit" name="submit" value="Login"></td></tr> </table> Getting Started with OneNote Page 35 </table> </form> <!--end the HTML login form --> </div> <% End Sub%> The subroutine code above simply creates a form. The image below shows how the form will look on your screen. I have entered the login details in the screenshot below. PASSWORD PROTECT OTHER PAGES If you want to password protect any other pages then you can simply add the following code at the top of the pages. So for all the other pages if the Session variable 'BlnLoggedIn' is not equal to True then the visitor will be redirected to the login page. We could put this code at the top of our new members page
Unfiled Notes Page 22

visitor will be redirected to the login page. We could put this code at the top of our new members page 'memberspage.asp' which can only be accessed if the visitor has logged in correctly. Code for 'memberspage.asp' <% If Session("BlnLoggedIn") <> True Then Response.Redirect("login.asp") End If %> <html> <head><title>Members Secure Homepage</title> </head> <body> Welcome to the secure member's page. </body> </html> If you need multiple users with different usernames and passwords then you could use a database to store all the users and query that database when the visitor logs in to check if they supplied a matching username and password, if they did then you could simply create a session variable as above and protect the pages in the same way. Read our tutorial on Subroutines and Functions Plug and play Membership script. Recurring subscriptions or one time payment. Up to 3 levels of membership subscription. Easy set up and admin with free installation. Works with PayPal. Receive updates and add-ons for 2 years. 1st class support and customization available. Can be customized to support more levels. Saves you hours and hours of development time and money. PURCHASE YOUR COPY TODAY MembersPro PayPal -Membership Script Pasted from <http://www.codefixer.com/tutorials/password_protect.asp> Rotating Banner Management System ASP comes with a ready to use 'Ad Rotator' component. We can use this to create a rotating banner management system. All we need are the following 3 files. Call this file banner_ad.asp The purpose of this file is to display the random advertisement. <% 'declare your variables dim varad, objAd Getting Started with OneNote Page 36 dim varad, objAd 'create an instance of the Rotator object and assign variable Set objAd = Server.CreateObject("MSWC.AdRotator") 'make sure the page will open up in a new browser
Unfiled Notes Page 23

'make sure the page will open up in a new browser objAd.TargetFrame="TARGET=_BLANK" 'call the GetAdvertisement method and assign all details to variable varAd = objAd.GetAdvertisement("adrotator.txt") 'display the banner and its details Response.Write varAd %> Call this next file redirect.asp Once the user clicks on one of the banners an associated url is sent through the querystring to this page. This file will then redirect the user to the url passed. <% response.redirect Request.querystring("url") %> The third file is Adrotator.txt As you can see from the file extension this is a text file which we can break down into 2 parts. The first part holds general information with 4 parameters, namely the width of the borders, the height and width of the banners and the page that will act as the redirection page ( the page that will be sent the url through the querystring ). In our case this will be redirect.asp which is in the same folder. Next we have a * which separates the parts. Dont forget it. In part2 we have the image source, this can be relative or absolute, the url to be sent to when the user clicks the url, the alternate text and the frequency of the advertisement in terms of percentage. Just note that below the url's may be the same, though for your purposes you can simply change them. REDIRECT redirect.asp border 0 height 60 width 468 * http://www.codefixer.com/advertising/BANNER1.gif http://www.codefixer.com Resources and Tutorials for the ASP developer 40 http://www.codefixer.com/advertising/BANNER2.gif http://www.codefixer.com The best ASP site on the net 50 http://www.codefixer.com/advertising/BANNER3.gif http://www.codefixer.com ASP for the beginner to intermediate ASP developer 10 You could use an include file to call banner_ad.asp Make sure the folder advertising is in the root web directory of your site when you call the file, you can then include this in any file on your site. <!--#include virtual="/advertising/banner_ad.asp"--> Download the source files -advertising.zip Here's a tip on improving this system click here. Pasted from <http://www.codefixer.com/tutorials/adrotator.asp> Generate a Random Number The Rnd function returns a value less than 1 but greater than or equal to 0. Note that to use the Rnd function properly you must place the Randomize statement somewhere before it to ensure that a new random number is generated each time the page is reloaded. Have a look at the following code in Example 1. Example 1; <% Dim MyRandomNum
Unfiled Notes Page 24

Dim MyRandomNum Randomize MyRandomNum = Rnd Response.Write MyRandomNum %> The above code will produce a different number each time. Below are typical numbers produced. 0.9923431 0.2924431 Example 2 below shows the code to create a number between 1-100. Example 2; <% Dim MyNewRandomNum Randomize MyNewRandomNum = (Rnd * 100)+1 Getting Started with OneNote Page 37 MyNewRandomNum = (Rnd * 100)+1 response.write MyNewRandomNum %> The code above will produce a number such as 55.9393933 To get rid of the decimals we can use the Int function as in example 3 below. Example 3; <% Dim MyNewRandomNum Randomize MyNewRandomNum = Int(Rnd * 100)+1 response.write MyNewRandomNum %> The above code chops off the decimals and leaves you with a number such as 55. Note that it doesn't round the number of, it merely chops off the decimals. To round of the number use the Round function instead of Int as is demonstrated in example 4 below. Example 4; <% Dim MyNewRandomNum Randomize MyNewRandomNum = Round(Rnd * 100)+1 response.write MyNewRandomNum %> Related tutorial 'Generate a random number between 2 numbers' Here's the code to display a random quote Pasted from <http://www.codefixer.com/tutorials/random_number.asp> Generate a Random Picture with ASP We first need to create a random number to use this script between the number of images that we are going to use, so yes you have guessed it , if you are going to use 5 images then obviously we need to create a random number between 1 and 5. To create a number between 0 and 1 we can use the Rnd function. So to create a number between 1 and 5 we must use the line of code below in red. If you have 10 images then you would just change the value of the HighestNumber to 10. Note that to use the Rnd function properly you must put Randomize somewhere before it. I should also point out that as the number generated is decimal the Int function will chop off the decimal (5.122 would become 5). Have a look at the following code. <% Dim LowestNumber, HighestNumber, RandomNumber RANDOMIZE LowestNumber = 1
Unfiled Notes Page 25

RANDOMIZE LowestNumber = 1 HighestNumber = 5 RandomNumber = Int((HighestNumber-LowestNumber+1)*Rnd+LowestNumber) %> So having written the code that will get us a random number I am going to use the SELECT CASE function to select a banner or image. I have also put a hyperlink behind the banner/image. <% Dim LowestNumber, HighestNumber, RandomNumber RANDOMIZE LowestNumber = 1 HighestNumber = 5 RandomNumber = Int((HighestNumber-LowestNumber+1)*Rnd+LowestNumber) SELECT Case RandomNumber %> <% Case 1 %> <a href="link1.htm"><img src="banner1.gif" border=0></a> <% Case 2 %> <a href="link2.htm"><img src="banner2.gif" border=0></a> <% Case 3 %> <a href="link3.htm"><img src="banner3.gif" border=0></a> <% Case 4%> <a href="link4.htm"><img src="banner4.gif" border=0></a> <% Case 5 %> <a href="link5.htm"><img src="banner5.gif" border=0></a> <% End Select %> You can change the links and substitute your own banner/images names. Save the above code in a fill called banner.asp, modify the links and make 5 images/banners. Now use this line of code on all the pages where you want the banners to appear. Just make sure that banner.asp is in the same directory as the script you include it in. <!--#include file="banner.asp"--> Using an include file makes the whole thing easier to maintain. Just modify the banner.asp file, and all the Getting Started with OneNote Page 38 Using an include file makes the whole thing easier to maintain. Just modify the banner.asp file, and all the pages on your site are updated. If you want to include banner.asp into scripts that are located in subdirectories you can place banner.asp in the root of your site and use this include statement instead. <!--#include virtual="/banner.asp"--> In Part 2 of Generate a Random picture with ASPwe show you a real example that this site uses. Pasted from <http://www.codefixer.com/tutorials/random_picture.asp> ASP Arrays In short arrays are variables that can store more than one value. They are used to store a series of related information. Lets create an array called 'myArray' that will hold the names of 7 soccer teams. Arrays in ASP/VBScript have a zero based index. This means that the first item in the array starts at 0. <% 'Lets create our Array. First lets declare our Array variable Dim myArray(6) myArray(0)="spurs" myArray(1)="celtic" myArray(2)="ipswich" myArray(3)="liverpool" myArray(4)="man utd" myArray(5)="ac milan" myArray(6)="juventus"
Unfiled Notes Page 26

myArray(5)="ac milan" myArray(6)="juventus" 'Now lets create a loop moving through the array and printing out the values 'In the loop below we will simply substitute the value of i in myArray(i) 'for the first loop through i will be 0, then 1 and so on until it passes through 6 For i=0 to 6 response.write myArray(i) & "<br>" Next 'move on to the next value of i %> Output: spurs celtic ipswich liverpool man utd ac milan juventus In the example code above we have defined values for each individual array element on separate lines. Another way to create an array especially for smaller arrays is to define the whole array in one line with each element separated by a comma. <% Dim myArray myArray = Array("spurs","celtic","ipswich","brazil") %> Again we could loop through the array and print out the values in each array element. <% Dim myArray myArray = Array("spurs","celtic","ipswich","brazil") For i=0 to 3 response.write myArray(i) & "<br>" Next 'move on to the next value of i %> Assigning an array size as in the example code below with a variable will result in an error. You have to use an integer unless it's a dynamic array. <% myArraySize=10 Dim myArray(myArraySize) %> In part 2 read about 'Array Functions' In part 3 read about 'Multidimensional Arrays' In part 4 read about 'Dynamic Arrays' Pasted from <http://www.codefixer.com/tutorials/arrays.asp> Getting Started with OneNote Page 39 Pasted from <http://www.codefixer.com/tutorials/arrays.asp> Multi-dimensional Arrays Think of multi-dimensional arrays in terms of a table holding columns and rows. To create a multidimensional array simply specify the number of columns and rows you want the array to have. For example myArray(2,3) would have 3 columns and 4 rows. The table below could represent our multidemsional array 'myArray(2,3)'. Each cell holds a value. Below cell (0,3) holds a "bmw". 0 1 2 0 toyota white
Unfiled Notes Page 27

toyota white 22.000 1 ford blue 12.500 2 porshe red 50.000 3 bmw yellow 26.000 Below is what a multidimensional array would look like that held the values in the table above; <% Dim myArray(2,3) 'myArray(col,row) myArray(0,0) = "toyota" myArray(1,0) = "white" myArray(2,0) = "22.000" myArray(0,1) = "ford" myArray(1,1) = "blue" myArray(2,1) = "12.500" myArray(0,2) = "porshe" myArray(1,2) = "red" myArray(2,2) = "50.000" myArray(0,3) = "bmw" myArray(1,3) = "yellow" myArray(2,3) = "26.000" %> Using our array 'myArray(2,3)' that we created above we could create a HTML table and display the array values with the code snippet below; <% Response.Write "<table border='0'>" Response.Write "<tr><td>Row</td><td>Car</td>" Response.Write "<td>Color</td><td>Cost</td></tr>" 'In our code below you'll notice UBound(myArray,2). 'The 2 is an optional parameter, it identifies which 'dimension of the array you want to find the highest element of. 'In this case 2 signifies the rows dimension '1 is the default and would apply to the columns 'the highest element in the row column in this case is 3 'so we could look on our loopcounter going from 0 to 3 i.e. For i=0 to 3 'ArrayDimension defaults to 1, so if you are checking a 1 dimensional array or 'you want to check the first dimension you can leave this out. For i = 0 to UBound(myArray,2) Response.Write "<tr><td>" & i & "</td>" Response.Write "<td>" & myArray(0,i) & "</td>" Response.Write "<td>" & myArray(1,i) & "</td>" Response.Write "<td>" & myArray(2,i) & "</td></tr>" Next Response.Write "</table>" %> The above code displays the following result:
Unfiled Notes Page 28

The above code displays the following result: Row Car Color Cost 0 toyota white 22.000 1 ford blue 12.500 2 porshe red 50.000 3 bmw yellow 26.000 In Part 1 read about 'Arrays' In Part 2 read about 'Array Functions' In part 4 read about 'Dynamic Arrays' Pasted from <http://www.codefixer.com/tutorials/multidimensional_arrays.asp> Sending Email with CDONTS Below is a script that will send an email using the NewMail Object provided that the server has the Collaboration Data Objects for Microsoft Windows NT Server (CDONTS) component installed on it. Check with your webhost if you aren't sure whether CDONTS is installed. The SMTP service should be installed Getting Started with OneNote Page 40 Check with your webhost if you aren't sure whether CDONTS is installed. The SMTP service should be installed and running with Internet Information Services (IIS). <%@ language= "VBscript" %> <% Option Explicit 'declare your variables Dim NewMail, Body 'create an instance of the NewMail Object Set NewMail = Server.CreateObject("CDONTS.NewMail") NewMail.To= "michael@codefixer.com" ' the email address it will be sent to NewMail.From= "whoever@hotmail.com" ' the email address it was sent from Body= "Hi there, just testing codefixer's email tutorial out!" NewMail.Subject = "Hello" NewMail.Body = Body NewMail.Bodyformat=0 NewMail.Mailformat=0 NewMail.Send Set NewMail=Nothing %> If you would like to send it as plain text rather than HTML just remove the 2 lines NewMail.Bodyformat=0 NewMail.Mailformat=0 Important -CDONTS is deprecated on Windows XP, Windows 2003 and only included on Windows 2000 for backward compatability. Learn how to send email with the CDOSYS component. Just save your file as email.asp and run it on the server and it should work. Have a look at the form to email tutorialwhich will make a more dynamic page. Pasted from <http://www.codefixer.com/tutorials/email_cdonts.asp> Functions and Subprocedures Functions and subprocedures have many similarities: They can be called or invoked from anywhere within your script. A function or subprocedure can be reused as many times as required, thus saving you time writing out repetitive code and making for a less clustered looking page. Both are blocks of self contained code that can accept arguments. Both will only run when called or invoked from code elsewhere and will not run automatically when the page is loaded. The difference between a function and a sub is that a sub will do some stuff (like printing something to the screen) and then quit, while a function runs some code and then returns the result back to the code that called it. A Function could be used to do a calculation and then return a result. How to declare/write each: <% Sub NameOfSubRoutine(parameter1, parameter2)
Unfiled Notes Page 29

Sub NameOfSubRoutine(parameter1, parameter2) 'code goes here... End Sub %> <% Function NameOfFunction(parameter1, parameter2) 'code goes here NameOfFunction = "return value" End Function %> You will notice above parameter1 and parameter2. Data is passed into a procedure through the use of these arguments. Arguments are separated by commas and put into parenthesis after the procedure name. If there are no arguments, the procedure would still have the parenthesis, but they would be empty as our example below shows: <% Sub NameOfSubRoutine() 'code goes here... End Sub %> Below is a subprocedure that prints out details on the page: <% Sub PrintOut(name,address,country) response.write name response.write address response.write country End Sub %> To call the Sub, I could do one of the following: <% Call PrintOut("michael","34 Hark Avenue","Ireland") %> Getting Started with OneNote Page 41 %> OR <% PrintOut "michael","34 Hark Avenue","Ireland" %> Note that in each example, the actual argument passed into the subprocedure is passed into the subprocedure in the corresponding position. Also note that if you use the Call statement, the arguments must be enclosed in parenthesis. If you do not use call, the parenthesis aren't used. Like the Sub procedure, a Function can accept arguments, but unlike the Sub procedure, a Function can return a value. Functions are especially good for doing calculations and returning a value. <% Function Total(firstnumber,secondnumber) Total=(firstnumber+secondnumber) End Function %> This is how the function was called: <% Sum=Total(2,100) %> Calling the Total function made the value of Total equal to the value returned by the function, which then can be displayed by doing <% response.write Sum %> The output of the above is: 102
Unfiled Notes Page 30

The output of the above is: 102 Note that the returned value is named the same as the function. This is important to remember! You will need to name the output value the same as your function or you will not get a value returned. Pasted from <http://www.codefixer.com/tutorials/subs_and_functions.asp> The Querystring Have you ever seen a webpage that doesn't look like the standard www.codefixer.comyou type into the address bar. Maybe something like: www.resume-samples.com/resume.asp?resume=lawyer You'll notice the question mark attached on the end with a name/value pair. The name in this case is resume and it's value lawyer. All this is really doing is using the querystring in ASP to pass information to a page and the ASP script within it. In the above case the page displayed may now know to run code to show a lawyer's resume rather than a doctor's because of the value passed. The page 'choice.asp' displays its background color equal to the value of choice passed in the querystring. Choice.asp with a bluebackground and choice.asp with a redbackground. Create a file called 'querystring.asp' and paste the code below into it. Let me explain what this code will do. There will be 3 hyperlinks <a href....> when you click on one of these, all the links will take you to the same page though through the querystring you are passing a value .. and that value will hold your color. Once that link has been clicked and the querystring holds a value ( Request.querystring("value") <> "" ) then write out the value of request.querystring("color") which will we be the color you chose. Just note that in the following example that the links and the values in the querystring are going to the same page (we are using only one page). Therefore if the querystring doesn't hold a value then display all the links otherwise if it does hold a value write out that value as the fav color. <%@ Language="VBscript" %> <html> <head> <title>Querystring color</title> </head> <body> <% If Request.querystring("color") <> "" Then Getting Started with OneNote Page 42 If Request.querystring("color") <> "" Then Response.write "You picked " & Request.querystring("color") & " as the color." Else %> What is your favorite colour? <ul> <li><a href="querystring.asp?color=blue">blue</a></li> <li><a href="querystring.asp?color=green">green</a></li> <li><a href="querystring.asp?color=red">red</a></li> </ul> <% End if %> </body> </html> Note you may want to send more than one value through the querystring. Below is how a link to the page 'querystring.asp' would send the values of name and sex. <a href="querystring.asp?name=michael&sex=male">link</a> Pasted from <http://www.codefixer.com/tutorials/querystring.asp> Displaying and formatting Dates and Times Just to clear up an issue, the date and time displayed on this page are provided by my server so may not
Unfiled Notes Page 31

Just to clear up an issue, the date and time displayed on this page are provided by my server so may not be the same where you are. Some of the dates are displayed in UK format ie dd/mm/yyyy rather than the American mm/dd/yyyy, though they'll display correctly according to where your server is located. <% strNow=Now()' this variable will be used later below %> strNow holds the value 01/04/2011 04:53:33 <%= Date() %> prints out 01/04/2011 <%= Now() %> prints out 01/04/2011 04:53:33 <%= Time() %> prints out 04:53:33 <%= FormatDateTime(strNow, vbGeneralDate) %> prints out 01/04/2011 <%= FormatDateTime(strNow, vbLongDate) %> prints out 01 April 2011 <%= FormatDateTime(strNow,vbShortDate) %> prints out 01/04/2011 <%= FormatDateTime(strNow, vbLongTime) %> prints out 04:53:33 <%= FormatDateTime(strNow, vbShortTime) %> prints out 04:53 <%= Year(strNow) %> prints out 2011 <%= Month(strNow) %> prints out 4 <%=Day(strNow) %> prints out 1 <%=Hour(strNow) %> prints out 4 <%=Minute(strNow) %> prints out 53 <%=Second(strNow) %> prints out 33 <%= WeekDay(strNow) %> prints out 6 <%= WeekDayName(WeekDay(strNow)) %> prints out Friday <%= WeekDayName(WeekDay(strNow), 1) %> prints out Fri Other date and time related tutorials: Read more on the Date, Time and Now VBScript functions Here's a code snippet to display the day and date(eg. Mon 25 December). Here's a code snippet to display the day and date with the ordinal suffix (eg. Mon 25th December). How to get the current month name Time and Date based greetings IsDate Function The DateDiff DateAdd and DatePart Functions Pasted from <http://www.codefixer.com/tutorials/dates_times.asp> Create Loops in ASP Loops allow you to execute the same section of code again and again thereby saving you time and cutting down on the amount of code you have to write. VBscript has 2 main types of loops. The For...Next loop The For...Next loop lets you specify the number of times you want the loop to execute. <% For i=1 to 5 ' use i as a counter response.write i & "<br>" next 'repeat the code and move on to the next value of i %> The code prints out 1 to 5, the <br> tag puts a line break in between each value; 1 2 Getting Started with OneNote Page 43 2 3 4 5 The Do...Loop The Do...Loop allows you to loop while a condition is true or until a condition becomes true The Do While...Loop <% 'first of all assign a value to i i=1
Unfiled Notes Page 32

i=1 Do While i<9 response.write i & "<br>" i=i+1 'increment the value of i for next time loop executes Loop %> What the above code does is simply print out the following; 1 2 3 4 5 6 7 8 The Do Until ...Loop <% 'first of all assign a value to i i=1 Do Until i=9 response.write i & "<br>" i=i+1 'increment the value of i for next time loop executes Loop %> Again What the above code does is simply print out the following; 1 2 3 4 5 6 7 8 Exiting the Loop If you want to exit the loop then VBscript allows you to; <% For i=1 to 100 response.write i & "<br>" If i= 99 Then Exit For 'just before 100 is printed out the loop is exited Next %> Pasted from <http://www.codefixer.com/tutorials/looping.asp> Error Handling No matter how good a programmer you are you will undoubtedly make mistakes in your code, so its good programming to write code to cope with this eventuality.You can easily trap and turn nasty error messages into easy on the eye messages that the user can understand. The first thing you need to do is to put the following line on the top of your ASP page or code: <% On Error resume Next %> This four word combination is used to tell the server to resume the next line of code if it stumbles upon an error, the ASP script will continue to execute instead of throwing up an exception. The following code will display the error number, description and source. <% If Err.number <> 0 then 'if there is an error
Unfiled Notes Page 33

If Err.number <> 0 then 'if there is an error response.write Err.number 'write out the error number response.write Err.source 'write out the error source response.write Err.description 'write out the error description End If %> Getting Started with OneNote Page 44 %> Here's a version of the above code slightly better formatted; <% If Err.number <> 0 then 'if there is an error response.write ("Sorry you have encoutered an error." & "<br>") response.write ("Your error number is " & Err.number & "<br>") response.write ("The error source is " & Err.source & "<br>") response.write ("The error description is " & Err.description & "<br>") End If %> "On Error Resume Next" is usually placed at the top of each page. Below is an example with all the code coupled together: <% On Error Resume Next respons.write ("there is an error here as response is spelt respons") If Err.number <> 0 then 'if there is an error response.write ("Sorry you have encoutered an error." & "<br />") response.write ("Your error number is " & Err.number & "<br />") response.write ("The error source is " & Err.source & "<br />") response.write ("The error description is " & Err.description & "<br />") End If %> Even though the code has come across an error there will be no ugly error message displayed and the execution of the code will continue. As there is an error the description, number and source will be written out. Note that the following two lines of code are the same: If Err.Number <> 0 Then If Err <> 0 Then Get the best asp web Pasted from <http://www.codefixer.com/tutorials/errorhandling.asp> Advanced Error Handling in ASP Below is a slightly more advanced script to deal with an error. It uses an include file which you should put in the same folder as the page that calls it or if you know how to use a virtual include then work that way. <html> <head> <title>Error Handling</title> </head> <body> <!--#include file="error_checker.asp"--> <% respons.write ("this will produce an error as there is a mispelling") ErrorCheck() 'this calls the function which will check if there is an error 'you can call this function anywhere on your page 'it will only check errors in the previous code %> </body> </html>
Unfiled Notes Page 34

</html> Ok so now we will write the include file that will hold the Errorcheck funtion and deal with any errors encountered in the code. Below is the file that should be called error_checker.asp <% On Error Resume Next Function ErrorCheck() If Err.Number<>0 then 'if there is an error then the html table will be written out %> <table width="80%" border="0" align="center"> <tr> <td>Error is <%= Err.description%> and Error no. is <%=Err.number%> </td> </tr> <tr> <td>Please report the error to our webmaster @<a href="mailto:webmaster@codefixer.com"> webmaster@codefixer.com</a> </td> </tr> </table> Getting Started with OneNote Page 45 </table> <% End If End Function %> Pasted from <http://www.codefixer.com/tutorials/errorhandling_advanced.asp> The Include file '../includes/config.asp' cannot contain '..' to indicate the parent directory. Redirecting (Response.Redirect) You can redirect the browser to another URL with the Redirect method of the Response object. If you are going to redirect the user anytime after the <HTML> tag then you need to turn on buffering. On some servers it may be on by default. The statement below turns on buffering. <% Response.Buffer = True %> Then you can redirect the browser by doing this. <% Response.Redirect "whatever_the_page_is_called.asp" %> So a typical page would look like the following, notice that as the redirect appears in the <body> HTML tag we need to have buffering turn on. <%@ LANGUAGE="VBSCRIPT" %> <% Option Explicit %> <% response.buffer=true %> <html> <head> <title>redirect page</title> </head> <body> <% response.redirect("http://www.codefixer.com") %> </body> </html> You can place different redirects within (if/else) statements or you can also use variables as in the example below. Example: <%@ LANGUAGE="VBSCRIPT" %> <% Option Explicit %>
Unfiled Notes Page 35

<% Option Explicit %> <% response.buffer=true %> <html> <head> <title>redirect page</title> </head> <body> <% 'declare your variable Dim Page Page = "mainpage.asp" Response.Redirect (Page) %> </body> </html> Pasted from <http://www.codefixer.com/tutorials/redirect.asp> Close the Objects and free up Server resources Close each object when done with them. This frees resources and memory. This applies to objects that support close methods, especially connections and recordsets! Set each object variable to nothing when done with it. Notice the close and set to nothing at the end of the code. NEVER forget it in your code. <% recordset.close Getting Started with OneNote Page 46 recordset.close set recordset=nothing connection.close set connection=nothing %> Pasted from <http://www.codefixer.com/tutorials/close_objects.asp> Cookies with Keys In Cookieswe worked with simple cookies that only had one value associated with them. Cookies can also store multiple values of related information. When this is the case they are said to have Keys. For example just say you wanted to create a cookie to keep track of 3 pieces of personal information about a visitor. Instead of creating 3 different cookies, you could create one cookie (PersonalDetails) with 3 keys as in example 1. Example 1: <% Response.Cookies(PersonalDetails)(FirstName)=Michael Response.Cookies(PersonalDetails)(SurName)=Wall Response.Cookies(PersonalDetails)(CountryofBirth)=Ireland %> You can find the value of a cookie subkey by using the following syntax: syntax:Request.Cookies(NameofCookie)(NameofSubKey) So for our code in example 1 above we could use the code below to retrieve this cookie PersonalDetails with its 3 keys and write them out. <% Response.write Request.Cookies(PersonalDetails)(FirstName) & "<br>" Response.write Request.Cookies(PersonalDetails)(SurName) & "<br>" Response.write Request.Cookies(PersonalDetails)(CountryofBirth) & "<br>" %> The result would be: Michael Wall Ireland
Unfiled Notes Page 36

Wall Ireland Remember that unless you set the Expires attribute, the cookie will only last as long as you have the browser open. You could set the Expires attribute as below in example 2. Example 2: <% Response.Cookies(PersonalDetails)(FirstName)=Michael Response.Cookies(PersonalDetails)(SurName)=Wall Response.Cookies(PersonalDetails)(CountryofBirth)=Ireland Response.Cookies(PersonalDetails).Expires=Now() + 60 %> Using the HasKeys Property We can use the HasKeys property to determine whether or not a cookie holds multiple values. Syntax:Request.Cookies(theCookieName).HasKeys Again if we wanted to determine whether our cookie PersonalDetails created in example 1 had keys we could run the code in example 3. Example 3: <% BlnValue=Request.Cookies(PersonalDetails).HasKeys %> If the cookie named PersonalDetails has keys, then the variable BlnValue will be true otherwise the value will be false. Returning all the cookies and their values If you wanted to check what cookies your server has sent to the user's computer you could run the code below. It checks for what cookies have been written and if they have keys. <html> <body> <% Dim cookie, cookieKey For each cookie in Request.Cookies Response.write "<p>" If Request.Cookies(cookie).HasKeys then For each cookieKey in Request.Cookies(cookie) Response.write cookie & ":" & cookieKey & "=" & _ Request.Cookies(cookie)(cookieKey) Response.write "<br>" Next Else Response.Write cookie & "=" & Request.Cookies(cookie) & "<br>" End if Getting Started with OneNote Page 47 End if Response.write "</p>" Next %> </body> </html> Pasted from <http://www.codefixer.com/tutorials/cookies_with_keys.asp> Include files You can place all of your commonly used code in one simple file and include it in any number of other ASP files you want. So when you need to update one piece of code that is used throughout your application you can simply update it in one file ie the include file and every other page that uses the include file will automatically be updated. The include file can come in handy for such things as functions, headers and footers and the connection string. Believe me it can save alot of maintenance and updating time. Below is an example of how to use an include file:
Unfiled Notes Page 37

string. Believe me it can save alot of maintenance and updating time. Below is an example of how to use an include file: <html> <head> <title>Using include files</title> </head> <body> <!--#include file="myfile.asp"--> <!--#include virtual="/includes/myotherfile.asp"--> </body> </html> There are two way of using an include file. 1. Virtual, using the 'virtual' keyword 2. Relative, using the 'file' keyword Virtual: In using the virtual keyword it assumes that you are starting from the webserver's root directory. You are not concerned with the relative path from the file that you will be including it in, but exactly where it is located starting from the root of the website. example 1 <!--#include virtual="/myfile.asp" --> Using the code above assumes that the file 'myfile.asp' is located in the root directory. example 2 When building my sites I sometimes put all my include files in an include folder called 'includes'. If I wanted to call a file called 'myfile.asp' in the includes folder with the virtual keyword then it would look like this <!--#include virtual="/includes/myfile.asp" --> It doesn't matter what the directory location of the page calling the include file is. Relative: The file keyword indicates a relative path so if the include file was in the folder 'test' then the relative path from the current folder might be <!--#include file="../test/yourfilename.asp" --> or if the file was in the same folder then it would simply be <!--#include file="yourfilename.asp" --> So just to note that with virtual you are not concerned with the path relative to the file from which you will call the include file but its exact absolute position starting from the root directory of the website. Whereas with the file keyword you are concerned with the relative address from the file that you will be calling the include file from. Remember to place this code outside of the ASP script blocks, ie not within ASP delimiters <% %> Include files can end with the "inc" extension. However, for security reason i prefer using the "ASP" extension. Functions written in files using the "inc" extension can be opened in a browser window and viewed. Functions written in files using an "ASP" extension are not displayed to the viewer, thus keeping the source code hidden from hackers. You may want to read how I built this site using includes here. Pasted from <http://www.codefixer.com/tutorials/include_files.asp> Dynamic Includes The most important thing to note is that server side include files are inserted into their holding file before any of the holding file is processed. The include file is parsed before any ASP code so you can't use ASP variables in Getting Started with OneNote Page 48 the holding file is processed. The include file is parsed before any ASP code so you can't use ASP variables in server side includes like the example 1 below. In example 1 below the variable 'whichpage' will not exist at the time the include file is parsed. Example 1: <% Dim whichpage whichpage = Request.QueryString("page")
Unfiled Notes Page 38

Dim whichpage whichpage = Request.QueryString("page") If whichpage = "" Then whichpage = "default" %> <!--#include file="<%= whichpage %>.asp" --> <%End If %> The code in example 1 is trying to dynamically generate the name of the include file. We were trying to send a string through the querystring and assign it to the variable 'whichpage' and then it was our intention that that variable would go with the .asp file extension and make up an asp file name. Unfortunately, since the web server first inserts the include file, it will attempt to include a file with the name <%= whichpage %>.asp . This will generate an error as that file does't exist. The way I would suggest that we go about dynamic includes is to include all files and use some conditional statement to make sure that only one will actually be executed. The following code should work: Example 2: <% Dim whichpage whichpage = Request.QueryString("page") Select Case whichpage Case "default" %> <!--#include file="default.asp" --> <% Case "main" %> <!--#include file="main.asp" --> <% Case "admin" %> <!--#include file="admin.asp" --> <% Case Else %> <!--#include file="default.asp" --> <%End Select%> The above code will include all three include files but depending on the value of our variable 'whichpage' only one file makes up the outputed page. Pasted from <http://www.codefixer.com/tutorials/dynamic_includes.asp> Pasted from <http://www.codefixer.com/tutorials/friendly_http_error_message.asp> Getting Started with OneNote Page 49

Unfiled Notes Page 39

Thursday, April 07, 2011 8:39 PM

EIC Economics of information and communication Focus o Digital economy (internet economy) o Technological product (digital product) Impact and consequences o Intellectual capital Impact on economy o Technological product Prospective based on consumer Prospective based on seller Prospective based on process o Laws and collaboration on technological product Antitrust policy The information economy Technology changes but economic laws do not Information That can be digitized Costly to produce but cheap to reproduce Higher fixed cost low marginal cost Price according to its value not its cost Difficult to manage intellectual property Value=> when consumer experience it Economics of attention Wealth of information creates poverty of attention Technology The technology infrastructure makes information more accessible and hence more valuable System competition o Focus not just on your competitor but also collaboration and complemetors Lack in switching cost

o Positive feedback and network externalities Large network larger Leads demand side economic of scale and positive feedback o Standard change the competition for a market to competition within the market

Unfiled Notes Page 40

S-ar putea să vă placă și