Tuesday, December 2, 2008
onkeypress not fired for Backspace and Delete
Here is a new thing that i have come across and wanted to share.
Scenario:
I was just experimenting to show the character count dynamically when a user types text in textarea. I have called a javascript function in onkeypress event of the textarea to calculate the count and put that in a html div element using innerHTML.
Observation:
onkeypress event does not fire for Back space and Delete keys in the keyboard.
Solution:
Use both onkeypress and onkeyup events and call the same function.
Saturday, October 4, 2008
Open a url in Kiosk/Full Screen mode
We can implement this by making configuration changes in window.open method of javascript.
Here is the sample logic:
window.open("sample.html","newwindow","fullscreen")
Monday, September 15, 2008
Browser detection in ASP
Request.ServerVariables("HTTP_USER_AGENT") will result in the following:
For IE:
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
For Firefox:
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Based on above, we can write below logic.
varBrowser= Request.ServerVariables("HTTP_USER_AGENT")
If InStr(varBrowser, "MSIE") > 0 Then
BrowserType = "IE"
Elseif InStr(varBrowser, "Firefox") > 0 Then
BrowserType = "FireFox"
End if
Saturday, September 13, 2008
Recordset GetString() method
This method can be used to fill HTML tables in ASP files.
You can find the details of the method in the below link:
http://www.w3schools.com/ADO/met_rs_getstring.asp
Saturday, June 14, 2008
Generate HTML dynamically in javascript
Suppose you want a textbox control to be added each time in an on click event of a hyper link,
Onclick javascript function:
You can use this logic according to your requirements.
Friday, June 13, 2008
To check and uncheck a radio button
Logic 1:
Add below code to the control
onclick='this.chk = this.chk ? this.checked = !this.chk : this.checked'
OR
Explanation:
A property by name "chk" is created to "this" object and is assigned the value of standard "checked". It stores the current state of the radio button. Based on this we check and uncheck the radio button. (You can use any name in place of "chk")
Logic 2:
Explanation:
Declare a global variable and set it to null initially. Call this function in the radio button control onclick event and pass "this" as parameter. When radio button is checked for first time, the if condition is true and hence it is checked. The global variable's value is now changed. Now when you check the radio button, if condition is false and hence else part is executed where radio button checked property is set to false. Here, global variable's value is again changed. This way, the radio button gets checked and unchecked alternatively.
Tuesday, May 27, 2008
Paging in ASP
Rs.Open sql,Conn,3,1 //here 3 is cursor type and 1 is lock type. cursor type is static and lock type is readonly
If not(Rs.eof and Rs.bof) then
//initialize paging requirements
Pagesize = 5 //set page size to a variable
Page = request(“page”) //get the current page no into a variable
If Page = “” then Page = 1 //if this variable is null that means it is first page
Recordcount = Rs.recordcount //get no. of records in Rs
Rs.pagesize = Pagesize //assign page size to Rs
Rs.absolutepage = Page //current page no. assigned to Rs
TotalPages = Rs.Pagecount //get count of total no. of pages
Prev = Page – 1 //Previous page no. set here
Next = Page + 1 //Next page no. set here
Count = 1 //initialize count variable to 1
//open the while loop of the result set
While not Rs.eof and Count <= Pagesize //Here, looping is restricted to the page size that we have set
………………………..
//increment count variable
Count = Count + 1
//close loopWend
//At the bottom of the page, provide links for paging
Print a page
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
Send Mail
//Declare mail object
Set objPersits = Server.CreateObject("Persits.MailSender")
With objPersits
.From = "sree@yahoo.com" //From Email Id
.FromName = "Sree" //Name of the Sender
.Host = "mail.domain.com" //Mail Host
.Subject = "Invitation"
.AddAddress mailTo,mailName
.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/affmail.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
Export to Excel
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment; filename=sheet1.xls"
Now write the code for the data that should be displayed in the excel file in the excel.asp page
................
In another page say export.asp give a link "Export to excel"
The href for the link should be given as excel.asp
When you click this link it will prompt you to open or save the excel file
Monday, May 26, 2008
Upload Files
Sample Code:
Upload code differs for different components used. I am giviing below the code for "Persits" component which i have used.
//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 the current window to the main page in the browser.
Virtual Directory
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.
ASP Components
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:
set adrotator=server.createobject("MSWC.AdRotator")
adrotator.GetAdvertisement("textfile.txt")
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:
Set cr=Server.CreateObject( "MSWC.ContentRotator" )
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:
Set nl=Server.CreateObject( "MSWC.NextLink" )
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:
Set MyBrow=Server.CreateObject("MSWC.BrowserType")
Global.asa File
The Global.asa file can contain only the following:
Application events
Session events
object declarations
TypeLibrary declarations
the #include directive
Events in Global.asa
Application_OnStart: Occurs when
# The FIRST user calls the first page from an ASP application.
# after the Web server is restarted or after the Global.asa file is edited
Session_OnStart: Occurs
# EVERY time a NEW user requests his or her first page in the ASP application.
Session_OnEnd: Occurs
# EVERY time a user ends a session.
# after a page has not been requested by the user for a specified time
Application_OnEnd: Occurs
# after the LAST user has ended the session.
# 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:
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 #include
Syntax:
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.
ASP 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:
Lock and Unlock:
Application.Lock
'do some application object operations
Application.Unlock
ASP Session
Internal mechanism:
Session is implemented by creating a unique id (session id) on the server for each user and embedding a cookie on the user machine with the session id. This is taken care of by isapi (internet server application programming interface) in server. If cookies are disabled in the user’s browser then isapi takes care of creating a cookie.
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.
Session.Timeout=5
To end the session immediately, Abandon method is used.
Session.Abandon
Store session variables:
Session("username")="Donald Duck"
Retrieve session variables:
Response.Write(Session("username"))
Remove session variables:
If Session.Contents("age")<18
To remove all variables in a session, use the RemoveAll method:
Session.Contents.RemoveAll()
To know the number of items in the content collection: use Count property
Session.Contents.Count
To see the values of all objects stored in the session object:
dim i
For Each i in Session.StaticObjects
Response.Write(i)
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 isn’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.
# Cookies are not secure where as sessions are secure.
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.
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:
Response.Cookies("firstname")="Alex"
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 = http://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:
dim x,y
for each x in Request.Cookies
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
next
else
Response.Write(x & "=" & Request.Cookies(x))
end if
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 Forms
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 as it is passed using querystring of the url.
POST:
1. Umlimited data can be sent.
2. Command used is Request.Form
3. Data is not visible to the users as it is passed using form elements.
ASP Introduction
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
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: asp delimiter @ language="JavaScript" asp delimiter
Execution: 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.
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 SCRIPT tags
5) HTML together with scripts tagged within asp delimiters
6) VBScripts tagged within SCRIPT tags
In a simple way, order of scripts is defined as (points 4, 5, 6 above) scripts in non-default language scripts using asp delimiter scripts in default language
ILLUSTRATION: