Tuesday, 29 June 2010

Files from ajax.googleapis.com not loading

Could be because Google hosted jQuery library is being blocked by a content filter such as Websense and there isn't a workaround other than getting the content unblocked by an administrator.

http://superuser.com/questions/65007/files-from-ajax-googleapis-com-not-loading

http://meta.stackoverflow.com/questions/32271/stackoverflow-is-not-working-with-ajax/32284#32284

Friday, 25 June 2010

How to enable "View Souce" option on secured (HTTPS) / encrypted pages in IE

Internet Explorer saves a lot of web site information and data in temporary files for faster retrieval in the future. For most web sites that isn't a problem, but saving encrypted web pages that should be secure to a temp file on your disk can pose a security risk. This tip will show you how to enable/disable the saving of encrypted web pages.

1. On the menu bar click on Tools and select Internet Options

2. Click on the Advanced tab

3. Scroll through the list to the Security section at the bottom

4. Uncheck the box next to the option "Do Not Save Encrypted Pages To Disk"

By default it is checked which disables the "View Source" option.

5. Click OK to close the window and initiate the changes

I.e. if "Do Not Save Encrypted Pages To Disk" is checked "View Source" option will be disabled when an encrypted page is rendered. To investigate the HTML output you have to uncheck the above mentioned option.

Enabing Script Debugging in IE

1. Click the "Tools" menu
2. Click "Internet Options"
3. Click "Advanced"
4. Make sure "Disable Script Debugging (Internet Explorer)" is unchecked.

How to enable third-party cookies in your web browser

Internet Explorer 7 and Internet Explorer 8

1. Click the "Tools" menu
2. Click "Internet Options"
3. Select the "Privacy" tab
4. Click "Advanced"
5. Select "Override automatic cookie handling"
6. Select the "Accept" button under "Third-party Cookies" and click "OK"

Internet Explorer 6

1. Click the "Tools" menu
2. Click "Internet Options"
3. Select the "Privacy" tab
4. Move the settings slider to "Low" or "Accept all cookies"
5. Click "OK"

Firefox 3 and Firefox 3.5

1. Click the "Tools" menu
2. Click "Options..."
3. Select the "Privacy" menu
4. Make sure "Keep until" is set to "they expire"
5. Make sure "Accept third-party cookies" is checked

Firefox 2

1. Click the "Tools" menu
2. Click "Options..."
3. Select the "Privacy" menu
4. Make sure "Accept cookies from sites" is checked
5. Make sure "Keep until" is set to "they expire"

Safari

1. Click the "Safari" menu
2. Click "Preferences..."
3. Click the "Security" menu
4. For "Accept cookies" select "Always"

Google Chrome

1. Select the Wrench (spanner) icon at the top right
2. Select "Options"
3. Select the "Under the Bonnet" tab
4. Click "Content Settings" button
5. Select "Cookies" tab
6. Make sure "Block all third-party cookies without exception" is unchecked

Opera 9

1. Click the "Tools" menu
2. Click "Preferences..."
3. Click the "Advanced" tab
4. Select "Cookies" on the left list
5. Make sure "Accept cookies" is selected and uncheck "Delete new cookies when exiting Opera"
6. Click "OK"

Thursday, 24 June 2010

PCI Scanning

PCI Scanning stands for "Payment Card Industry" scanning. It involves having a PCI ASV (Approved Scanning Vendor) scan any and all IP addresses that the public has access to, related to your website or your site's transaction process.

Basically, when your merchant account provider or bank asks you to conduct a PCI Scan, they are asking you to ensure that all IP addresses that feed into or out from your site are clean and virus-free.

PCI stands for Payment Card Industry. A group, known as the PCI council consists of the five major credit card companies. They came up with a set of security standards in order to ensure that there is consistency throughout when processing credit cards.

If you are a merchant or service provider and accept credit cards you must confirm PCI compliance at least once a year. In order to be PCI compliant, network security scans, or PCI scans, are mandatory for all merchants and service providers that collect, process, or transmit payment card account information.

