Friday 30 December 2011

ASP.NET MVC : Using C# keyword 'class' as HTML attribute

If you are developing an ASP.NET MVC application you will have to set the CSS class name of an HTML element or INPUT control using HTML Helper methods. For example


@Html.RadioButton("status", "1", true, new { id = "status", class='radio' })


tries to set the CSS class name of the radio button to 'radio'. C# will not allow to do this as "class" is a C# keyword. You have to prefix "class" with an @ to fix this.


@Html.RadioButton("status", "1", true, new { id = "status", @class='radio' })


will work.

Problem setting an html attribute containing hyphens in ASP.NET MVC

C# doen't allow you to have a hyphen in the name of a property. For example if you try something like


@Html.TextBox("firstname", "", new { id = "firstname", maxlength = 100, data-val="true", data-val-required="Please enter the first name of the contact." })


It will fail to run.

Try using underscores which should be automatically converted into dashes by the standard HTML helpers:


@Html.TextBox("firstname", "", new { id = "firstname", maxlength = 100, data_val="true", data_val_required="Please enter the first name of the contact." })

Thursday 29 December 2011

Ipconfig syntax

Ipconfig

Displays all current TCP/IP network configuration values and refreshes Dynamic Host Configuration Protocol (DHCP) and Domain Name System (DNS) settings. When used without parameters, ipconfig displays the IP address, subnet mask, and default gateway for all adapters.

Syntax

ipconfig [/all] [/renew [Adapter]] [/release [Adapter]] [/flushdns] [/displaydns] [/registerdns] [/showclassid Adapter] [/setclassid Adapter [ClassID]]

Parameters

/all : Displays the full TCP/IP configuration for all adapters. Without this parameter, ipconfig displays only the IP address, subnet mask, and default gateway values for each adapter. Adapters can represent physical interfaces, such as installed network adapters, or logical interfaces, such as dial-up connections.

/flushdns : Flushes and resets the contents of the DNS client resolver cache. During DNS troubleshooting, you can use this procedure to discard negative cache entries from the cache, as well as any other entries that have been added dynamically.

/displaydns : Displays the contents of the DNS client resolver cache, which includes both entries preloaded from the local Hosts file and any recently obtained resource records for name queries resolved by the computer. The DNS Client service uses this information to resolve frequently queried names quickly, before querying its configured DNS servers.

/registerdns : Initiates manual dynamic registration for the DNS names and IP addresses that are configured at a computer. You can use this parameter to troubleshoot a failed DNS name registration or resolve a dynamic update problem between a client and the DNS server without rebooting the client computer. The DNS settings in the advanced properties of the TCP/IP protocol determine which names are registered in DNS.

/?: Displays help at the command prompt.

Examples



To display the basic TCP/IP configuration for all adapters, type:

ipconfig

To display the full TCP/IP configuration for all adapters, type:

ipconfig /all

To renew a DHCP-assigned IP address configuration for only the Local Area Connection adapter, type:

ipconfig /renew "Local Area Connection"

To flush the DNS resolver cache when troubleshooting DNS name resolution problems, type:

ipconfig /flushdns

How to flush DNS cache in Windows?

To flush DNS cache in Microsoft Windows (Windows 7, Windows XP, Windows ME, Win 2000):-

- Start -> Run -> type cmd

- in command prompt, type ipconfig /flushdns

- Done! Your Windows DNS cache has just been flushed.

Friday 23 December 2011

The C# ?? null coalescing operator

The C# ?? operator provides a nice way to check whether a value is null, and if so return an alternate value.

Simply put, the ?? operator checks whether the value provided on the left side of the expression is null, and if so it returns an alternate value indicated by the right side of the expression. If the value provided on the left side of the expression isn't null, then it returns the original value.

string message = "Welcome";
string result = message ?? "Good Bye";
//outcome: result == "Welcome"

string message = null;
string result = message ?? "Good Bye";
//outcome: result == "Good Bye"

int? age = 21;
int result = age ?? 0;
//outcome: result == 21


int? age = null;
int result = age ?? 0;
//outcome: result == 0

Click here to read more.

Friday 14 October 2011

Why do I receive an "Operation aborted" error message when I visit a Web page in Internet Explorer?

This problem occurs because a child container HTML element contains script that tries to modify the parent container element of the child container. The script tries to modify the parent container element by using either the innerHTML method or the appendChild method.

For example, this problem may occur if a DIV element is a child container in a BODY element, and a SCRIPT block in the DIV element tries to modify the BODY element that is a parent container for the DIV element.

http://support.microsoft.com/kb/927917

Friday 7 October 2011

Calculate last date of given month using JavaScript

<html>
<body>
The end date of this month is
<script type="text/javascript">


//Today
var d = new Date();

//var d = new Date(2011, 10, 1);
//alert(d);

//End date of this month
var d = new Date(d.getFullYear(), d.getMonth() + 1, 0);

//alert(d);

var monthNames = [ 'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December' ];
var endDate = d.getDate() + ' ' + monthNames[d.getMonth()] + ' ' + d.getFullYear();

//alert(endDate);

document.getElementById('prizeDrawEndDate').innerHTML = endDate;

</script>




Click here to try it by copying the script into w3schools try it editor

Friday 5 August 2011

Using Fiddler with HTTPS

By default Fiddler doesn't allow you to view and inspect the details of requests made via HTTPS.

This can be done if you enable "Decryption of HTTPS traffic"

Go to Tools >> Fiddler Options >> Select HTTPS tab >> Select "Decrypt HTTPS traffic" if it is not already selected.

When you select this option Fiddler will popup two warning message boxes, one after the other. First one will say something like "Fiddler generates a root CA certificate to intercept HTTPS traffic". Click "Yes" then it will popup another message box saying "You are about to install a certificate from CA...". Click "Yes" again.

That is it. You can start debugging HTTPS traffic now.

http://www.fiddler2.com/fiddler/help/httpsdecryption.asp

Thursday 4 August 2011

Disable hardware acceleration in Firefox

When dual monitor is used, and firefox is on the second monitor, the Firefox menu doesn't show up. Same happens to the address bar when typing previously visited sites.

If you experience this problem disabling hardware acceleration might fix it.

To disable hardware acceleration in Firefox follow below steps

In the Options window, select the Advanced → General tab.

Then un-check the checkbox labeled "Use hardware acceleration when available".

Click OK

Friday 29 July 2011

jQuery Plug-ins : how to build?

Plugin Authoring Guidelines
http://docs.jquery.com/Plugins/Authoring

Building Your First jQuery Plugin
http://blog.jeremymartin.name/2008/02/building-your-first-jquery-plugin-that.html

A Plugin Development Pattern
http://www.learningjquery.com/2007/10/a-plugin-development-pattern

Wednesday 27 July 2011

Hiding JavaScript code from older browsers

It is straighforward, follow the steps below:

1. Immediately after the opening <script> tag, put a one-line HTML-style comment without the closing characters, so that the first two lines of your script would look like this:

<script language="JavaScript">
<!--


2. At the end of your script, put the following two lines:

//-->
</script>


Thus, your HTML file will contain the following fragment:

<script language="JavaScript">
<!--
Here you put your JS code.
Old browsers will treat it
as an HTML comment.
//-->
</script>

Old browsers will treat your JS code as one long HTML comment. On the other hand, new JavaScript-aware browsers will normally interpret JS code between the tags <script> and </script> (the first and last lines of your JavaScript code will be treated by the JavaScript interpreter as one-line comments).

Tuesday 26 July 2011

Auto-boxing JavaScript primitive types

Primitive Types in JavaScript

Number values, like 1,
string values, like "",
the boolean values true and false,
and the special values null and undefined

Object types in JavaScript

Date objects,
regular expression objects,
function objects,
arrays
and literal objects like {}

Auto-boxing
Whenever you access or assign to a property of a number, string or boolean, a temporary object value (of the Number, String or Boolean class, respectively) is created with the same naked value as the primitive value, but that temporary object is only available to that property access, and does not replace the primitive value that your variable references.

Example

Calling split() on primitive value.


var str = 'primitive-valued string literal';
console.log( str.split(' ') ); //=> obviously ["primitive-valued", "string", "literal"]
str.split = function(){ return 'overridden!'; };
console.log( str.split(' ') ); //=> still ["primitive-valued", "string", "literal"]


Calling split() on String object.


