ASP Tutorial

Document Sample
ASP Tutorial
Shared by: swetha19
Stats
views:
1739
posted:
8/12/2009
language:
English
pages:
32
INTRODUCTION

    



ASP stands for Active Server Pages ASP is a program that runs inside IIS (Internet Information Services) An ASP file can contain text, HTML, XML, and scripts Scripts in an ASP file are executed on the server When a browser requests an ASP file, IIS passes the request to the ASP engine. The ASP engine reads the ASP file, line by line, and executes the scripts in the file. Finally, the ASP file is returned to the browser as plain HTML



You can run ASP on your own PC without an external server. To do that, you must install Microsoft's Personal Web Server (PWS) or Internet Information Services (IIS) on your PC. The default scripting language is VBScript. To set JavaScript as the default scripting language for a particular page you must insert a language specification at the top of the page. Like this: Advantages of ASP: • Minimizes network traffic by limiting the need for the browser and server to talk to each other • Makes for quicker loading time since HTML pages are only downloaded • Allows to run programs in languages that are not supported by the browser • Can provide the client with data that does not reside on the client’s machine • Provides improved security measures since the script cannot be viewed by the browser Difference between server side scripting and client side scripting: Scripts executed only by the browser without contacting the server is called client-side script. It is browser dependent. The scripting code is visible to the user and hence not secure. Scripts executed by the web server and processed by the server is called server-side script. Order of execution for an ASP application: 1) Global.asa 2) Server-side Includes statements 3) Directives 4) Jscript scripts tagged within tags 5) HTML together with scripts tagged within delimiters 6) VBScripts tagged within tags In a simple way, order of scripts is defined as (points 4, 5, 6 above) 1. scripts in non-default language 2. scripts using 3. scripts in default language



ILLUSTRATION: response.write("1") Response.Write("2"); ") %> Response.Write("4"); response.write("5") OUTPUT: 2 4 response.write("1") Response.Write("2"); "); %> Response.Write("4"); response.write("5")



3



1



5



OUTPUT: 1



5



3



2



4



ASP PROCEDURES Call a procedure using vbscript: OR Call a procedure using javascript: Call both vbscript and javascript procedures in vbscript: function jsproc(num1,num2) { Response.Write(num1*num2) }



Note: When calling a JavaScript or a VBScript procedure from an ASP file written in JavaScript, always use parentheses after the procedure name. In vbscript, parentheses are optional. If you omit the "call" keyword, the parameter list must not be enclosed in parentheses. ASP FORMS and INPUTS Commands for information retrieval from forms: 1. Request.QueryString 2. Request.Form Difference between GET and POST methods: GET: 1. Limited data can be sent upto 255 characters. 2. Command used is Request.QueryString 3. Data is visible to the users. POST: 1. Umlimited data can be sent. 2. Command used is Request.Form 3. Data is not visible to the users. ASP COOKIES A cookie is a temporary file used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. Why is a cookie used? A cookie (persistent) enables a website to remember you on subsequent visits, speeding up or enhancing your experience of services or functions offered. For example, a website may offer its contents in different languages. On your first visit, you may choose to have the content delivered in French and the site may record that preference in a persistent cookie set on your browser. When you revisit that site it will use the cookie to ensure that the content is delivered in French. Creating a Cookie:



Properties: 1. Domain: This is the domain that the cookie originated from. It is set by default to the domain in which it was created but it can be altered. Example: Response.Cookies("name").Domain = "www.cookiemonster.com" 2. Expires: There are 2 ways. a) You can use the current date and add or subtract days Response.Cookies("name").Expires = Date + 365

b)



You can set it to a specific date



Response.Cookies("name").Expires = #May 10,2002# Note: To expire the session enabled with cookies, Give current date. Example: Response.Cookies("name").Expires = Date OR Date-1 3. Path: This specifies in more detail the exact path on the domain that can use the cookie. Response.Cookies("name").Path = "/this/is/the/path" 4. Secure: If set, the cookie will only be set if the browser is using secure sockets or https:// to connect. Response.Cookies("name").Secure = True Dictionary Cookie OR Cookies with Keys: It is a cookie that can hold multiple values. Example: Response.Cookies("name")("first") = "John" Response.Cookies("name")("last") = "Smith" How to know if the cookie has keys? Ans: With the Haskeys property. Example: ") if Request.Cookies(x).HasKeys then



for each y in Request.Cookies(x) response.write(x & ":" & y & "=" & Request.Cookies(x)(y)) response.write("") next else Response.Write(x & "=" & Request.Cookies(x) & "") end if response.write "" next %> Note: There are limits on how much data you can put on a clients browser. Most browsers allow you to place 20 cookies per domain at a maximum of 4k each. Types of cookies: 1. Persistent: Persistent cookies are stored on your computer hard disk. They stay on your hard disk and can be accessed by web servers until they are deleted or have expired. Persistent cookies are not affected by your browser setting that deletes temporary files when you close your browser. 2. Non-Persistent: Non-persistent cookies are saved only while your web browser is running. They can be used by a web server only until you close your browser. They are not saved on your disk.



ASP OBJECTS



Response Object: Response object is used to display items on a web page. Request Object: The ASP Request object is used to get information from the user. Application Object: A group of ASP files that work together to perform some purpose is called an application. The Application object in ASP is used to tie these files together. Session Object: The Session object is used to store information about, or change settings for a user session. Server Object: The ASP Server object is used to access properties and methods on the server.



ASPError Object: The ASPError object is used to display detailed information of any error that occurs in scripts in an ASP page. Object Context: The ObjectContext object can be used to commit or abort a transaction. Collections, Properties and Methods: OBJECT COLLECTIONS PROPERTIES 1. Cookies 1. Buffer Response 2. ContentType 3. Expires 4. ExpiresAbsolute 5. Charset 6. CacheControl 7.IsClientConnected 8. Pics 9. Status 1. Cookies 1. TotalBytes Request 2. Form 3. QueryString 4.ServerVariables 5.ClientCertificate Application 1. Contents 2. StaticObjects



METHODS 1. Write 2. Redirect 3. End 4. Clear 5. Flush 6. BinaryWrite 7. AddHeader 8.AppendToLog 1. BinaryRead



EVENTS



Session



1. Contents 2. StaticObjects



Server



1. CodePage 2. LCID 3. SessionID 4. Timeout 1. ScriptTimeOut



1. Lock 2. UnLock 3.Contents.Remove 4.Contents.RemoveAll() 1. Abandon 2. Contents.Remove 3.Contents.RemoveAll() 1. CreateObject 2. Execute 3. GetLastError() 4. Transfer 5. HTMLEncode 6. URLEncode 7. MapPath



1. Application_OnStart 2. Application_OnEnd 1. Session_OnStart 2. Session_OnEnd



Error



1. ASPCode 2. ASPDescription 3. Category 4. Column 5. Line 6. Source 7. Description 8. File 9. Number



Object Context



1. SetAbort 2. SetComplete



1.OnTransactionAbort 2.OnTransaction CommitEvent



RESPONSE: Collections Collection Cookies Description Sets a cookie value. If the cookie does not exist, it will be created, and take the value that is specified



Properties Property Buffer CacheControl Charset ContentType Expires ExpiresAbsolute IsClientConnected Pics Status Methods Method AddHeader AppendToLog BinaryWrite Clear End Flush Redirect Write REQUEST: Description Adds a new HTTP header and a value to the HTTP response Adds a string to the end of the server log entry Writes data directly to the output without any character conversion Clears any buffered HTML output Stops processing a script, and returns the current result Sends buffered HTML output immediately Redirects the user to a different URL Writes a specified string to the output Description Specifies whether to buffer the page output or not Sets whether a proxy server can cache the output generated by ASP or not Appends the name of a character-set to the content-type header in the Response object Sets the HTTP content type for the Response object Sets how long (in minutes) a page will be cached on a browser before it expires Sets a date and time when a page cached on a browser will expire Indicates if the client has disconnected from the server Appends a value to the PICS label response header Specifies the value of the status line returned by the server



Collections Collection ClientCertificate Cookies Form QueryString ServerVariables Properties Property TotalBytes Description Returns the total number of bytes the client sent in the body of the request Description Contains all the field values stored in the client certificate Contains all the cookie values sent in a HTTP request Contains all the form (input) values from a form that uses the post method Contains all the variable values in a HTTP query string Contains all the server variable values



Methods Method BinaryRead Description Retrieves the data sent to the server from the client as part of a post request and stores it in a safe array