So what exactly is PCI scanning? It is when an ASV (Approved Scanning Vendor) scans your website to check for any vulnerabilities. All PCI scans must be conducted by a third party compliant network security scanning vendor. The scanning usually includes your websites IP address, but if you transfer your customers to a third-party shopping cart during the checkout process, then you should include their IP address to be scanned as well. This is very important because you could be held responsible if anyone gets a hold of your client's payment card information anywhere along the transaction process.

http://hubpages.com/hub/what-is-pci-scanning

Using jQuery pseudo selectors

jQuery offers a powerful set of tools for matching a set of elements in a document.

If you wish to use any of the meta-characters (#;&,.+*~':"!^$[]()=>|/ ) as a literal part of a name, you must escape the character with two backslashes: \\. For example, if you have an an input with name="names[]", you can use the selector $("input[name=names\\[\\]]").

Attribute Ends With Selector [name$=value]

jQuery('[attribute$=value]')

where

attribute = An attribute name.
value = An attribute value. Quotes are optional.

Description: Selects elements that have the specified attribute with a value ending exactly with a given string.

Example

<input name="newsletter" />
<input name="milkman" />
<input name="jobletter" />
<script>$("input[name$='letter']").val("a letter");</script>

:first Selector

Description: Selects the first matched element.

The :first pseudo-class is equivalent to :eq(0). It could also be written as :lt(1). While this matches only a single element, :first-child can match more than one: One for each parent.

Example
<table>
<tr>Row 1
<tr>Row 2
<tr>Row 3
</table>
<script>$("tr:first").css("font-style", "italic");</script>


http://api.jquery.com/category/selectors/

Tuesday, 22 June 2010

Everything You Need to Know About Response.Redirect

Basics of Response.Redirect

When you request a page from a web server, the response you get has some headers at the top, followed by the body of the page. When viewed in your browser the headers are never seen, but are used by the browser application. I have the following page called test.asp

<%@ Language=VBScript %>
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
</HEAD>
<BODY>

<p>Hello



</BODY>
</HTML>

When I request that from the web server this is the reply I get;

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Date: Mon, 19 Mar 2001 15:07:44 GMT
Connection: close
Content-Length: 134
Content-Type: text/html
Set-Cookie: ASPSESSIONIDQQGQQJWO=OMCJFABDNCDLLBKAPNHJBKHD; path=/
Cache-control: private


<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
</HEAD>
<BODY>

<p>Hello



</BODY>
</HTML>

http://pubs.logicalexpressions.com/pub0009/lpmarticle.asp?id=214

Server.Transfer Vs. Response.Redirect

Server.Transfer() doesn't end the current request, it only instructs ASP.NET to stop rendering the current page and start rendering the new page instead. The client is none the wiser, from its point of view the server is still responding to the initial request, so the URL displayed in the address bar does not change.

  • The page transferred to should be another .aspx page. For instance, a transfer to an .asp or .asmx page is not valid.
  • The Transfer method preserves the QueryString and Form collections.
  • Transfer calls Response.End(), which throws a ThreadAbortException exception upon completion.

Response.Redirect() ends the current request and sends a 302 response code to the client. The client then issues another HTTP request to the redirected URL and processes the response. Since the client knows that the URL has changed, it displays the redirected URL in its address bar.

Response.Redirect simply sends a message down to the browser, telling it to move to another page.

Server.Transfer is similar in that it sends the user to another page with a statement such as Server.Transfer("newpage.aspx"). However, the statement has a number of distinct advantages and disadvantages.

Firstly, transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.

But watch out: because the "transfer" process can work on only those sites running on the server, you can't use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.

Secondly, Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.

That's not all: The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("newpage.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.

For example, if your newpage.aspx has a TextBox control called TextBox1 and you transferred to WebForm2.aspx with the preserveForm parameter set to True, you'd be able to retrieve the value of the original page TextBox control by referencing Request.Form("TextBox1").

This technique is great for wizard-style input forms split over multiple pages. But there's another thing you'll want to watch out for when using the preserveForm parameter. ASP.NET has a bug whereby, in certain situations, an error will occur when attempting to transfer the form and query string values. You'll find this documented at http://support.microsoft.com/default.aspx?id=kb;en-us;Q316920.

The unofficial solution is to set the enableViewStateMac property to True on the page you'll be transferring to, then set it back to False. This records that you want a definitive False value for this property and resolves the bug.

So, in brief: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and, with a little bug-bashing, allows you to transfer the query string and form variables.

Top Tip: Don't confuse Server.Transfer with Server.Execute, which executes the page and returns the results. It was useful in the past, but, with ASP.NET, it's been replaced with fresher methods of development. Ignore it.

ViewState and its role in ASP.NET page processing

Processing Page Requests
When an initial request for a page (a Web Form) is received by ASP.NET, it locates and loads the requested Web Form (and if necessary compiles the code). It is important to understand the sequence of events that occurs when a Web Forms page is processed. This knowledge will help you program your Web Forms pages and Web applications more effectively.

As described before, initial page requests are relatively simple. The real work gets done when a page is submitted to itself - and a postback request is generated. Here are a few notes on postback requests:

* The current value of every control on a Web Form is contained in the postback request. This is referred to as the Post Data
* The content of the ViewState is also contained in the Post Data. ViewState holds the original property values of every control on a Web Form - before the user made any changes
* If a postback was caused, for example, by a button click, Post Data is used to identify the button that caused the postback


Postback Event Processing Sequence
Here are the events (and the order) that are raised when a Button is clicked and a postback occurs:

1. Page.Init + Control.Init for every control on the Web Form
The first stage in the page life cycle is initialization. After the page's control tree is populated with all the statically declared controls in the .aspx source the Init event is fired. First, the Init event for the Page object occurs, then Init event occurs for each control on the Page. Viewstate information is not available at this stage.
2. Page.LoadViewState
After initialization, ASP.NET loads the view state for the page. ViewState contains the state of the controls the last time the page was processed on the server.
3. Page.ProcessPostData
Post Data gets read from the request and control values are applied to control initalized in stage 1.
4. Page.Load + Control.Load for each control on the Page
If this is the first time the page is being processed (Page.IsPostback property), initial data binding is performed here.
5. "Change" events are fired for controls (TextChanged, SelectedIndexChanged, and similar)
The current value (from Post Data) is compared to the original value located in the ViewState. If there is a difference "Changed" events are raised.
6. Server-side events are fired for any validation controls
7. Button.Click + Button.Command
The Click and Command events are fired for the button that caused the postback
8. Page.PreRender + Control.PreRender
9. Page.SaveViewState
New values for all the controls are saved to the view state for another round-trip to the server.
10. Page.Render

As you can see from the postback steps, the ViewState has a major role in ASP.NET. Viewstate is a collection of name/value pairs, where control's and page itself store information that is persistent among web requests.

* The ASP.NET Page Life Cycle
* The Role of View State
* The Cost of View State
* How View State is Serialized/Deserialized
* Specifying Where to Store the View State Information (see how to store it in a file on the Web server rather than as a bloated hidden form field)
* Programmatically Parsing the View State
* View State and Security Implications

Follow the MSDN link to read more
http://msdn.microsoft.com/en-us/library/ms972976

ViewSate vs PostBack Data

Why do some Web controls like Textbox retain values even after disabling the ViewState while others do not?

Let’s build a simple Web application to examine how ViewState works.

Create a blank Web project and paste the code given below in the page:

<script runat="server">
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Handles btnSubmit.Click
lblMessage.Text = "Goodbye everyone"
lblMessage1.Text = "Goodbye everyone"
txtMessage.Text = "Goodbye everyone"
txtMessage1.Text = "Goodbye everyone"
End Sub
</script>
<form id="form1" runat="server">

<asp:Label runat="server" ID="lblMessage" EnableViewState =true
Text="Hello World"></asp:Label>
<asp:Label runat="server" ID="lblMessage1" EnableViewState =false
Text="Hello World"></asp:Label>
<asp:Textbox runat="server" ID="txtMessage" EnableViewState =true
Text="Hello World"></asp:Textbox>
<asp:Textbox runat="server" ID="txtMessage1" EnableViewState =false
Text="Hello World"></asp:Textbox>
<br />
<asp:Button runat="server"
Text="Change Message" ID="btnSubmit"></asp:Button>
<br />
<asp:Button ID="btnEmptyPostBack" runat="server" Text="Empty Postback">
</form>

The page rendered will have four controls (two text boxes and two labels) initialized with Hello World and two buttons.

Click on the Change Message button, the value in controls will be changed to Goodbye Everyone.

Now click on the Empty Postback button.

The expected result is, after postback the Textbox (txtMessage) and label (lblMessage) with EnableViewState = false should not retain the value and hence the value should be Hello world, while the controls with ViewState enabled (txtMessage1 and lblMessage1) should retain the value and hence value should be Goodbye world.

But this does not happen. Both the Textbox will maintain the value irrespective of whether ViewState is enabled or disabled, but in the case of label control if ViewState is disabled, the value we changed programmatically is not retained.

Let's examine why this happens?

Page LifeCycle and ViewState

In page life cycle, two events are associated with ViewState:

* Load View State: This stage follows the initialization stage of page lifecycle. During this stage, ViewState information saved in the previous postback is loaded into controls. As there is no need to check and load previous data, when the page is loaded for the first time this stage will not happen. On subsequent postback of the page as there may be previous data for the controls, the page will go through this stage.
* Save View State: This stage precedes the render stage of the page. During this stage, current state (value) of controls is serialized into 64 bit encoded string and persisted in the hidden control (__ViewState) in the page.
* Load Postback Data stage: Though this stage has nothing to do with ViewState, it causes most of the misconception among developers. This stage only happens when the page has been posted back. ASP.NET controls which implement IPostBackEventHandler will update its value (state) from the appropriate postback data. The important things to note about this stage are as follows:

1. State (value) of controls are NOT retrieved from ViewState but from posted back form.
2. Page class will hand over the posted back data to only those controls which implement IPostBackEventHandler.
3. This stage follows the Load View State stage, in other words state of controls set during the Load View State stage will be overwritten in this stage.

Why some controls retain values even after disabling the ViewState while others do not?


The answer is Controls which implements IPostBackEventHandler like Textbox, Checkbox, etc. will retain the state even after disabling the viewstate. The reason is during the Load Postback Data stage, these controls will get state information from Posted back form.

But controls like label which do not implement IPostBackEventHandler will not get any state information from posted back data and hence depend entirely on viewstate to maintain the state.

**An interesting behavior is if we make a control which implements IPostBackEventHandler interface disabled then the ASP.NET will not process the control during postback. So in the above sample, if we make the Textbox (one with EnableViewState = false) disabled then it will not retain the changed value and behave like a label control.


http://www.codeproject.com/KB/aspnet/ASPViewStateandPostBack.aspx

Friday, 18 June 2010

JavaScript Cookies

Writing and Reading cookies using JavaScript
http://www.w3schools.com/js/js_cookies.asp

<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());

}