var str = new String( 'primitive-valued string literal' );
console.log( str.split(' ') ); //=> obviously ["primitive-valued", "string", "literal"]
str.split = function(){ return 'overridden!'; };
console.log( str.split(' ') ); //=> "overridden!" that's more like it


Read more >>

Debugging JavaScript using Firebug console

Sometimes the fastest way to find bugs is just to dump as much information to the console as you can. Firebug gives you a set of powerful logging functions that you can call from your own web pages.

console.log

The easiest way to write to the Firebug console looks like this: console.log("hello world")

You can pass as many arguments as you want and they will be joined together in a row, like console.log(2,4,6,8,"foo",bar).

Logging object hyperlinks

console.log and its related functions can do a lot more than just write text to the console. You can pass any kind of object to console.log and it will be displayed as a hyperlink. Elements, functions, arrays, plain ol' objects, you name it. Clicking these links will inspect the object in whatever tab is most appropriate.

String formatting

console.log can format strings in the great tradition of printf. For example, you can write console.log("%s is %d years old.", "Bob", 42).

Color coding

In addition to console.log, there are several other functions you can call to print messages with a colorful visual and semantic distinction. These include console.debug, console.info, console.warn, and console.error.

console.log() and older browsers



You can write a script which creates console functions if they don't exist. For example following script can be used to alert the given value when console.log() is unavailable.


<script type="text/javascript">

if (!window.console) console = {};
console.log = console.log || function(s){alert(s)};

console.log('testing')

</script>



Click here to read more

JavaScript For...In Statement

The for...in statement loops through the properties of an object.

Syntax


for (variable in object)
{
//code to be executed
}


Note: The code in the body of the for...in loop is executed once for each property.

Example

Looping through the properties of an object:


<script type="text/javascript">

var person={fname:"prince",lname:"thomas",age:30};

for (var property in person)
{
document.write(property + ": " + person[property] + "<br>");
}
</script>


The output will be

fname: prince
lname: thomas
age: 30

Friday 22 July 2011

What is "this" in jQuery?

When is this a DOM element?

The short answer is - usually. Scripting with jQuery quite often involves the use of callback functions. Whether handling an event, iterating a collection of nodes, animating an image, or applying a dynamic filter, callbacks are used to invoke your custom code at the appropriate time. To make things easy for you, jQuery sets the scope of the callback function to the element which is the subject of the callback. For example, when we want to handle a mouse click event for an element we bind a handler function to the event like so:


$('#myButton').bind('click', function() {

// our code to handle the click event goes

// here, in the callback function

});


When a user clicks the 'myButton' element, jQuery invokes the callback function that was passed to the bind method. But when it invokes our callback it sets the current scope to the DOM element that initiated the event, in this case the 'myButton' element. jQuery does this as a convenience. The object you are most likely to need in the event callback is the element that triggered the event. And what easier way to have access to it than by using the this keyword? So within the callback function it can be assumed that this is the relevant DOM element.

Converting this to $this

When this is a DOM element it is often in the context of code that needs to access or manipulate it in some way. This, of course, is something that jQuery excels at. So how do we use the power of the jQuery API when this is a DOM element? Just turn this into $this:


$('div').each(function() {

// 'this' is a DOM element

// wrap 'this' in a jQuery object

var $this = $(this);

// now we have the full jQuery API at our disposal

var title = $this.attr("title");

if (title != null)

$this.prepend("<h2>" + title + "</h2>");

});


Click here to read more

Setting multiple CSS attributes at a time using jQuery

This can be done by passing a comma seperated list of "attributeName:value" pairs to the .css() jQuery method.

Syntax

.css({ attributeName-1:"value",attributeName-2:"value",...attributeName-N:"value" })

For example to the following line sets the font-family and font-size of all paragraphs in the page.

$("p").css({fontFamily:"verdana", fontSize:"25px", color:"green"});

This can also be aschieved by the following script.


$("p").css("fontFamily","verdana");
$("p").css("font-size",25);
$("p").css("color","green");

jQuery .css("height") and .height()