APPLICATION: Collections Collection Contents StaticObjects Description Contains all the items appended to the application through a script command Contains all the objects appended to the application with the HTML tag



Methods Method Contents.Remove Contents.RemoveAll() Lock Unlock Description Deletes an item from the Contents collection Deletes all items from the Contents collection Prevents other users from modifying the variables in the Application object Enables other users to modify the variables in the Application object (after it has been locked using the Lock method)



Events



Event Application_OnEnd Application_OnStart



Description Occurs when all user sessions are over, and the application ends Occurs before the first new session is created (when the Application object is first referenced)



SESSION: Collections Collection Contents StaticObjects Description Contains all the items appended to the session through a script command Contains all the objects appended to the session with the HTML tag



Properties Property CodePage LCID Description Specifies the character set that will be used when displaying dynamic content Sets or returns an integer that specifies a location or region. Contents like date, time, and currency will be displayed according to that location or region Returns a unique id for each user. The unique id is generated by the server Sets or returns the timeout period (in minutes) for the Session object in this application



SessionID Timeout



Methods Method Abandon Contents.Remove Contents.RemoveAll() Events Event Session_OnEnd Session_OnStart SERVER: Description Occurs when a session ends Occurs when a session starts Description Destroys a user session Deletes an item from the Contents collection Deletes all items from the Contents collection



Properties Property ScriptTimeout Description Sets or returns the maximum number of seconds a script can run before it is terminated



Methods Method CreateObject Execute GetLastError() HTMLEncode MapPath Transfer URLEncode ERROR: Properties Property ASPCode ASPDescription Category Column Description File Line Number Source Description Returns an error code generated by IIS Returns a detailed description of the error (if the error is ASPrelated) Returns the source of the error (was the error generated by ASP? By a scripting language? By an object?) Returns the column position within the file that generated the error Returns a short description of the error Returns the name of the ASP file that generated the error Returns the line number where the error was detected Returns the standard COM error code for the error Returns the actual source code of the line where the error occurred Description Creates an instance of an object Executes an ASP file from inside another ASP file Returns an ASPError object that describes the error condition that occurred Applies HTML encoding to a specified string Maps a specified path to a physical path Sends (transfers) all the information created in one ASP file to a second ASP file Applies URL encoding rules to a specified string



ASP SESSION The Session object is used to store information about a user session. Session variables are used to store information about ONE single user, and are available to all pages in one application. Typically information stored in session variables are name, id, and preferences. Session is implemented by creating a unique cookie for each user.



Session Starts when a new user requests an ASP file, and the Global.asa file includes a Session_OnStart procedure. A session ends if a user has not requested or refreshed a page in the application for a specified period. By default, this is 20 minutes. To set the timeout interval, Timeout property is used. To end the session immediately, Abandon method is used. Store session variables: Retrieve session variables: Remove session variables: The Contents collection contains all session variables. It is possible to remove a session variable with the Remove method. To remove all variables in a session, use the RemoveAll method: To know the number of items in the content collection: use Count property To see the values of all objects stored in the session object: ") Next %> What is the difference between session and cookie? If you set the variable to "cookies", then your users will not have to log in each time they



enter your community. The cookie will stay in place within the user’s browser until it is deleted by the user. But Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high. If you set the variable to "sessions", then user activity will be tracked using browser sessions, and your users will have to log in each time they re-open their browser. The Key difference would be cookies are stored in your hard disk whereas a session aren't stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.



ASP APPLICATION A group of ASP files that work together to perform some purpose is called an application. Application variables are available to all pages in one application. Application variables are used to store information about ALL users in a specific application. To create application variables: You can create Application variables in "Global.asa" like this: Sub Application_OnStart application("vartime")="" application("users")=1 End Sub Lock and Unlock: ASP #INCLUDE The #include directive is used to create functions, headers, footers, or elements that will be reused on multiple pages. Syntax:



or Virtual: to indicate a path beginning with a virtual directory File: to indicate a relative path. A relative path begins with the directory that contains the including file. Note: Included files are processed and inserted before the scripts are executed. GLOBAL.ASA FILE The Global.asa file is an optional file (stored in the root directory of the application) that can contain declarations of objects, variables, and methods that can be accessed by every page in an ASP application. The Global.asa file can contain only the following:

    



Application events Session events declarations TypeLibrary declarations the #include directive