function checkCookie()
{
username=getCookie('username');
if (username!=null && username!="")
{
alert('Welcome again '+username+'!');
}
else
{
username=prompt('Please enter your name:',"");
if (username!=null && username!="")
{
setCookie('username',username,365);
}
}
}
</script>
</head>

<body onload="checkCookie()">
</body>
</html>

Preventing Users From Copying Text From and Pasting It Into TextBoxes

Copy, Cut, and Paste Events in JavaScript
Much like ASP.NET, JavaScript code is typically event-driven, meaning that certain blocks of JavaScript execute in response to particular events. For example, you can run a block of script when the web page loads, when a form is submitted, or when an HTML element is clicked. If you are not familiar with JavaScript's event model, check out Introduction to Events, which gives a great overview of how event handling works in JavaScript.

JavaScript includes events that fire when the user attempts to copy, cut, or paste from within the browser window: copy, cut, and paste. What's more, by creating an event handler for these events you can write script that cancels the default behavior, meaning that with just a few lines of JavaScript you can "turn off" copying, cutting, and/or pasting behavior from within the browser. The copy, cut, and paste events are supported in most modern browsers, including Internet Explorer
5.5 and up, Firefox 3.0 and up, Safari 3.0 and up, and Chrome, although the support differs a bit between the various browsers. For instance, Firefox, Safari, and Chrome will fire the copy, cut, and paste events if the user copies, cuts, or pastes, anywhere in the document, but Internet Explorer only fires these events if the copy, paste, and cut occurs within a form, on an HTML element, within a text input, or on an image. (For more information on the browser compatibility for these events, refer to the cut, copy, paste Event Compatibility Matrix.)