The difference between .css('height') and .height() is that the latter returns a unit-less pixel value (for example, 250) while the former returns a value with units intact (for example, 250px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation.

jQuery height() vs outerHeight()

.height()
Get the current computed height for the first element in the set of matched elements. This does not include the padding, border and margin.

.outerHeight([includeMargin])
Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin.

"includeMargin" is a optional boolean indicating whether to include the element's margin in the calculation.

$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document

$("#IdofYourDIV").height(); // returns height of "IdofYourDIV" excluding padding, border and margin

$("#IdofYourDIV").outerHeight(); // returns height of "IdofYourDIV" including padding and border but excluding margin

$("#IdofYourDIV").outerHeight(true); // returns height of "IdofYourDIV" including padding, border and margin

Getting selected text from DropDownList using jQuery

Try

$("#IDofYOurDropDownList option:selected").text();

$("#IDofYOurDropDownList").text() will return you all the "text" values of the dropdown list.

BUT

$("#IDofYOurDropDownList").val(); will give you the selected value.

Wednesday 20 July 2011

Iterating an Array using jQuery each() method

Try the below JavaScript code.



var arr = ['a','b','c'];

$.each(arr, function(index, obj) {
// 'this' is the object of the current iteration
alert(this);
//This will alert a or b or c in each iteration
});

$(arr).each(function(index, obj) {
// 'obj' is the object of the current iteration
alert(obj);
//This will alert a or b or c in each iteration
});

jQuery eq(index) method

Reduce the set of matched elements to the one at the specified index.

index is an integer indicating the 0-based position of the element.When index is a -ve value, counting is done backwards from the last element in the set.

Consider a page with a simple list on it:

<ul>
<li>list item 1
<li>list item 2
<li>list item 3
<li>list item 4
<li>list item 5
</ul>

We can apply this method to the set of list items:

$('li').eq(2).css('background-color', 'red');

he result of this call is a red background for item 3. Note that the supplied index is zero-based, and refers to the position of the element within the jQuery object, not within the DOM tree.

Providing a negative number indicates a position starting from the end of the set, rather than the beginning. For example:

$('li').eq(-2).css('background-color', 'red');

This time list item 4 is turned red, since it is two from the end of the set.

Triggering an event handler only for the first occurance of an event using jQuery one()

This method is identical to .bind(), except that the handler is unbound after its first invocation. For example:

$("#bob").one("click", function() {
alert("This will be displayed only once.");
});



After the code is executed, a click on the element with ID "bob" will display the alert. Subsequent clicks will do nothing. This code is equivalent to:

$("#bob").bind("click", function( event ) {
alert("This will be displayed only once.");
$(this).unbind( event );
});



In other words, explicitly calling .unbind() from within a regularly-bound handler has exactly the same effect.

jQuery 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 ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\. For example, if you have an element with id="foo.bar", you can use the selector $("#foo\\.bar").

All Selector jQuery('*')
Selects all elements.

Attribute Equals Selector [name="value"]
Selects elements that have the specified attribute with a value exactly equal to a certain value.
$('input[type="radio"]') //selects all radio buttons in the document

Attribute Starts With Selector [name^="value"]
Selects elements that have the specified attribute with a value beginning exactly with a given string.
$('div[id^="inputfield"]') //selects all DIVs whose id starts with "inputfield"

Child Selector (“parent > child”)
Selects all direct child elements specified by "child" of elements specified by "parent".
$("div.inputfield > input.ageBox") //select all input fields with class "ageBox" within DIVs with class "inputfield"

Descendant Selector (“ancestor descendant”)
Selects all elements that are descendants of a given ancestor.
$("form input") //selects all input field in the form

Class Selector (“.class”)
Selects all elements with the given class.

Element Selector (“element”)
Selects all elements with the given tag name

ID Selector (“#id”)
Selects a single element with the given id attribute.

Has Attribute Selector [name]
Selects elements that have the specified attribute, with any value.
$('div[id]') //Selects all DIVs with Ids

:first-child Selector
Selects all elements that are the first child of their parent. While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

$("div span:first-child").css("text-decoration", "underline")

last-child selector
Selects all elements that are the last child of their parent.While :last matches only a single element, :last-child can match more than one: one for each parent.

Multiple Attribute Selector [name="value"][name2="value2"]
$('input[id][name$="address"]') //Finds all inputs that have an id attribute and whose name attribute ends with "address"

Multiple Selector (“selector1, selector2, selectorN”)
Selects the combined results of all the specified selectors.

Click here to read more about jQuery selectors from jQuery API

Trying jQuery in W3Schools TryIt Editor

Click here to open W3Schools TryIt Editor

Copy and paste the below html into the editor. Cick "Edit and Click Me>>" button on top to see the result. Now you can add your own HTML and JavaScript and test it.

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script language="javascript">

//alert(jQuery);

$(document).ready(function () {

alert($('div').length);

});
</script>

</head>

<body>

<div>Test1</div>
<div>Test2</div>

</body>
</html>

Monday 18 July 2011

DateAdd JavaScript function

The following JavaScript function can be used to add the given "duration" to the given "datepart" i.e. "day", "month" or "year". See the example calls and return values and the actual function definition below.


document.write(DateAdd('1/1/2011', 10, 'day')); //returns 11/01/2011
document.write(DateAdd('1/1/2011', 10, 'month')); //returns 31/10/2011
document.write(DateAdd('1/1/2011', 10, 'year')); //returns 31/12/2020
document.write(DateAdd('1/3/2011', 1, 'year')); //returns 29/02/2012

function DateAdd(startDate, duration, datepart)
{
var day = startDate.split("/")[0];
var month = startDate.split("/")[1];
var year = startDate.split("/")[2];

if (typeof (datepart) != "undefined")
{
switch(datepart.toLowerCase())
{
case "year":
year = Number(year) + duration; day = Number(day) - 1;
break;
case "month":
month = Number(month) + duration; day = Number(day) - 1;
break;
case "day":
day = Number(day) + duration;
break;
}
}

var endDate = new Date(year, month - 1, day);
//Month starts from 0. 0 is Jan, 11 is Dec


/*new Date(2012, 0, 0) -- returns 31/Dec/2011
new Date(2012, 1, 0) -- returns 31/Jan/2012
new Date(2012, 1, -1) -- returns 30/Jan/2012
new Date(2012, 13, 1) -- returns 1/Feb/2013
*/


day = endDate.getDate();
month = endDate.getMonth() + 1;
year = endDate.getFullYear();

day = ((day + "").length == 1) ?
("0" + (day + "")) : (day + "");
month = ((month + "").length == 1) ?
("0" + (month + "")) : (month + "");

return ( day + "/" + month + "/" + year );
}



You might be also interested in DateDiff() function which can be used to find the difference in days between 2 given dates.

Friday 15 July 2011

Creating PDF Documents with ASP.NET and iTextSharp

The Portable Document Format (PDF) is a popular file format for documents. Due to their ubiquity and layout capabilities, it's not uncommon for a websites to use PDF technology. For example, an eCommerce store may offer a "printable receipt" option that, when selected, displays a PDF file within the browser.

This article on www.4guysfromrolla.com investigates iTextSharp, a .NET open source library for PDF generation, showing how to use iTextSharp to create PDF documents from scratch. It starts with an example of how to programmatically define and piece together paragraphs, tables, and images into a single PDF file. Following that, it explores how to use iTextSharp's built-in capabilities to convert HTML into PDF.

Click here to read the article



Filling in PDF Forms with ASP.NET and iTextSharp

What is iTextSharp


iText# (iTextSharp) is a port of the iText open source java library for PDF generation written entirely in C# for the .NET platform.

Click here to DOWNLOAD iTextSharp

Wednesday 13 July 2011

Setting "nowrap" using CSS white-space property

To achieve the same results as a TD nowrap (<td nowrap="true">) using cascading style sheets, use the following:

white-space: nowrap;

white-space
The white-space property specifies how white-space inside an element is handled.

Property values
normal, nowrap, pre, pre-line, pre-wrap, inherit

JavaScript syntax: object.style.whiteSpace="nowrap"

Please note that replacing white spaces by " " does the job, too. "nbsp" means "Non Breakable SPace".

Sample code

Example 1.
<table id="mytable">
<tr><td></td><td></td></tr>
</table>

CSS

table#mytable tr td{white-space:nowrap;}

Example 2.
<table>
<tr class="nowrap">
<td></td>
<td></td>
</tr>
</table>

CSS:

tr.nowrap { white-space:nowrap; }

td { white-space:inherit; }

OR

tr.nowrap td {white-space:nowrap;}

Debuggging Javascript using developer tools in IE8

We can now debug Javascript with the developer tool bar plugins integreted in IE8 and IE9.

Follow these steps

1. Open developer tools bar (From Tools menu OR by pressing F12)
2. Click on "Script" tab
3. Click on "Start Debugging"

Now you can set breakpoints, use watch to inspect variables during runtime, see call stack etc ...

Debugging JavaScript using Firebug

FireFox add-on Firebug comes with built-in JavaScript debugger. Click here for the details.

What is Firebug?

Firebug integrates with Firefox to put a wealth of web development tools at your fingertips while you browse. You can edit, debug, and monitor CSS, HTML, and JavaScript live in any web page.

Tuesday 12 July 2011

parseInt('08') returns 0 with Javascript

I came across a rather interesting problem with the Javascript parseInt() function a couple of days ago; if the value is a zero padded string and is '08' or '09' then parseInt() will return 0.

parseInt('08') returns 0

The leading zero in the string tells the Javascript engine that it is an octal number. Because 8 and 9 are not valid numbers in octal, parseInt returns 0. This is expected behaviour because they are not valid octal integers and parseInt returns 0 because the first valid number encountered is a zero.

The solution

After a quick bit of research when I had this problem, I discovered the parseInt function has an optional 'radix' parameter which specifies the base to use. By passing 10 as the base it solves the leading 0 issue, for example:

alert( parseInt('08', 10) );

will show the number 8 in an alert dialog, whereas:

alert( parseInt('08') );

would display 0.

Conclusion

To be on the safe side it's probably always a good idea to pass the radix parameter to the parseInt function to ensure the values returned are what you expect them to be, especially if they might contain leading zeroes.

Friday 8 July 2011

jQuery AJAX slow in Firefox, fast in IE

This is true when you run the application from Visual Studio. Try after creating an IIS application or deploying to your developement server.

jQuery Each() Method

The jQuery library provides a method, Each(), which will loop through each element of the target jQuery object.


$( "#selector" ).each(

// For each item in the "selector", run this code. The "index" is the
// loop iteration index on the current element.
function( index ){

// Bind the onclick event to simply alert the
// iteration index value.
$( this ).bind (
"click",
function(){
alert( intIndex + " of " + $( "#selector" ).length);
}
);
}
);

Thursday 7 July 2011

CSS Image Opacity / Transparency

The CSS3 syntax for transparency is opacity:x

where x can be a value from 0.0 - 1.0. A lower value makes the element more transparent.

Image Transparency - Mouseover Effect



<img src="yourimage.jpg" style="opacity:0.4;"
onmouseover="this.style.opacity=1;"
onmouseout="this.style.opacity=0.4;" />

Click here to see the W3Schools.com example

How to get MonthName from DateTime in C#?

Following syntax can be used to get month name from current date

4 letter format
DateTime.Now.ToString( "MMMM" )

3 letter format
DateTime.Now.ToString( "MMM" )

string CurrentMonth = String.Format("{0:MMMM}", DateTime.Now).ToString();


Click here for more custom DateTime format strings

C# method to turn first letter to upper case

Can be done in different ways.


private string TurnFirstLetterToUpper(string s)
{
string firstLetter = s.Substring(0,1);
return firstLetter.ToUpper() + s.Remove(0,1);
}



Response.Write(TurnFirstLetterToUpper("programming")); //Ouput: Programming


Another one


string s = "coding";
string firstLetter = s.Substring(0, 1);
s= s.Replace(firstLetter, firstLetter.ToUpper()); //You should be careful while doing this, bcs String.Replace() will replace all the occurances of "firstLetter" in "s"

Response.Write(s); //Ouput: Coding


String.Replace(string,string):
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

String.Remove(int,int):
Deletes a specified number of characters from the string beginning at a specified position.

Tuesday 5 July 2011

Calculate DateDiff using JavaScript

This script will let you know how long you have to wait for the New Year

<script type="text/javascript">

//Set the two dates
var today = new Date();

var endofyear =new Date(today.getFullYear(), 11, 31); //Month is 0-11 in JavaScript

if (today.getMonth()==11 && today.getDate()==31)
alert("Happy New Year " + today.getFullYear()+1);
else
{
//Set 1 day in milliseconds
var one_day=1000*60*60*24;

//Calculate difference btw the two dates, and convert to days
alert(Math.ceil((endofyear.getTime()-today.getTime())/(one_day))+
" days left until New Year!");
}
</script>

You might be also interested in DateAdd() function which can be used to add day/month/year to give date.

Generic IComparer to sort strings alphabetically

Sorting a list is one of the common tasks for a developer. It is handy to have a generic function to do this. See the example below. It sorts the employees by their name.


class Employee
{
public string Name { get; set; }
public string Email{ get; set; }
}

//Create Employee List
List<Employee> employees = new List<Employee>();
Employee emp = new Employee();
emp.Name = "Joe";
emp.Email= "joe@somewhere.com";
employees.add(emp);

emp = new Employee();
emp.Name = "Bell";
emp.Email= "bell@somewhere.com";
employees.add(emp);

//Sort Employee List albhabetically
employees.Sort(new GenericComparer());

//Generic IComparer to do the sorting
public class GenericComparer : IComparer<object>
{
public int Compare(object x, object y)
{
System.Collections.CaseInsensitiveComparer c = new System.Collections.CaseInsensitiveComparer();

if (x is Employee && y is Employee)
return c.Compare(((Employee)x).Name, ((Employee)y).Name);
else
throw new ArgumentException();
}
}

//You can replace the CaseInsensitiveComparer.Compare() call with the following line if you want to do a case-sensitive search
return string.Compare(((Employee)x).Name, ((Employee)y).Name);


Assume you have another List where Department is


class Department
{
public string Name { get; set; }
}


It will be handy if you can write something like the below line to sort the department list similar to the employee list.


departmentList.Sort(new GenericComparer());


Not a biggie. Just modify the Compare() function.


public int Compare(object x, object y)
{
System.Collections.CaseInsensitiveComparer c = new System.Collections.CaseInsensitiveComparer();

if (x is Employee && y is Employee)
return c.Compare(((Employee)x).Name, ((Employee)y).Name);
//Below condition is new
else if (x is Department&& y is Department)
return c.Compare(((Department)x).Name, ((Department)y).Name);
else
throw new ArgumentException();
}


Then you should be able to sort the department list successfully by calling
departmentList.Sort(new GenericComparer());

Thursday 30 June 2011

Detecting Google Chrome using JavaScript

You can detect Chrome by using the following bit of JavaScript:


var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;


The following string represents Chrome's full user agent:

User-agent header sent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.112 Safari/534.30

Friday 24 June 2011

CSS3 overflow-y Property

This can be used to clip the contents of a DIV element when the content overflows the element's content area.

Example

div
{
overflow-y:scroll;
}

The overflow-y property specifies whether or not to clip the top/bottom edges of the content - if it overflows the element's content area.

Tip: Use the overflow-x property to determine clipping at the left and right edges.
Default value: visible
JavaScript syntax: object.style.overflowY="scroll"

Syntax
overflow-y: visible|hidden|scroll|auto|no-display|no-content;

Click here to play with it using W3Schools Try it editor

Shelve and Unshelve Pending Changes in TFS

Shelving enables you to set aside the pending changes in your workspace to work on a higher priority task or to share your code with another user for code review.

Perform a Get Latest operation to synchronize your workspace with the latest server version and then build your application to ensure that it compiles prior to shelving or checking in. Doing so gives you an opportunity to incorporate changes to source files that have been made outside of your workspace.


To shelve folders and files from Source Control Explorer


1. In Source Control Explorer, right-click, and click Shelve Pending Changes.
2. In the Shelve - Source Files dialog box, type the shelveset name, for example shelvetest in the Shelveset name box.
3. In the Comment box, type Testing my shelveset, and then click Shelve.

The files and folders are copied to the source control server and are available for other team members to unshelve.

To shelve folders and files from Solution Explorer

1.In Solution Explorer, right-click, and click Shelve Pending Changes.
2.In the Shelve - Source Files dialog box, type the shelveset name, for example shelvetest in the Shelveset name box.
3.In the Comment box, type Testing my shelveset and then click Shelve.

The files and folders are copied to the source control server and are available for other team members to unshelve.

To shelve pending changes from the Pending Changes window

1.In the Visual Studio 2005 Team System integrated development environment (IDE), click View, Other Windows, and then click Pending Changes.
2.In the Pending Changes window, click Source Files, and then select the files you want to shelve.
3.Click Work Items, and then add or remove work items.
4.Select or clear the Preserve Pending Changes Locally box.

Unshelving



When you unshelve a shelveset, Team Foundation restores each shelved revision into the destination workspace as a pending change as long as the revision does not conflict with a change that is already pending in the workspace.

You can use the unshelve command to restore individual file revisions from a shelveset to your workspace, but unshelving does not restore your entire workspace to the base workspace version, which is the server version upon which a shelved revision is based. After unshelving, perform one of the following operations to guard against the introduction of chronological inconsistencies in your code.
To unshelve a set of pending changes

1.In Visual Studio 2005 Team System, click File, point to Source Control, and then click Unshelve.
2.In the Owner name box, type the shelveset creator's name (for example, ADVENTUREWORKS\JuanGo or simply juango) and then click Find.
3.In the Results pane, select the shelveset you want to unshelve into your workspace, and then click Details.
4.If you want to delete the shelveset from the Team Foundation source control server, deselect the Preserve shelveset on server option.
5.Optionally deselect the Restore work items and check-in notes option if you do not want to have the work items and check-in notes associated with the shelveset restored.
6.When the Details dialog box appears, select the shelveset or shelveset items you want to unshelve into your workspace, and then click Unshelve.

Unlike the Get operation, which merges reconcilable differences between two versions of a file automatically and helps you merge conflicts manually, the unshelve operation does not support merges. By removing shelved pending changes from your workspace at the commencement of the code review, you can be assured that any changes your reviewer makes to the shelveset, such as adding comments to a file, do not create merge conflicts during the unshelve process.

source: MSDN

Thursday 23 June 2011

What is Denial-of-service (DoS) attack?

A denial-of-service attack (DoS attack) or distributed denial-of-service attack (DDoS attack) is an attempt to make a computer resource unavailable to its intended users. Although the means to carry out, motives for, and targets of a DoS attack may vary, it generally consists of the concerted efforts of person or persons to prevent an Internet site or service from functioning efficiently or at all, temporarily or indefinitely. Perpetrators of DoS attacks typically target sites or services hosted on high-profile web servers such as banks, credit card payment gateways, and even root nameservers. The term is generally used with regards to computer networks, but is not limited to this field; for example, it is also used in reference to CPU resource management.

One common method of attack involves saturating the target machine with external communications requests, such that it cannot respond to legitimate traffic, or responds so slowly as to be rendered effectively unavailable. In general terms, DoS attacks are implemented by either forcing the targeted computer(s) to reset, or consuming its resources so that it can no longer provide its intended service or obstructing the communication media between the intended users and the victim so that they can no longer communicate adequately.

Denial-of-service attacks are considered violations of the IAB's (Internet Architecture Board) Internet proper use policy, and also violate the acceptable use policies of virtually all Internet service providers. They also commonly constitute violations of the laws of individual nations.

Symptoms and manifestations



The United States Computer Emergency Readiness Team (US-CERT) defines symptoms of denial-of-service attacks to include:

* Unusually slow network performance (opening files or accessing web sites)
* Unavailability of a particular web site
* Inability to access any web site
* Dramatic increase in the number of spam emails received—(this type of DoS attack is considered an e-mail bomb)

Denial-of-service attacks can also lead to problems in the network 'branches' around the actual computer being attacked. For example, the bandwidth of a router between the Internet and a LAN may be consumed by an attack, compromising not only the intended computer, but also the entire network.

If the attack is conducted on a sufficiently large scale, entire geographical regions of Internet connectivity can be compromised without the attacker's knowledge or intent by incorrectly configured or flimsy network infrastructure equipment.

Methods of attack



A "denial-of-service" attack is characterized by an explicit attempt by attackers to prevent legitimate users of a service from using that service. There are two general forms of DoS attacks: those that crash services and those that flood services.[3] Attacks can be directed at any network device, including attacks on routing devices and web, electronic mail, or Domain Name System servers.

A DoS attack can be perpetrated in a number of ways. The five basic types of attack are:

1. Consumption of computational resources, such as bandwidth, disk space, or processor time.
2. Disruption of configuration information, such as routing information.
3. Disruption of state information, such as unsolicited resetting of TCP sessions.
4. Disruption of physical network components.
5. Obstructing the communication media between the intended users and the victim so that they can no longer communicate adequately.

A DoS attack may include execution of malware intended to:

* Max out the processor's usage, preventing any work from occurring.
* Trigger errors in the microcode of the machine.
* Trigger errors in the sequencing of instructions, so as to force the computer into an unstable state or lock-up.
* Exploit errors in the operating system, causing resource starvation and/or thrashing, i.e. to use up all available facilities so no real work can be accomplished.
* Crash the operating system itself.

source: wikipedia

Click here to read more.

Monday 20 June 2011

Open up hidden HTML DIV using jQuery

On of the Web UIs which I have worked on recenlty had a requirement to open-up a DIV when it is hidden and show a message to the user in response to a button click (it can be any other user action). I did it using the following code


if ($("#div").is(":hidden")) {
$("#div").slideDown('slow', function () {
alert("Your message goes here");
}
);


$("#div").is(":hidden") returns true or false depending on the DIVs visibility.

Handling WCF Exceptions from ASPX page

If a WCF method fails when you call it from your ASPX page you might want to save the exception details somewhere, in a database table or in a text/xml file, or output it in the browser. But how will you get the details of the WCF exception in your ASP.NET code-behind class? You may find the following code snippet useful.


string serviceStackTrace = "";

try
{
//WCF method call
}
catch(Exception ex)
{
if (ex is FaultException)
serviceStackTrace = ((System.ServiceModel.FaultException)(ex)).Detail.StackTrace;
else if (ex is System.ServiceModel.CommunicationException)
serviceStackTrace = ex.StackTrace;
}

//Do whatever you want to do with serviceStackTrace

Thursday 16 June 2011

CSS Sprites: What, Why and How?


  • A sprite image is a collection of images put into a single image.

  • A web page with many images can take a long time to load and generates multiple server requests.

  • Using image sprites will reduce the number of server requests and save bandwidth.


The name "sprite" might be a little misleading, because sprites aren't little images like you might be picturing, a sprite is actually one big image. Have you ever seen the CSS technique where the "on" and "off" states of a button are contained within the same image and are activated by shifting the background-position?

Think of CSS Sprites as an extension of that technique. The difference is that instead of just two or three images being combined into one, you can combine an unlimited number of images into one. The origin of the term "sprites" comes from old school computer graphics and the video game industry. The idea was that the computer could fetch a graphic into memory, and then only display parts of that image at a time, which was faster than having to continually fetch new images. The sprite was the big combined graphic. CSS Sprites is pretty much the exact same theory: get the image once, shift it around and only display parts of it, saves the overhead of having to fetch multiple images.

Why combine all those images? Isn't it quicker to have smaller images?

Nope, it's not. Back in the day, everybody and their brothers were "slicing" images to make pages load faster. All that technique did was fool the eye to make it look like the page was loading faster by loading bits and pieces all over at once. Each one of those images is a separate HTTP-Request, and the more of those, the less efficient your page is.

The impact of having many components((i.e. images, scripts, and stylesheets) in the page is exacerbated by the fact that browsers download only two or four components in parallel per hostname, depending on the HTTP version of the response and the user's browser. Our experience shows that reducing the number of HTTP requests has the biggest impact on reducing response time and is often the easiest performance improvement to make.

Every single image, whether it's an tag or an background-image from your CSS is a separate HTTP-Request, so you can imagine how quickly those requests can wrack up.

Here is an example from w3schools.com which creates a navigation list using the below sprite image



CSS

<style type="text/css">

#navlist{position:relative;}

#navlist li{margin:0;padding:0;list-style:none;position:absolute;top:0;}

#navlist li, #navlist a{height:44px;display:block;}

#home{left:0px;width:46px;background:url('img_navsprites.gif') 0 0;}

#prev{left:63px;width:43px;background:url('img_navsprites.gif') -47px 0;}

#next{left:129px;width:43px;background:url('img_navsprites.gif') -91px 0;}
</style>

HTML

<ul id="navlist">
<li id="home">
<li id="prev">
<li id="next">
</ul>

Example explained:

* #navlist{position:relative;} - position is set to relative to allow absolute positioning inside it
* #navlist li{margin:0;padding:0;list-style:none;position:absolute;top:0;} - margin and padding is set to 0, list-style is removed, and all list items are absolute positioned
* #navlist li, #navlist a{height:44px;display:block;} - the height of all the images are 44px

* #home{left:0px;width:46px;} - Positioned all the way to the left, and the width of the image is 46px
* #home{background:url(img_navsprites.gif) 0 0;} - Defines the background image and its position (left 0px, top 0px)

* #prev{left:63px;width:43px;} - Positioned 63px to the right (#home width 46px + some extra space between items), and the width is 43px.
* #prev{background:url('img_navsprites.gif') -47px 0;} - Defines the background image 47px to the right (#home width 46px + 1px line divider)

* #next{left:129px;width:43px;}- Positioned 129px to the right (start of #prev is 63px + #prev width 43px + extra space), and the width is 43px.
* #next{background:url('img_navsprites.gif') no-repeat -91px 0;} - Defines the background image 91px to the right (#home width 46px + 1px line divider + #prev width 43px + 1px line divider )

See it working on w3schools.com

Wednesday 15 June 2011

Rounded corners in CSS

As a Web Developer you might have come across a requirement where you have to display the content in a box with rounded corners instead of showing it in a square box. If yes here is an example which allows you do it using CSS and few images.



In the spot where you want the rounded box to show up create a container div to hold the box, a div for the top row and a div for the bottom row. Between the top and bottom rows add your content. In the top and bottom row divs, I add the left corner image and set the inline style to display: none;. This makes the image invisible unless you make it visible through the stylesheet. That way you can hide the effect from incompatible browsers by not showing them the stylesheet.

<div class="roundcont">
<div class="roundtop">
<img src="tl.gif" alt=""
width="15" height="15" class="corner"
style="display: none" />
</div>

<p>Your content gos here</p>

<div class="roundbottom">
<img src="bl.gif" alt=""
width="15" height="15" class="corner"
style="display: none" />
</div>
</div>

The CSS sets the width and background color of the container object and the color of the text inside. The margins on interior paragraphs are set so that the text doesn’t sit right up against the edge of the box.

Then the top and bottom divs are given a background image that contains the right corner images and the left corner images from the HTML code are enabled.

.roundcont {
width: 250px;
background-color: #f90;
color: #fff;
}

.roundcont p {
margin: 0 10px;
}

.roundtop {
background: url(tr.gif) no-repeat top right;
}

.roundbottom {
background: url(br.gif) no-repeat top right;
}

img.corner {
width: 15px;
height: 15px;
border: none;
display: block;
}

if you want you can also set the width of "roundcont" to 100%.

Corner images :



Also if you are more concerned about the number of images(I mean performance optimisation or something like that) you can combine the corner images into a CSS sprite and modify CSS accordingly.


Click here to download the corner images and read the whole article

CSS z-index - how it works?

z-index goes hand-in-hand with the local stacking context. What is a stacking context? Whenever you specify a z-index, you create a new stacking context. Here's an example:

CSS:

body {
margin: 0;
padding: 0;
}
/* generic style */
div.tile {
position: absolute;
border: 1px solid black;
background: white;
width: 4em;
height: 4em;
}
/* box One */
.a {
top: 0;
left: 0;
}
/* box Two */
.b {
top: 1em;
left: 1em;
}
/* box Three */
.c {
top: 2em;
left: 2em;
z-index: -1;
}
/* box Four */
.d {
top: 3em;
left: 3em;
}
/* box Five */
.e {
top: 4em;
left: 4em;
}

HTML

<div style="position: absolute; z-index: 0;">
<div class="tile a">One</div>
<div class="tile b">Two</div>
<div class="tile c">Three</div>
<div class="tile d">Four</div>
</div>
<div class="tile e">Five</div>

So here we have three stacking contexts, the root of the document (<html>), the plain div, and box Three (.c).

When you specify a z-index, that z-index is the offset relative to the current stacking level.

When the z-index on the plain div is 0, boxes One, Two, Four, and Five stack on top of each other sucessively. Since box Three has a negative z-index it is rendered behind boxes One, Two, and Four, and Five. The stacking order from bottom to top is: 3, 1, 2, 4, 5

If you give the z-index on the plain div a 1, boxes One, Two, Three and Four are rendered in front of box Five (change the position and size of box five, go ahead), but box Three is rendered behind boxes One, Two, and Four, due to its negative z-index. The stacking order from back to front is: 5, 3, 1, 2, 4

If you remove the z-index on the plain div, boxes One, Two, Four, and Five are rendered sucessively on top of each other, and box Three is rendered behind the root stacking context (the html element) and cannot be seen. The stacking order from bottom to top is: 3, root, 1, 2, 4, 5)

CSS Version: CSS2

JavaScript syntax: object.style.zIndex="1"

click here to read the original document.

Read about z-index on wwww.w3schools.com

wwww.w3schools.com example

You can also copy the above CSS and HTML to wwww.w3schools.com "Try It" editor and play with it.

Friday 10 June 2011

Liquid Canvas - jQuery plugin to create rounded corners

Liquid Canvas is a JavaScript library which allows you to draw inside an HTML canvas element with an easy yet powerful description language.

It can be used to add graphics to your web page without ever touching an image creation tool such as The Gimp, Inkscape or Photoshop.

Click here to see the Demo page

The demo is a good way to find out what Liquid Canvas can do for you.

Features

* Automatic generation of HTML canvas elements which scale with their HTML container, e.g. a floating DIV
* Abstraction of canvas - each HTML element gets a "paint" method
* Works with plugins for rendering
* Loads of plugins already exist
* Own plugins are possible
* Simplified render language for plugin-based rendering
* Rendering language uses a CSS-like syntax for plugin styles
* Based on HTML Canvas, jQuery, ExplorerCanvas
* Tested on Firefox, Internet Explorer, Safari, Chrome

Wednesday 8 June 2011

Simple JavaScript function to create TimeStamp from Date()

function dateTimeStamp()
{
return (new Date().toLocaleString()+':'+new Date().getMilliseconds());
}

if you call the above method output will be something like
08 June 2011 17:29:04:605

toLocaleString()
Converts a Date object to a string, using locale conventions

getMilliseconds()
Returns the milliseconds (from 0-999)

If you are looking for a milliseconds version of the Date objects then you have to use Date.getTime() which returns the number of milliseconds since midnight Jan 1, 1970.

Click here for a complete list of JavaScript Date Object Methods

Friday 3 June 2011

Generic jQuery method to attach a querystring value to all the links in a page

Ever wondered how to attach a querystring, which exist in the original request, to all the requests made by hypertext link (<a> tag) clicks in an ASPX page. See below script.

$(document).ready(function () {
$('a').click(function (event) {

var $a = $(this);

//Add quesrystring if it is a relative URL and the querystring is not part of the href value already
var appendqstring = $a.attr("href").toLowerCase().indexOf("http://") == -1 && $a.attr("href").toLowerCase().indexOf("https://") == -1 &&
$a.attr("href").toLowerCase().indexOf(".aspx") != -1 && $a.attr("href").toLowerCase().indexOf("qs=") == -1;

if (appendqstring ) {
event.preventDefault();
location.href = $a.attr("href") + "?qs=" + GetQStringVal("qs");
}
});
});

/* function to read value of the given key, x, from querystring */
function GetQStringVal(x) {
var a = location.search.substring(1); var b = a.split("&");
for (var i = 0; i < b.length; i++) {
var c = b[i].split("=");
if (c[0].toLowerCase() == x.toLowerCase()) { return c[1]; }
}
return "";
}

Resizing JavaScript pop-up windows to make use of the whole screen width and height

In theory the following line has to do it.

window.resizeTo(screen.width, screen.height);

But for some reason this does not work in IE. If you call window.moveTo(0,0) before calling resizeTo() it works.

I.e. if you add the following JavaScript lines in your page which is opened in a pop-up it will be resized to the screen width and height when the page is loaded.

window.moveTo(0,0);
window.resizeTo(screen.width, screen.height);

Tuesday 10 May 2011

Serializing DateTime values using JavaScriptSerializer class

As you know .NET Framework's System.Web.Script.Serialization.JavaScriptSerializer class can be used to to do C# to JSON serialization and JSON to C# deserialization. When JavaScriptSerializer serializes a DateTime into a JSON string it uses the Local DatetimeKind, unless otherwise specified while creating the DateTime, resulting in a potential problem while deserializing it. The reason is AJAX framework deserializes DateTime value assuming its Kind property is set to Utc format. So if the serialized DateTime is created using a different DateTimeKind deserialization will produce a different DateTime value.

For example assume your Local is GMT+1 and you have serialized the DateTime value "15-May-2011 00:00:00" using JavaScriptSerializer and passed it to a WCF method where you deserialize it. Here deserialization will produce a DateTime with the value "14-May-2011 23:00:00". This is because deserialization assumes the value is serialized using Utc DateTimeKind, which is nothing but GMT time, and it uses the same DateTimeKind.Utc to deserialize it. So it results in a DaTime value which is one hour (remember the Local is GMT+1) less than the original value.

The fix is do something similar to below code snippet before serializing which will make sure DateTimeKind.Utc will be used for serializing the value.

DateTime departureDate = DateTime.SpecifyKind(value, DateTimeKind.Utc);

And finally you will get the correct value after deserialzation in the WCF method or wherever you do it.

Click here to read more.

Wednesday 4 May 2011

How to check whether an element is visible or not using jQuery

jQuery(':visible') - Selects all elements that are visible.

Elements can be considered hidden for several reasons:

* They have a CSS display value of none.
* They are form elements with type="hidden".
* Their width and height are explicitly set to 0.
* An ancestor element is hidden, so the element is not shown on the page.

Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout. During animations that hide an element, the element is considered to be visible until the end of the animation. During animations to show an element, the element is considered to be visible at the start at the animation.

Below JavaScript is useful if you need to know if a specific object is visible:

if ( $('#elementid').is(':visible')){
// element is visible, do something
}

OR

if ($('#elementid:visible').length > 0){
// element is visible, do something
}

Thursday 21 April 2011

DropDownList.FindByText() case in-sensitive

The default behavior of FindByText() and FindByValue() of ListBox is case sensitive. You have to write your own code to do a case-insensitive search against any list box. One of the UIs which I was working on recently had a country list box where "United Kingdom" had to be selected by default. It was done by binding a country list returned by the middle-tier to the listbox and then doing

CountryListBox.FindByText("United Kingdom").Selected = true


Everything was fine until the middle-tier code started returning a new list where it has "UNITED KINGDOM" in place of "United Kingdom" in the original list. As you know this breaks my code.

This caused me to think about a solution which can do it case-insensitively. And here is what I have come up with.


foreach (ListItem countryListItem in CountryListBox.Items)
{
if (countryListItem.Text.ToLower().Equals("united kingdom"))
{
_ddlCountry.SelectedIndex = -1;
_ddlCountry.Items.FindByText(countryListItem.Text).Selected = true;
}
break;
}


FYI

String.Compare Method (String, String, Boolean) allows to to do case insensitve comparison when you pass the third parameter as true.

Click here to read more about String.Compare()

How to check whether an element exists using jQuery

There might be different ways of doing this. One is using the length property of jQuery selector as shown in the below code snippet

if ($("#elementid").length > 0){
// element exists, do something here
}

Align radio button with corresponding label

You might have spent time to align the label against radio button or checkbox when you use RadioButton, RadioButtoList, CheckBox, CheckBoxList in ASP.NET. It can be fixed by using CSS vertical-align propery.

Example :

label, input[type="radio"]{
vertical-align:middle;
}

Or if you want to apply it for all the input fields

input, label{
vertical-align:middle;
}

This works for IE8, Firefox3.6 and Chrome as well. I may not work for IE6. Worth testing if your are targeting your site for IE6 users.

Tuesday 12 April 2011

First-Party and Third-Party cookies

Websites save cookies in your computer for the purpose of recognising your specific browser / computer combination, were you to return to the same site.

All cookies have an owner which tells you who the cookie belongs to. The owner is the domain specified in the cookie.

The word "party" refers to the domain as specified in cookie; the website that is placing the cookie. So, for example, if you visit www.helloeveryone.com and the domain of the cookie placed on your computer is www.helloeveryone.com, then this is a first-party cookie. If, however, you visit www.helloeveryone.com and the cookie placed on your computer says www.goodbye.com, then this is a third-party cookie.

Increasing numbers of people are either manually blocking third-party cookies, or deleting them reguarly. The cookies being deleted / blocked are third-party party cookies, as opposed to less problematic first-party cookies.

Why do far fewer people block first-party cookies? The reason for this is primarily that it is very difficult to surf the internet without accepting these cookies. First party cookies are necessary in order for you to be recognised as an individual. Any site that you login to as an individual requires a way of identifying you as "you". Hotmail, Yahoo, Gmail, online banking, ebay, Amazon, etc.

Additionally, anti-spyware software and privacy settings do not target first-party cookies.

How does this affect tracking systems, when people block / delete cookies?

A: All visits will still be recorded, but a person who has deleted the cookies will not be recognised as the same (returning) visitor.

When cookies are in place, and not blocked or deleted, total visitor counts will remain comparatively low. If a person constantly deletes cookies, they will be counted as a new "unique" visitor with every subsequent visit.

How Google Analytics works?

Google Analytics works by the inclusion of a block of JavaScript code on pages in your website. When visitors to your website view a page, this JavaScript code references a JavaScript file which then executes the tracking operation for Analytics. The tracking operation retrieves data about the page request through various means and sends this information to the Analytics server via a list of parameters attached to a single-pixel image request.

The data that Google Analytics uses to provide all the information in your reports comes from these sources:
  • The HTTP request of the visitor
  • Browser/system information
  • First-party cookies

How the Tracking Code Works

In general, the Google Analytics Tracking Code (GATC) retrieves web page data as follows:

  1. . A browser requests a web page that contains the tracking code.
  2. . A JavaScript Array named _gaq is created and tracking commands are pushed onto the array.
  3. . A <script> element is created and enabled for asynchronous loading (loading in the background).
  4. . The ga.js tracking code is fetched, with the appropriate protocol automatically detected. Once the code is fetched and loaded, the commands on the _gaq array are executed and the array is transformed into a tracking object. Subsequent tracking calls are made directly to Google Analytics.
  5. . Loads the script element to the DOM.
  6. . After the tracking code collects data, the GIF request is sent to the Analytics database for logging and post-processing.




The data contained in the GIF request is the data sent to the Google Analytics servers, which then gets processed and ends up in your reports. Here is an example of only a portion of a GIF request:

http://google-analytics.com/__utm.gif?utmwv=4&utmn=769876874&utmhn=example.com&utmcs=ISO-8859-1&utmsr=1280x1024&utmsc=32-bit&utmul=en-us&utmje=1&utmfl=9.0%20%20r115utmcc=__utma%3D97315849.1774621898.1207701397.1207701397.1207701397.1%3B

How GIF Requests Are Classified

A GIF request is sent to the Analytics servers in the following cases and classified according to the table below (Page, Event, Transaction, Item, Var). In each of these cases, the GIF request is identified by type in the utmt parameter. In addition, the type of the request also determines which data is sent to the Analytics servers. For example, transaction and item data is only sent to the Analytics servers when a purchase is made. Visitor, page, and system information is only sent when an event is recorded or when a page loads, and the user-defined value is only sent when the _setVar method is called.



Requests classified as interaction requests will impact the bounce rate calculations for your page or site. Bounce rate is referred to as a single-page visit to your site, but is strictly defined as a single interaction request during a user session. For this reason, a bounce rate for a page is also affected by ecommerce transactions and event tracking requests. This is because these features co-exist with page tracking and, when they are triggered, they result in additional interaction requests to the Analytics servers.

click here to read more.

Friday 8 April 2011

Test Automation for Web Applications

Many, perhaps most, software applications today are written as web-based applications to be run in an Internet browser. The effectiveness of testing these applications varies widely among companies and organizations. In an era of highly interactive and responsive software processes where many organizations are using some form of Agile methodology, test automation is frequently becoming a requirement for software projects. Test automation is often the answer. Test automation means using a software tool to run repeatable tests against the application to be tested. For regression testing this provides that responsiveness.

There are many advantages to test automation. Most are related to the repeatability of the tests and the speed at which the tests can be executed.

Test automation has specific advantages for improving the long-term efficiency of a software team’s testing processes.

Test automation supports:

* Frequent regression testing
* Rapid feedback to developers
* Virtually unlimited iterations of test case execution
* Support for Agile and extreme development methodologies
* Disciplined documentation of test cases
* Customized defect reporting
* Finding defects missed by manual testing

To Automate or Not to Automate?


It is not always advantageous to automate test cases. There are times when manual testing may be more appropriate. For instance, if the application’s user interface will change considerably in the near future, then any automation might need to be rewritten anyway. Also, sometimes there simply is not enough time to build test automation. For the short term, manual testing may be more effective. If an application has a very tight deadline, there is currently no test automation available, and it’s imperative that the testing get done within that time frame, then manual testing is the best solution.

Selenium



There are a number of commercial and open source tools available for assisting with the development of test automation. Selenium is possibly the most widely-used open source solution.

Selenium is set of different software tools each with a different approach to supporting test automation. Most Selenium QA Engineers focus on the one or two tools that most meet the needs of their project, however learning all the tools will give you many different options for approaching different test automation problems. The entire suite of tools results in a rich set of testing functions specifically geared to the needs of testing of web applications of all types. These operations are highly flexible, allowing many options for locating UI elements and comparing expected test results against actual application behavior. One of Selenium’s key features is the support for executing one’s tests on multiple browser platforms.

Click here to read more about Selenium

Custom Variables in Google Analytics

Custom variables are name-value pair tags that you can insert in your tracking code in order to refine Google Analytics tracking. With custom variables, you can define additional segments to apply to your visitors other than the ones already provided by Analytics.

You'll get the most out of custom variables if you understand the basic visitor interaction model used in Google Analytics. In this model, the visitor interacts with your content over a period of time, and the engagement with your site is broken down into a hierarchy.


The diagram illustrates this model for a single visitor to your site, where each block represents the number of user sessions and interactions from that particular user.

Each level in this model is defined as follows:

* Visitor—the client that visits the site, such as the browser or mobile phone operated by a person.

* Session—the period of time during which the visitor is active on the site.

* Page—activity on the user's behalf which sends a GIF request to the Analytics servers. This is typically characterized by a pageview, but it can include:

o a pageview
o an event (e.g. click on "Add To Cart" button)


Syntax

_setCustomVar(index, name, value, opt_scope)

Points to Remember


  1. All parameteres are required except the last one.
  2. The sum of all your custom varaiables cannot exceed 5 in any given request.
  3. The length of the string used for the name and the length of the string used for the value must not exceed 64 bytes


Example

_gaq.push(['_setCustomVar', 1, 'User Type', 'Member', 2 ]);
_gaq.push(['_trackEvent', 'Shopping', 'Item Removal']);

Click here to read more about GA custom variables

Thursday 7 April 2011

Printing database diagram in a single page from SQL Server Management Studio

When you try to print database diagrams in SQL Server Management Studio most of the time things end up printing the diagram multiple pages. There is a work-around to this.

Right-Click on the diagram and select the option 'View Page Breaks'. Now you can rearrange your tables to avoid page breaks. Print it once you move all your tables into a single page.

"View Page Breaks" option is also available in "Dtabase Diagram" menu as well.

Thursday 31 March 2011

Hard reboot and Soft reboot

A hard reboot (also known as a cold reboot, cold boot or cold start) is when power to a computer is abruptly turned off, then turned back on. This starts the computer without first performing any shut-down procedure. With many operating systems, especially those using disk caches, after a hard reboot the filesystem may be in an "unclean" state, and an automatic scan of on-disk filesystem structures will be done before normal operation can begin. It may be caused by power failure, be done by accident, or be done deliberately as a last resort to forcibly retrieve the system from instances of a system freeze, critical error or virus-inflicted DoS attack. It can also be used by intruders to access cryptographic keys from RAM, in which case it is called a cold boot attack. The attack relies on the data remanence property of DRAM and SRAM to retrieve memory contents which remain readable in the seconds to minutes after power has been removed.


A soft reboot (also known as a warm reboot) is restarting a computer under software control, without removing power or (directly) triggering a reset line. It usually refers to an orderly shutdown and restarting of the machine.

Thursday 17 March 2011

JavaScript replace() Method

The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring

Syntax

string.replace(regexp/substr,newstring)

Both are required arguments.

To replace all matches with the newstring it is better to use the regular expression version of it. string.replace(substr,newstring) replaces only the first match. But string.replace(/regexp/g,newstring) replaces all matches with newstring. Also you can do case-insensitive replace using regexp i.e. string.replace(/regexp/gi,newstring)

<script type="text/javascript">

var str="I enjoy scripting"; //Not really!!!

//Following script will do a case-insensitive search for the string "enjoy" in the var str and will replace all occurances with "hate"

document.write(str.replace(/enjoy/gi, "hate"));

//And the output will be "I hate coding"

//Following script will do a global search for spaces in the var str and replaces them with non-breaking spaces.

document.write(str.replace(/ /g, "&nbsp;"));


//The output will be "I&nbsp;enjoy&nbsp;coding"

</script>

Non-breaking Space in HTML

&nbsp; is the entity used to represent a non-breaking space. It is essentially a standard space, the primary difference is a browser will not not break (or wrap) a line of text at the point that this &nbsp;occupies.

You can use the non-breaking space to indent text and images a small amount. It's not a good idea to use a lot in a row, as older browsers don't support more than one at a time.

The Single Pixel GIF Trick

This uses a transparent GIF image that is 1 pixel square. You take that image and stretch it out to force your HTML to lay the way you want it to. For example:

<p><img src="spacer.gif" alt=" " width="1" height="1" style="margin-right: 5px; margin-left: 5px;" />This paragraph is indented 11 pixels.</p>

Monday 14 March 2011

Serialize and Deserialize using JavaScriptSerializer and JSON

Ever worndered how to serialize your object instance into a JSON string. You can use System.Web.Script.Serialization.JavaScriptSerializer to do this.

public static string SerializeToJSON(T obj)
{
System.Web.Script.Serialization.JavaScriptSerializer scriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

StringBuilder jsonBuilder = new StringBuilder();

scriptSerializer.Serialize(obj, jsonBuilder);

return jsonBuilder.ToString();
}

And it is quite straightforward to deserialise the JSON string into the original object instance

OriginalType obj = (new System.Web.Script.Serialization.JavaScriptSerializer()).Deserialize(JSONString);

Anonymous C# method for XML serialization

Following is an anonymous C# method which can be used to serialize any given object into XML.

public static string SerializeToXML(T obj)
{
string serializedContext;

System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());

StringWriter stwOutPut = new StringWriter(new StringBuilder());

serializer.Serialize(stwOutPut, obj);

serializedContext = stwOutPut.ToString();

//Replace tag
serializedContext = serializedContext.Replace("", " ");

serializedContext = serializedContext.Replace("\r\n", " ");

return serializedContext;
}

How to disable radiobutton list via jQuery?

Using normal JavaScript you have to find all the elements in the radio group, which can be done using document.getElementsByTagName(radiogroupname), and iterate through the list to do this. But it is very simple to do this using jQuery, just one line of code.

Use either

$("*[name$='radiogroupname']").attr("disabled", "true");

or

$("input:radio[name$='radiogroupname']").attr("disabled", "true");

It will disable all the radio buttons in the group.

:) Happy scripting

Thursday 24 February 2011

Understanding Forms Authentication Ticket and Cookie

What is forms authentication ticket and forms authentication cookie? How are they related?

Forms authentication cookie is nothing but the container for forms authentication ticket. The ticket is passed as the value of the forms authentication cookie with each request and is used by forms authentication, on the server, to identify an authenticated user.

However, if we choose to use cookieless forms authentication, the ticket will be passed in the URL in an encrypted format. Cookieless forms authentication is used because sometimes the client browsers block cookies. This feature is introduced in the Microsoft .NET Framework 2.0.

What is the role of a ticket in Forms Authentication?

The forms authentication ticket is used to tell the ASP.NET application who you are. Thus, ticket is building block of Forms Authentication's security.

The ticket is encrypted and signed using the <machineKey> configuration element of the server's Machine.config file. ASP.NET 2.0 uses the decryptionKey and the new decryption attribute of the <machineKey> element to encrypt forms authentication tickets. The decryption attribute lets you specify the encryption algorithm to use. ASP.NET 1.1 and 1.0 use 3DES encryption, which is not configurable. Tampering with the ticket value is determined by a failure to decrypt the ticket on the server. As a result, the user will be redirected to the logon page.

If the application is deployed in a Web farm, you must make sure that the configuration files on each server share the same value for the validationKey and decryptionKey attributes in the <machineKey> tag, which are used for hashing and decryption of the ticket respectively. You must do this because you cannot guarantee which server will handle successive requests.

How are cookie expiration and ticket expiration related?

In case of non-persistent cookie, if the ticket is expired, cookie will also expire, and the user will be redirected to the logon page. On the other side, if the ticket is marked as persistent, where the cookie is stored on the client box, browsers can use the same authentication cookie to log on to the Web site any time. However, we can use the FormsAuthentication.SignOut method to delete persistent or non-persistent cookies explicitly.

How does sliding expiration work in the context of forms authentication ticket and forms authentication cookie?

Let us take an example: If the logon page is accessed at 5:00 00:00:00 PM, it should expire at 5:10 00:00:00 PM if the timeout attribute is 10 and the slidingExpiration attribute is set to TRUE. Now, if any Web page is browsed again at 5:05 00:00:00 PM, the cookies and ticket time-out period will be reset to 5:15 00:00:00 PM.

If the Web page is accessed before half of the expiration time passes, the ticket expiration time will not be reset. Fore example, if any Web page is accessed again at 5:04 00:00:00 PM, the cookies and ticket timeout period will not be reset.

Where can the time-out value of the forms authentication cookie and forms authentication ticket be set?

The only setting that you can make is in the Web.config file or the Machine.config file, in the tag. This change will determine the time-out period of forms authentication in the context of a ticket or cookie unless the ticket is generated manually.

If the ticket is generated manually by using the FormsAuthenticationTicket class, the time-out can be set through the Expiration attribute. This value will override the timeout attribute value specified in configuration files.

The forms authentication may time out before the timeout attribute value that is set in the configuration file.
If the forms authentication ticket is manually generated, the time-out property of the ticket will override the value that is set in the configuration file. Therefore, if that value is less than the value in the configuration file, the forms authentication ticket will expire before the configuration file timeout attribute value and vice-versa.

FormsAuthenticationTicket.IsPersistent Property

true if a durable cookie (a cookie that is saved across browser sessions) was issued; otherwise, false.

FormsIdentity id = (FormsIdentity)User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;

If there is no logged-on user, the Identity property will be null and you will receive a compiler exception when attempting to cast the Identity property as a FormsIdentity object.


more>>

more >>

Sliding Expiration

Inside the FormsAuthentication class we find the method that renews the ticket only if the time left till expiration is greater than the time since the current ticket was issued.

Public Shared Function RenewTicketIfOld(
 ByVal tOld As FormsAuthenticationTicket) As FormsAuthenticationTicket
If (tOld Is Nothing) Then
Return Nothing
End If

Dim time1 As DateTime = DateTime.Now
Dim span1 As TimeSpan = DirectCast((time1 - tOld.IssueDate), TimeSpan)
Dim span2 As TimeSpan = DirectCast((tOld.Expiration - time1), TimeSpan
      
If (span2 > span1) Then
        Return tOld
End If
  
Return New FormsAuthenticationTicket(tOld.Version, tOld.Name, time1, _
                      (time1 + (tOld.Expiration - tOld.IssueDate)), _
                      tOld.IsPersistent, tOld.UserData, tOld.CookiePath)
End Function

Wednesday 16 February 2011

Empty Cache vs. Primed Cache

Using a far future Expires header affects page views only after a user has already visited your site. It has no effect on the number of HTTP requests when a user visits your site for the first time and the browser's cache is empty. Therefore, the impact of this performance improvement depends on how often users hit your pages with a primed cache. It is likely that a majority of your traffic comes from users with a primed cache. Making your components cacheable improves the response time for these users.

When I say "empty cache" or "primed cache", I mean the state of the browsers cache relative to your page. The cache is "empty" if none of your page's components are in the cache. The browser's cache might contain components from other web sites, but that doesn't help your page. Conversely, the cache is "primed" if all of your page's cacheable components are in the cache.

The number of empty versus primed cache page views depends on the nature of the web application. A site like "word of the day" might only get one page view per session from the typical user. There are several reasons why the "word of the day" components might not be in the cache the next time a user visits the site:

a. Despite her desire for a better vocabulary, a user may visit the page only weekly or monthly, rather than daily.

b. A user may have manually cleared her cache since her last visit.

c. A user may have visited so many other web sites that her cache is filled up, and the "word of the day" components were pushed out.

d. The browser or an antivirus application may have cleared the cache when the browser was closed

With only one page view per session, it is not very likely that "word of the day" components are in the cache, so the percentage of primed cache page views is low.

Click here to read more about improving Web Site performance.

More>>

More>>