Events in Global.asa Application_OnStart: Occurs when 1. The FIRST user calls the first page from an ASP application. 2. after the Web server is restarted or after the Global.asa file is edited Session_OnStart: Occurs 1. EVERY time a NEW user requests his or her first page in the ASP application. Session_OnEnd: Occurs 1. EVERY time a user ends a session. 2. after a page has not been requested by the user for a specified time Application_OnEnd: Occurs 1. after the LAST user has ended the session. 2. when a Web server stops



Note: we cannot use the ASP script delimiters () to insert scripts in the Global.asa file A Global.asa file could look something like this: sub Application_OnStart 'some code end sub sub Application_OnEnd 'some code end sub sub Session_OnStart 'some code end sub sub Session_OnEnd 'some code end sub Object Declaration: Syntax: .... Parameters: 1. scope 2. id 3. ProgID 4. ClassID Example: Difference between Object tag and Server.CreateObject: object tag creates the object and initializes the memory only when the first method/property of the object was accessed. Server.CreateObject will immediately create the object and initialize the memory.



ASP COMPONENTS 1. 2. 3. 4. AdRotator Content Rotator Content Linking Browser Capabilities



1. ADROTATOR: The ASP AdRotator component creates an AdRotator object that displays a different image each time a user enters or refreshes a page. Syntax: //Here textfile.txt contains information about the images Example: ASP page looks like below: /* code if images are hyperlinks "" then Response.Redirect(url) %> */ Txt file looks like below: REDIRECT banners.asp //is used when images should be hyperlinks WIDTH 468 //width, height and border are for the size of the image that is displayed HEIGHT 60 BORDER 0 * w3schools.gif //image http://www.w3schools.com/ //hyperlink address Visit W3Schools Alt text 80 //percent of hits microsoft.gif



http://www.microsoft.com/ Visit Microsoft 20 Methods: 1. GetAdvertisement Properties: 1. Border 2. Clickable 3. TargetFrame 2. CONTENT ROTATOR: The ASP Content Rotator component creates a ContentRotator object that displays a different HTML content string each time a user enters or refreshes a page. Syntax: Example: //ASP File looks like this: //Txt file looks like this %% #1 This is a great day!! %% #2 Smile %% #3 %% #4 Here's a link. Note: #Num indicates the relative weight of the HTML content string Methods: 1. ChooseContent



2. GetAllContent 3. CONTENT LINKING: The ASP Content Linking component is used to create a quick and easy navigation system! The Content Linking component returns a Nextlink object that is used to hold a list of Web pages to be navigated. Syntax: Example: //txt file looks like this: asp_intro.asp ASP Intro asp_syntax.asp ASP Syntax asp_variables.asp ASP Variables asp_procedures.asp ASP Procedures //On each of the pages listed above, put one line of code: . This line will include the code below on every page listed in "links.txt" and the navigation will work. //nlcode.inc file looks like this: 1) then Response.Write("Previous Page") end if Response.Write("Next Page") %> Methods: 1. GetListCount 2. GetListIndex 3. GetNextDescription 4. GetNextURL 5. GetNthDescription 6. GetNthURL 7. GetPreviousDescription 8. GetPreviousURL



4. BROWSER CAPABILITIES:



The ASP Browser Capabilities component creates a BrowserType object that determines the type, capabilities and version number of each browser that visits your site. When a browser connects to a server, an HTTP User Agent Header is also sent to the server. This header contains information about the browser (like browser type and version number). The BrowserType object then compares the information in the header with information in a file on the server called "Browscap.ini". If there is a match between the browser type and version number sent in the header and the information in the "Browsercap.ini" file, you can use the BrowserType object to list the properties of the matching browser. If there is no match for the browser type and version number in the Browscap.ini file, it will set every property to "UNKNOWN". The "Browsercap.ini" file is used to declare properties and to set default values for browsers. Syntax: Example: //browsercap.ini file on the server looks like this: ;IE 5.0 [IE 5.0] browser=IE Version=5.0 majorver=#5 minorver=#0 frames=TRUE tables=TRUE cookies=TRUE backgroundsounds=TRUE vbscript=TRUE javascript=TRUE javaapplets=TRUE ActiveXControls=TRUE beta=False ;DEFAULT BROWSER [*] browser=Default frames=FALSE



tables=TRUE cookies=FALSE backgroundsounds=FALSE vbscript=FALSE javascript=FALSE //ASP file looks like this: Client OS Web Browser Browser version Frame support? Table support? Sound support? Cookies support? VBScript support?



JavaScript support? ASP SCRIPTING OBJECTS Objects that can enhance the application are known as scripting objects. 1. Dictionary Object 2. File System Object 3. Text Stream



FILE SYSTEM OBJECT: The FileSystemObject object is used to access the file system on the server. Types: 1. FileSystem 2. TextStream 3. Drive 4. File 5. Folder FILESYSTEM: The following code creates a text file (c:\test.txt) and then writes some text to the file: Properties: Property Drives



Description Returns a collection of all Drive objects on the computer



Methods: Method BuildPath



Description Appends a name to an existing path



CopyFile CopyFolder CreateFolder CreateTextFile DeleteFile DeleteFolder DriveExists FileExists FolderExists GetAbsolutePathName GetBaseName GetDrive GetDriveName GetExtensionName GetFile GetFileName GetFolder GetParentFolderName GetSpecialFolder GetTempName MoveFile MoveFolder OpenTextFile



Copies one or more files from one location to another Copies one or more folders from one location to another Creates a new folder Creates a text file and returns a TextStream object that can be used to read from, or write to the file Deletes one or more specified files Deletes one or more specified folders Checks if a specified drive exists Checks if a specified file exists Checks if a specified folder exists Returns the complete path from the root of the drive for the specified path Returns the base name of a specified file or folder Returns a Drive object corresponding to the drive in a specified path Returns the drive name of a specified path Returns the file extension name for the last component in a specified path Returns a File object for a specified path Returns the file name or folder name for the last component in a specified path Returns a Folder object for a specified path Returns the name of the parent folder of the last component in a specified path Returns the path to some of Windows' special folders Returns a randomly generated temporary file or folder Moves one or more files from one location to another Moves one or more folders from one location to another Opens a file and returns a TextStream object that can be used to access the file



TEXTSTREAM OBJECT: The variable f is an instance of the TextStream object in the above example. To create an instance of the TextStream object you can use the CreateTextFile or OpenTextFile methods of the FileSystemObject object, or you can use the OpenAsTextStream method of the File object. Properties: Property AtEndOfLine



Description Returns true if the file pointer is positioned immediately before the end-of-line marker in a TextStream file, and false if not



AtEndOfStream Column Line Methods: Method Close Read ReadAll ReadLine Skip SkipLine Write WriteLine WriteBlankLines



Returns true if the file pointer is at the end of a TextStream file, and false if not Returns the column number of the current character position in an input stream Returns the current line number in a TextStream file



Description Closes an open TextStream file Reads a specified number of characters from a TextStream file and returns the result Reads an entire TextStream file and returns the result Reads one line from a TextStream file and returns the result Skips a specified number of characters when reading a TextStream file Skips the next line when reading a TextStream file Writes a specified text to a TextStream file Writes a specified text and a new-line character to a TextStream file Writes a specified number of new-line character to a TextStream file



DRIVE: The Drive object is used to return information about a local disk drive or a network share. The Drive object can return information about a drive's type of file system, free space, serial number, volume name, and more. Example: Output: Drive c: Total size in bytes: 4293563392



Properties: Property AvailableSpace DriveLetter DriveType FileSystem FreeSpace IsReady Path RootFolder SerialNumber ShareName TotalSize VolumeName FILE: The File object is used to return information about a specified file. To work with the properties and methods of the File object, you will have to create an instance of the File object through the FileSystemObject object. First; create a FileSystemObject object and then instantiate the File object through the GetFile method of the FileSystemObject object or through the Files property of the Folder object. Example: Output: File created: 9/19/2001 10:01:19 AM Description Returns the amount of available space to a user on a specified drive or network share Returns one uppercase letter that identifies the local drive or a network share Returns the type of a specified drive Returns the file system in use for a specified drive Returns the amount of free space to a user on a specified drive or network share Returns true if the specified drive is ready and false if not Returns an uppercase letter followed by a colon that indicates the path name for a specified drive Returns a Folder object that represents the root folder of a specified drive Returns the serial number of a specified drive Returns the network share name for a specified drive Returns the total size of a specified drive or network share Sets or returns the volume name of a specified drive