Remarks:
1. You cannot truly prevent someone from copying, cutting, or pasting. The techniques we'll examine in this article show how to use JavaScript to put up a roadblock to copying, cutting, and pasting. However, a determined user could disable JavaScript in their browser, at which point the JavaScript you've written to prevent copying, cutting, and pasting is moot.
2. Preventing copying, cutting, and pasting can lead to a jarring and frustrating user experience. No matter what car you get into, when you turn the key you expect the to start. Imagine how frustrated you would become if you rented a car, hopped in, turned the key, and nothing happened. The same sentiment exists for computer user interfaces. Users expect certain functionality to be available when they sit down at a keyboard. They expect Ctrl+C to copy the selected contents to the clipboard, and Ctrl+V to paste. Disabling these comfortable and well-known idioms can unnerve users.

For these reasons, I would only recommend disabling copy and paste operations in specific circumstances where the benefits outweigh the negatives. Furthermore, I'd suggest giving users some sort of obvious and visual feedback when they attempt to copy or paste so that they understand these operations have been disabled and that it's not some software bug or hardware failure at play.

Using jQuery to Disable Copy and Paste

<script type="text/javascript">
$(document).ready(function () {
$('input[type=text]').bind('copy paste', function (e) {
e.preventDefault();
});
});
</script>

