Monday, May 9, 2011

How to Debug Classic ASP in VS 2010 and Windows 7

Bookmark and Share
In the past, I have been using Team Remote ASP Debugger tool to debug my legacy ASP applications in Windows XP. However, the debugger tool stopped working after I migrated my computer OS to Windows 7. I called their tech support and they told me that that tool no longer works in Windows 7 – I need to buy their Windows 7 version for an upgrade price of $200. Wow! $200 is a little bit pricy for an ASP debugger. The heck with it! I am sure there is an alternative out there. After a few trials and errors over the weekend, I was able to figure out how to debug ASP in VS2010. Here is what you need to do:


1. Make sure that the following Windows features are installed on your computer correctly. To see what already installed on your computer, go to Control Panel >> Programs >>Turn Windows Feathers on or off
>>Under Internet Information Services, enable IIS Management Console, IIS Management Scripts & Tools, and IIS Management Service.
>>Under World Wide Web Services:
>Application Development Features - enable everything
>Common HTTP Features - enable Default Document and Static Content
>Security - enable Basic Authentication, Request Filtering and Windows Authentication
>>Check OK


In IIS, under “Default Web Site”, add a new app that points to the physical location of your files (see the example below for creating a new app named HPUnify . Note that an Application Pool is created with DefaultAppPool.




2. In IIS Manager Features View, double-click Default Document and ensure the Default.asp is in the list. Backup to the Features View and double-click - ASP icon.
• Enable Parent Paths - set to True
• Expand Debugging Properties
i. Enable Client-side Debugging - set to True
ii. Enable Server-side Debugging - set to True
iii. Send Errors to Browser - set to True




3. Go to Explorer, right-click on the top folder, select Properties >> Security. Make sure that you are granted to the full control of the physical folder.



4. Finally to Visual Studio 2010 - run Visual Studio as an administrator! Then, open your website - File >> Open Web Site >> File System and select the root folder then click open. Now in Solution Explorer, right-click on the site root and select Property Pages. Under Build, select "No Build", then under Start Options >> Server, select "Use custom server" and enter the base URL with the port number for the site you created earlier: http://localhost/hp-unify - click OK.





Now Go back to Visual Studio 2010 and select Debug >> Attach to Process. At the bottom of the dialog, select both "Show Processes..." check boxes - then in the "Available Processes" list, scroll to the bottom and select w3wp.exe and then click "Attach". If you get a warning select YES/Continue.





Now set breakpoints in your code.

Finally launch your App from IIS manager by right-click on the app select Manage Application >> Browse. Your app should start and you should be able to step through your code (see my example below)



Hope this information is helpful!

Bookmark and Share

Sunday, May 8, 2011

How to Implement Context-Sensitive Help in ASP.NET App


Bookmark and Share


Context-sensitive help is usually perceived as being tedious or difficult to implement. However, if you’re writing help for a web application, this little javascript trick makes delivering context-sensitive help easy. Using this method, the developer doesn’t have to manually configure any of the URLs, and you as a tech writer have only a minimal amount of work as well. Each page in the application calls the right help topic for the right page. After seeing how easy it is to deliver context-sensitive help this way, I would never use any other method.

Conceptual Explanation
While easy to implement, it’s conceptually tricky to explain. Just so you don’t miss anything, here’s the concept of how it works. Each page in the application has a help button with the exact same code. When a user clicks the help button, the help button calls a javascript that says something like this:
1. What is the name of the current page?
2. OK, great, now change the extension of this page name to .htm.
3. Call this exact same page from the help folder.
It does not matter what tool you are using for this method, as long as the application is a Web application (rather than a Winform application).

Writer’s Role

Writers must follow these steps to deliver the context-sensitive help:
1. If you’re using a tool like RoboHelp or Flare (or any other tool, for that matter), match the help topic’s file names with the application page names that you’re associating the help topic with. For example, if the application page is called contact.aspx (look in the Web address to see the name), then you would rename your help topic’s file name contact.htm. If the application page is named config.aspx, then rename the help topic’s file name corresponding to this page config.htm.
2. Remove each of your help files from any distinct subfolders. You can’t have some files inside folder A, some files inside folder B, others inside folder C, etc. All the files must be within the same folder.
3. Let the developer know the path and folder of the published files.

Developer’s Role

1. In the following javascript code, change the path in red to match the path of the published help folder, and insert this javascript into the header of each page (between the
tags).

function showHelp(){
//this is the name of the domain or the root url you want for the help link
var pagePrefix = “http:/
/samplewebpath/acmeapplication/webhelp/index.htm#”
//this is the help extension that will replace whatever exists on the current page
var helpExtension = “.htm”
//this gets the current full path to the page
var pageName = window.location.pathname;
//this returns just the page name and its extension
pageName = pageName.substring(pageName.lastIndexOf(‘/’) + 1);
//this identifies just the page extension of the current page
var pageExtension = pageName.substring(pageName.lastIndexOf(‘.’));
//this replaces the current page name extension with the help extension
pageName = pagePrefix + pageName.replace(pageExtension, helpExtension)
// this shows you the link that will be opened
//alert(pageName);
//this is the popup script for the new window
myWindow = window.open(pageName, “tinyWindow”, ‘scrollbars=yes,menubar=no,height=600,width=600,resizable=yes,toolbar=no,location=no,status=no’)
//this assures the window will come to the front of the current page
myWindow.focus()
}

2. In the body of your page, call the help topic like this:



Obviously you need to replace the path in red with the path of your actual help button file.

That’s it. Now when the user clicks the help button, the page with the same file name in your help files will appear.






Bookmark and Share

Thursday, May 5, 2011

How to Improve Performance in ASP.NET


Bookmark and Share


Below is the list of things you can do to improve your ASP.NET application performance:

1) Set debug=false under compilation as follows:

2) Use Server.Transfer instead of Response.Redirect.

3) Always check Page.IsValid when using Validator Controls

4) Use Foreach loop instead of For loop for String Iteration.

5) Use Client-Side Validation.

6) Check “Page.IsPostBack”. To avoid repetition code execution.

7) GIF and PNG are similar, but PNG typically produces a lower file size.

8) Use the AppOffline.htm when updating binaries

9) Turn off Tracing unless until required.

trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/


10) Precompiled pages and disable AutoEventWireup; setting the AutoEventWireup attribute to false in the Machine.config file.

11) Turn off Session State, if not required.
sessionstate timeout="20" cookieless="false" mode="Off" stateconnectionstring="tcpip=127.0.0.1:42424" sqlconnectionstring="data source=127.0.0.1;Trusted_Connection=no"


12) Select the Release mode before making the final Build for your application.

This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug

13) Disable ViewState when not required.

EnableViewState="false"

14) Avoid frequent round trips to the Database.

15) Use Caching to improve the performance of your application.

16) Validate all Input received from the Users.

17) Use Finally Method to kill resources.

18) The String and Stringbuilder Magic.

It is nice to use Stringbuilder instead of String when string are Amended. Strings occupy different memory location in every time of amended where stringbuilder use single memory location

19) Never use object value directly; first get object value in local variable and then use. It takes more time then variable reading.

20) Avoid Exceptions: Use If condition (if it is check proper condition)

21) Code optimization: Avoid using code like x = x +1; it is always better to use x+=1.

22) Data Access Techniques: DataReaders provide a fast and efficient method of data retrieval. DataReader is much faster than DataSets as far as performance is concerned

23) Before doing a bulky ASP code processing, you can check to make sure Response.IsClientConnected.

24) As always, avoid session variables because each ASP page runs in a different thread and session calls will be serialized one by one. So, this will slow down the application. Instead of session variables you can use the QueryString collection or hidden variables in the form which holds the values.

25) Enabling buffering will improve the performance, like
response.buffer=true

Then use:
response.flush=true

26) Use Repeater control instead of DataGrid , DataList, Because It is efficient, customizable, and programmable.

27) Data listing is more time consume when large data are retrieve from database.

Paging will display only particular data but take load of all data.

Fetch only data that is needed for current page.

28) Avoid Inline JavaScript and CSS

29) Use single css file instead of multiple css file.

Try your best to combine all your CSS based classes into a single .css file as lot of .css files will cause a large amount of requests, regardless of the file sizes.

.css files are normally cached by browsers, so a single and heavy .css file doesn’t cause a long wait on each page request.

Inline .css classes could make HTML heavy, so again: go ahead with a single.css file.

30) Reduce cookie size

31) Compress CSS, JavaScript and Images

Online compressors are available; to compress file please refers following web and Replace your file content with optimize code.

http://iceyboard.no-ip.org/projects/css_compressor for CSS compression

www.xtreeme.com/javascript-optimizer/ . For JS Compression

32 .Use Cache appropriately

i. Page output caching:
@ OutputCache Duration="3600" VaryByParam="none"

ii. Page fragment caching:

Write a Page output caching code into each User Control

iii. Data caching:



33) Use server side compression software such as Port80s http://www.port80software.com/products/httpzip/


Bookmark and Share

Friday, April 29, 2011

Preventing SQL Injection Attacks in Classic ASP


Bookmark and Share


The term "SQL Injection" means to inject malicious SQL statement(s) in an otherwise regular SQL to get access to secure data on a website. Most hackers who attempt this attack use SQL injection in querystring variables in a URL or in form contents being posted back to a web page. In this article, we will examine what SQL injection attacks are and what programming techniques can be used to prevent them. While we will assume classic ASP pages and the backend SQL Server database to demonstrate the method and means of prevention, the concept is equally applicable to other web programming technologies and database systems.

How a SQL Injection Attack is Carried Out?
Any time you generate a SQL statement dynamically in an ASP page using data retrieved from a querystring, form content, or even a cookie, you expose yourself to a SQL injection attack. To demonstrate this, have a look at the following insecure code which creates a dynamic SQL statement by retrieving data form a querystring:

Dim sql
sql = "SELECT [Title], [Description] FROM [Articles] WHERE [ArticleID] = " & _
Request.QueryString("articleId")
This code expects a querystring parameter with the name of articleId. While the developer may have provided a valid integer in the URLs on his website for this piece of code to work as expected, a hacker when he sees this URL will try to exploit this weakness by injecting his own SQL statement(s) to view, update or delete the content in the developer's database.

For example, all the hacker has to do to view the contents of [dbo].[sysobjects] table is to set the value of querystring to following:

0 UNION SELECT [name], [xtype] FROM [dbo].[sysobjects] --
The 0 at the start effectively removes any rows being returned for the original query while the second statement usign a UNION keyword appends secret data from [dbo].[sysobjects] table to the returning recordset. The last "--" keyword comments out any other SQL statement(s) appended to this statement by the developer. Thus the complete SQL statement that will get executed becomes the following:

SELECT [Title], [Description] FROM [Articles] WHERE [ID] = 0 UNION
SELECT [name], [xtype] FROM [dbo].[sysobjects] --
Now that you have got the idea what SQL injection attack is and how it is carried out, we will focus on what measures can be taken by an ASP developer to prevent such an attack from happening.

Programming Techniques Necessary to Prevent SQL Injection Attacks
I am going to describe two techniques which will effectively prevent most SQL injection attacks from happening on your website. They are:

Use CLng() when retrieving non-string values
Use Replace(str, "'", "''") when retrieving string values

Using CLng() to Prevent SQL Injection in non-String Values
When appending non-string values like numbers in a dynamic SQL statement, use CLng() to convert that value to a number. CLng() will internally check if the parameter can actually be converted to a number. If the parameter to CLng() contains malicious strings like apostrophe, CLng() will throw an error.

Dim articleId
articleId = CLng(Request.QueryString("articleId"))
In our example of SQL injection attack, had we used CLng() to convert the querystring value to a number first, the SQL injection attack would have failed. So remember this, always use CLng() for all non-string values that you want to append to a dynamic SQL statement.

Using Replace(str, "'", "''") to Prevent SQL Injection in String Values
When retrieving String values, convert all apostrophe (') characters to double apostrophe ('') characters. This will effectively remove the special status of apostrophe character in a SQL statement and will be treated by the SQL Server as a regular string character.

Dim userName
userName = Replace(Request.Form("userName"), "'", "''")
Remember, always use Replace(str, "'", "''") for all String values that you want to append in a SQL statement.

Creating a Utility Routine in VBScript to do the Conversion for Us
Instead of hand coding CLng() and Replace(str, "'", "''") every time you have a non-string or String value, respectively; we can create a Function in VBScript and use it every time we retrieve values from querystrings, forms and cookies.

Function GetSecureVal(param)
If IsEmpty(param) Or param = "" Then
GetSecureVal = param
Exit Function
End If

If IsNumeric(param) Then
GetSecureVal = CLng(param)
Else
GetSecureVal = Replace(CStr(param), "'", "''")
End If
End Function
Now each time you have to retrieve values, just use GetSecureVal() like this:

' Retrieving values from a form
Dim firstName, lastName, email, age
firstName = GetSecureVal(Request.Form("firstName"))
lastName = GetSecureVal(Request.Form("lastName"))
email = GetSecureVal(Request.Form("email"))
age = GetSecureVal(Request.Form("age"))

Dim sql
sql = "INSERT INTO [Users] ([FirstName], [LastName], [Email], [Age]) " & _
"VALUES ('" & firstName & "', '" & lastName & "', '" & email & _
"', " & age & ")"
Use GetSecureVal() for Values retrieved even from Cookies
Do not underestimate hackers, they can change the cookies and enter their malicious string to inject SQL statements. So, even when retrieving values from cookies and using them in SQL statements, always use GetSecureVal() to convert the apostrophe charaters (') to double apostrophe characters ('').

Dim userNameFromCookie
userNameFromCookie = GetSecureVal(Request.Cookies("userName"))
Summary of Programming Techniques
Always use CLng() for numeric values and Replace(str, "'", "''") for String values. I have provided you a good generic function which will convert the parameter to appropriate type and remove any chances of SQL injection.

I hope you found the content in this article uesful, and will use the programming techniques mentioned to secure your SQL statements against malicious injection.

Bookmark and Share