Properties: Property Attributes DateCreated DateLastAccessed DateLastModified Drive Name ParentFolder Path ShortName ShortPath Size Type Methods: Method Copy Delete Move OpenAsTextStream



Description Sets or returns the attributes of a specified file Returns the date and time when a specified file was created Returns the date and time when a specified file was last accessed Returns the date and time when a specified file was last modified Returns the drive letter of the drive where a specified file or folder resides Sets or returns the name of a specified file Returns the folder object for the parent of the specified file Returns the path for a specified file Returns the short name of a specified file (the 8.3 naming convention) Returns the short path of a specified file (the 8.3 naming convention) Returns the size, in bytes, of a specified file Returns the type of a specified file



Description Copies a specified file from one location to another Deletes a specified file Moves a specified file from one location to another Opens a specified file and returns a TextStream object to access the file



FOLDER: The Folder object is used to return information about a specified folder. To work with the properties and methods of the Folder object, you will have to create an instance of the Folder object through the FileSystemObject object. First; create a FileSystemObject object and then instantiate the Folder object through the GetFolder method of the FileSystemObject object. Example: Output: Folder created: 10/22/2001 10:01:19 AM Collections: Collection Files SubFolders Properties: Property Attributes DateCreated DateLastAccessed DateLastModified Drive IsRootFolder Name ParentFolder Path ShortName ShortPath Size Type Methods: Method Copy Delete Move CreateTextFile



Description Returns a collection of all the files in a specified folder Returns a collection of all subfolders in a specified folder



Description Sets or returns the attributes of a specified folder Returns the date and time when a specified folder was created Returns the date and time when a specified folder was last accessed Returns the date and time when a specified folder was last modified Returns the drive letter of the drive where the specified folder resides Returns true if a folder is the root folder and false if not Sets or returns the name of a specified folder Returns the parent folder of a specified folder Returns the path for a specified folder Returns the short name of a specified folder (the 8.3 naming convention) Returns the short path of a specified folder (the 8.3 naming convention) Returns the size of a specified folder Returns the type of a specified folder



Description Copies a specified folder from one location to another Deletes a specified folder Moves a specified folder from one location to another Creates a new text file in the specified folder and returns a TextStream object to access the file



DICTIONARY OBJECT: The Dictionary object is used to store information in name/value pairs (referred to as key and item). The Dictionary object might seem similar to Arrays, however, the Dictionary object is a more desirable solution to manipulate related data. Comparing Dictionaries and Arrays:

      



Keys are used to identify the items in a Dictionary object You do not have to call ReDim to change the size of the Dictionary object When deleting an item from a Dictionary, the remaining items will automatically shift up Dictionaries cannot be multidimensional, Arrays can Dictionaries have more built-in functions than Arrays Dictionaries work better than arrays on accessing random elements frequently Dictionaries work better than arrays on locating items by their content



Example: Output: The value of key gr is: Green Properties: Property CompareMode Count Item Key Methods: Method Add



Description Sets or returns the comparison mode for comparing keys in a Dictionary object Returns the number of key/item pairs in a Dictionary object Sets or returns the value of an item in a Dictionary object Sets a new key value for an existing key value in a Dictionary object



Description Adds a new key/item pair to a Dictionary object



Exists Items Keys Remove RemoveAll



Returns a Boolean value that indicates whether a specified key exists in the Dictionary object Returns an array of all the items in a Dictionary object Returns an array of all the keys in a Dictionary object Removes one specified key/item pair from the Dictionary object Removes all the key/item pairs in the Dictionary object



VIRTUAL DIRECTORY Allows you to create multiple website under one ip address. Allows you reference another location (folder) to include additional functionality. To create one 1) Open IIS Manager (Ctrl Panel->Admin Tools->Internet Service Manager) 2) Right click the default site and “New”>”Virtual Directory”. 3) Type the name of the virtual directory and then browse to the location you would like to reference.



UPLOAD FILES //Form tag in upload page //To browse a file, give Type=”FILE” Eg: Note: We use a third party component “Persits” to upload any file. //Create Upload object Set Upload=Server.CreateObject("Persits.Upload.1") //If a file already exists with same name then we can give option whether to upload or not to upload. Upload.OverwriteFiles = False/True Eg: True: If swetha.jpg already exists then also the file is uploaded as swetha[1].jpg False: If same name already exists then we cannot upload. //If there is any error in uploading and we still want to move ahead then we give this. If we want to see the error then we should remove this statement. On Error Resume Next //Set File Limit to upload



Upload.SetMaxSize 5242880 //We can also add code for creating the folder if the specified does not exist Set fso=Server.CreateObject("Scripting.FileSystemObject") if fso.FolderExists(server.mappath("./CoachImages"))=false then Set fobj=fso.CreateFolder(server.mappath("./CoachImages")) end if Set fobj=nothing Set fso=nothing //To get the count of the uploaded files Count = Upload.Save(server.mappath("./"&folder))



//To know if a file a uploaded or not. If not Show Error Message if Count = 0 then Error // In Else part, we increment a loop for the uploaded Files For Each File in Upload.Files //Here we check the type of file. Suppose it is an image, then If ucase(File.ImageType) = "GIF" or ucase(File.ImageType) = "JPG" …….then //To get File Name File.FileName //To get Image Width File.ImageWidth //To get Image Height File.ImageHeight Else //If file type does not match then we can delete the file File.Delete End If Next //To delete an old uploaded file Set fs=Server.CreateObject("Scripting.FileSystemObject") if fs.FileExists(Server.MapPath("./BoardImages/"&IRs("photoname"))) then fs.DeleteFile(Server.MapPath("./BoardImages/"&IRs("photoname"))) end if set fs=nothing After clicking SUBMIT, in Javascript function SendBoardValues() { window.close();



window.opener.evntfrm.submit(); } Here, opener is used to get the values in this window to the main page in the browser.



Export to Excel // Mention below lines in the asp page Response.ContentType = "application/vnd.ms-excel" Response.AddHeader "Content-Disposition", "attachment; filename=sheet1.xls" After this, use an html table to write the desired data.



Send Mail Note: We use a third party component “Persits” to send a mail. //Declare mail object Set objPersits = CreateObject("Persits.MailSender") With objPersits .From = "affiliates@sportskids.com" //From Email Id .FromName = "SportsKids.com" //Name of the Sender .Host = "mail.sportskids.com" //Mail Host .Subject = "Invitation" .AddAddress , .Body = mailbody .isHTML = True //If html content exists in the mail body on error resume next .Send //To send mail finally if err.number 0 then response.write "Error " & err.number & " sending to " & mailTo & " (" & mailName & ")" //To know the description of the error, we give response.write err.description err.clear else //Mail has been sent end if .RemoveAddress mailTo, mailName End With set objPersits = nothing How to send an external html file through mail?



//Declare file system object to read from the file set fso = Server.CreateObject("Scripting.FileSystemObject") //Specify File location fname = "/AffiliateEmails/skaffmail.htm" //Open a file using above object and set it to a new object set fObj = fso.openTextFile(server.mappath(fname)) //Read from the file and assign to a variable which is further assigned to the .Body of the mail mailBody = fObj.readAll //Close the connection to the file fObj.close set fso = nothing



No Print //Give the link in the html page to print Print //On clicking, the entire page is printed How to eliminate the unnecessary things from printing? // Declare the style in a style sheet .noprint { DISPLAY: none } //include the external style sheet in the page //Put the div tags with class=”noprint” in the page wherever required ……..



Paging //execute the query and open the recordset If not(Rs.eof and Rs.bof) then //initialize paging requirements Pagesize = 5 Page = request(“page”)



//set page size to a variable //get the current page no into a variable



If Page = “” then Page = 1 Recordcount = Rs.recordcount Rs.pagesize = Pagesize Rs.absolutepage = Page TotalPages = Rs.Pagecount Prev = Page – 1 Next = Page + 1 Count = 1



//if this variable is null that means it is first page //get no. of records in Rs //assign page size to Rs //current page no. assigned to Rs //get count of total no. of pages //Previous page no. set here //Next page no. set here //initialize count variable to 1



//open the while loop of the result set While not Rs.eof and Count 0 then //if previous pages are available then this link appears %> ">Previous "> -3 then //if next pages are available %> ">Next




Share This Document


Related docs
Other docs by swetha19
AJAX Basic Tutorial
Views: 402  |  Downloads: 72
ASP Tutorial
Views: 1739  |  Downloads: 211
by registering with docstoc.com you agree to our
privacy policy

You are almost ready to download!

You are almost ready to download!