<script type="text/javascript">
$(document).ready(function () {
$('#id_of_textbox').bind('paste', function (e) {
e.preventDefault();
alert("You cannot paste text into this textbox!");
});
});
</script>

<script type="text/javascript">
$(document).ready(function () {
$('#<%=txtEmail.ClientID%>').bind('copy', function (e) {
e.preventDefault();
});


$('#<%=txtConfirmEmail.ClientID%>').bind('paste', function (e) {
e.preventDefault();
});
});
</script>

When a user attempts to copy or paste, "message" <div>'s text is set to an appropriate message, it is positioned to the right of the textbox, and is faded in over the course of three seconds, after which it fades out over the course of 1.5 seconds.

<script type="text/javascript">
$(document).ready(function () {
$('#<%=txtEmail.ClientID%>').bind('copy', function (e) {
e.preventDefault();

$('#message').text("You cannot copy the text from this textbox...")
.css(
{
left: 20 + $(this).offset().left + $(this).width() + 'px',
top: $(this).offset().top + 'px'
})
.fadeIn(3000, function () { $(this).fadeOut(1500) });
});
});
</script>

http://www.4guysfromrolla.com/articles/060910-1.aspx

Method to read Request Query String / Form Parameters

public string RequestParam(string ParamName)
{
string Result = String.Empty;

if (Context.Request.Form.Count != 0)
{
Result = Convert.ToString(Context.Request.Form[ParamName]);
}
else if (Context.Request.QueryString.Count != 0)
{
Result = Convert.ToString(Context.Request.QueryString[ParamName]);
}

return (Result==null) ? String.Empty : Result.Trim();
}

Managing User Account Creation

Many websites that support user account allow anyone to create a new account, but require new users to undergo some form of verification before their account is activated. A common approach is to send an email to the newly created user with a link that, when visited, activates their account. This approach ensures that the email address entered by the user is valid (since it is sent to that user's email address). This workflow not only ensures the valid data entry, but also helps deter automated spam
bots and abusive users.

In past installments of this article series we've seen how to use the CreateUserWizard control to allow users to create new accounts. By default, the user accounts created by the CreateUserWizard control are activated; new users can login immediately and start interacting with the site. This default behavior can be customized, however, so that new accounts are disabled. A disabled user cannot log into the site; therefore, there needs to be some manner by which a newly created user can have her account enabled.

There are many ways by which an account may be activated. You could have each account manually verified by an administrative user. If your site requires users to pay some sort of monthly fee or annual due, you could have the account approved once the payment was successfully processed. As aforementioned, one very common approach is to require the user to visit a link sent to the email address they entered when logging on.

This article explores this latter technique.

Wednesday, 2 June 2010

CAPTCHA

A CAPTCHA or Captcha is a type of challenge-response test used in computing to ensure that the response is not generated by a computer. The process usually involves one computer (a server) asking a user to complete a simple test which the computer is able to generate and grade. Because other computers are unable to solve the CAPTCHA, any user entering a correct solution is presumed to be human. Thus, it is sometimes described as a reverse Turing test, because it is administered by a machine and targeted to a human, in contrast to the standard Turing test that is typically administered by a human and targeted to a machine. A common type of CAPTCHA requires that the user type letters or digits from a distorted image that appears on the screen.

The term "CAPTCHA" (based upon the word capture) was coined in 2000 by Luis von Ahn, Manuel Blum, Nicholas J. Hopper, and John Langford (all of Carnegie Mellon University). It is a contrived acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart." Carnegie Mellon University attempted to trademark the term, but the trademark application was abandoned on 21 April 2008.

http://en.wikipedia.org/wiki/CAPTCHA

Free CAPTCHA ASP.NET Control

HTTP Status Codes

When a request is made to your server for a page on your site (for instance, when a user accesses your page in a browser or when Googlebot crawls the page), your server returns an HTTP status code in response to the request.

This status code provides information about the status of the request. This status code gives browser/Googlebot information about your site and the requested page.

Some common status codes are:

* 200 - the server successfully returned the page
* 404 - the requested page doesn't exist
* 503 - the server is temporarily unavailable

Visit W3C page on HTTP status codes for more information


1xx (Provisional response)


Status codes that indicate a provisional response and require the requestor to take action to continue.

100 (Continue)
The requestor should continue with the request. The server returns this code to indicate that it has received the first part of a request and is waiting for the rest.
101 (Switching protocols)
The requestor has asked the server to switch protocols and the server is acknowledging that it will do so.

2xx (Successful)

Status codes that indicate that the server successfully processed the request.

200 (Successful)
The server successfully processed the request. Generally, this means that the server provided the requested page. If you see this status for your robots.txt file, it means that Googlebot retrieved it successfully.
204 (No content)
The server successfully processed the request, but isn't returning any content.
206 (Partial content)
The server successfully processed a partial GET request.

3xx (Redirected)

Further action is needed to fulfill the request. Often, these status codes are used for redirection. Google recommends that you use fewer than five redirects for each request. You can use Webmaster Tools to see if Googlebot is having trouble crawling your redirected pages. The Crawl errors page under Diagnostics lists URLs that Googlebot was unable to crawl due to redirect errors.

300 (Multiple choices) The server has several actions available based on the request. The server may choose an action based on the requestor (user agent) or the server may present a list so the requestor can choose an action.

4xx (Request error)
These status codes indicate that there was likely an error in the request which prevented the server from being able to process it.

400 (Bad request) The server didn't understand the syntax of the request.

5xx (Server error)
These status codes indicate that the server had an internal error when trying to process the request. These errors tend to be with the server itself, not with the request.

500 (Internal server error) The server encountered an error and can't fulfill the request.

Click here to read more.