Uppercase and lowercase strings using jquery

In this programming tutorial we will learn how to convert strings in uppercase and lowercase using jquery. It is not a difficult task in jquery. Jquery has two built-in functions for handling these two cases. Those two functions are .toUpperCase() and .toLowerCase(). Let's have a look over the example given below that demonstrates how to do so.
Convert string in uppercase
var name="Adeel Fakhar";//Very simple
var nameUpperCase=name.toUpperCase(); 

Output
ADEEL FAKHAR

Convert string in lowercase
var name="Adeel Fakhar";
var nameLowerCase=name.toLowerCase(); //Very simple

Output
adeel fakhar

So that's it. I hope you will find this tutorial very useful.

Stay tuned with nice-tutorials.blogspot.com for bundle of jquery tutorials.

I love your feedback.
Read more...

Add new item in dropdown using jquery

In this programming tutorial we will learn how to add new item in dropdown using jquery. It is quite easy in jquery. Let's have a look over the code snippet given below in which i will add a new country in dropdown when button is clicked.
Add new item in dropdown using jquery
before

After
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Add new item in dropdown using jQuery</title>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnClick").click(function () {
                var newCountry = $("#txtItem").val();
                if (newCountry.length > 0)
                    {
                    $("#ddlCountry").append($("<option>").val(newCountry).text(newCountry));
                    $("#txtItem").val("");
                   }
            });
        });
    </script>
</head>
<body>
    <div style="font-family:verdana;font-size:12px;">
   New Country: <input type="text" id="txtItem" />
 Country:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;
 <select id="ddlCountry">
 <option value="Pakistan">Pakistan</option>
 <option value="China">China</option>
 <option value="United States">United States</option>
 </select>
        <input id="btnClick" type="button" value=" Add Country " />
    </div>
</body>
</html>

In this above mentioned example, i have a textbox, a dropdown and a button in my page. Country dropdown by default contains three countries which are Pakistan, China and United States. Now for adding new country such as Australia or india, i have written a code in document.ready(), that will execute when button's click event will be fired.
$("#ddlCountry").append($("<option>").val(newCountry).text(newCountry));
The above mentioned code snippet will dynamically add new item or in this example we can say new country to the dropdown using append() function of jquery, which is a built-in function in jquery.

So that's it. This is the way to add new item or element in dropdown using jquery.
I love your feedback.
Read more...

Install php on windows server 2008 R2

In this programming tutorial we will learn how to install php on windows server 2008 R2. Couple of weeks ago one of my colleague asked me to install php on windows server 2008 R2 as he had to deploy a website and I have done it successfully without any problem. Let’s have a look over how to accomplish our task.
Simply go to this tutorial Install PHP on Windows 7 with IIS 7 via FastCGI and that's it. You just have to repeat the steps that you have performed on Windows 7 in order to accomplish this task.

Note:-
Depending on your location you can set a specific date.timezone value by setting the date.timezone property in php.ini file:
date.timezone = "US/Central"

Don't forget to uncomment the date.timezone by removing its preceding semicolon.

So that's it.
Your feedback gives me energy.
Read more...

Learn jquery from beginners to advanced level - part 3 (Final Part)

Finally I am writing the third and last tutorial of this tutorial series. Again I am saying if you are new visitor and haven't read my first two tutorial of this series then please read those tutorials first. Click to read Part 1 and click to read Part 2. One thing I want to ensure you is that if you read and understand all of these three tutorials then you can say yourself the expert of jquery, and you can do any task in jquery with minimum effort. Ok. Now let's start right from there, where we were.
Events

When the DOM is ready…

$(document).ready(function(){
 //Your code will come here
});

  • Fires when the document is ready for programming.
  • Uses advanced listeners for detecting.
  • window.onload() is a fallback.

Attach Event

// execute always
$("div").bind("click", fn);
// execute only once
$("div").one("click", fn);

Possible event values:

blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error (or any custom event)

jQuery.Event object
Detaching Events
$("div").unbind("click", fn);

(Unique ID added to every attached function)

Events Triggering
$("div").trigger("click");

Triggers browser’s event action as well. Can trigger custom events. Triggered events bubble up.

Events Helpers
// attach / trigger
elem.blur(fn) / elem.blur()
elem.focus(fn) / elem.focus()
elem.click(fn) / elem.click()
elem.change(fn) / elem.change()

And many others…

Preventing Browser Default Action
// use different triggering function
$("div").triggerHandler("click");

// prevent default action in handler
function clickHandler(e) {
 e.preventDefault();
}

// or just return false
function clickHandler(e) {return false;}

Preventing Bubbling
// stop bubbling, keep other handler
function clickHandler(e) {
 e.stopPropagation();
}

// stop bubbling and other handlers
function clickHandler(e) {
 e.stopImmediatePropagation();
}

// or just return false
function clickHandler(e) {return false;}

Live Events (Attach events to dynamically created elements)
// attach live event
("div").live("click", fn);
// detach live event
("div").die("click", fn);

Currently supported events:

click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup

Effects

Showing or Hiding Element
// just show
$("div").show();
// reveal slowly, slow=600ms
$("div").show("slow");
// hide fast, fast=200ms
$("div").hide("fast");
// hide or show in 100ms $(“div”).toggle(100);

Sliding Elements
$("div").slideUp();
$("div").slideDown("fast");
$("div").slideToggle(1000);

Fading Elements
$("div").fadeIn("fast");
$("div").fadeOut("normal");
// fade to a custom opacity
$("div").fadeTo ("fast", 0.5);

Fading === changing opacity

Detecting animation completion
$("div").hide("slow", function() {
  alert("The DIV is hidden");
});

$("div").show("fast", function() {
  $(this).html("Hello jQuery");
}); // this is a current DOM element 

Every effect function has a (speed, callback) overload

Custom Animation
// .animate(options, duration)
$("div").animate({
    width: "90%",
    opacity: 0.5,
    borderWidth: "5px"
     }, 1000);

Chaining Animation
$("div").animate({width: "90%"},100)
  .animate({opacity: 0.5},200)
  .animate({borderWidth: "5px"});

By default animations are queued and than performed one by one

Controlling Animations Sync
$("div")
 .animate({width: "90%"},
      {queue:false, duration:1000})
 .animate({opacity : 0.5});

The first animation will be performed immediately without queuing

AJAX with jQuery

Loading content
$("div").load("content.htm");
// passing parameters
$("#content").load("getcontent.aspx",
     {"id":"33","type":"main"});

Sending GET/POST requests
$.get("test.aspx", {id:1},
  function(data){alert(data);});

$.post("test.aspx", {id:1},
  function(data){alert(data);});

Retrieving JSON Data
$.getJSON("users.aspx", {id:1},
  function(users)
  {
   alert(users[0].name);
  });

Retrieving JS Files
$.getScript("script.js",
  function()
  {
   doSomeFunction();
  });

Extending the Library

Adding Methods
// definition
jQuery.fn.printLine = function(s) {
 return jQuery(this).each(function() {   this.append("<div>"+ s +"</div>");
 });
};
// usage
$("#log").printLine("Hello");

Closure to solve the $ issue
(function ($) {
  jQuery.fn.printLine = function(s) {
 return $(this).each(function() {    this.append("<div>"+ s +"</div>");
 });
};
})(jQuery);

Custom Selectors
$.expr[‘:’].test = function(o, i, m, s) {
// o – current object in the selection
// i – loop index in the stack
// m – meta data about your selector
// s – stack of all the elements
// return true to include the element
// return false to exclude the element
};

So that's it. I tried my level best to teach you jquery from beginners to advanced level in this series of tutorials. Now just you have to practice more and more to get a grip on jquery.

I love your feedback.
Read more...

Learn jquery from beginners to advanced level - part 2

In this programming tutorial we will learn jquery from beginners to advanced level. If you are new visitor and haven't read my first tutorial of this series then first please read the tutorial Learn jquery from beginners to advanced level - part 1. Ok. Now let's start right from there, where we were.
Selectors demo

Document Traversal

A Selector returns a pseudo array of jQuery objects
$(“div”).length

Returns number of selected elements. It is the best way to check selector.

Getting a specific DOM element

 $(“div”).get(2) or $(“div”)[2]

Returns a 2nd DOM element of the selection

Getting a specific jQuery element

$(“div”).eq(2)

Returns a 2nd jQuery element of the selection

each(fn) traverses every selected element calling fn()
var sum = 0;
$(“div.number”).each(
		function(){
		  sum += (+this.innerHTML);
		});

this – is a current DOM element

each(fn) also passes an indexer

$(“table tr”).each(
	function(i){
		if (i % 2) 
			$(this).addClass(“odd”);
	});

$(this) – convert DOM to jQuery i - index of the current element

Traversing HTML
.next(expr) 	// next sibling

.prev(expr)		// previous sibling

.siblings(expr)	// siblings

.children(expr) // children

.parent(expr) 	// parent

Check for expression
$(“table td”).each(function() {
	if ($(this).is(“:first-child”)) {
		$(this).addClass(“firstCol”);
	}
}); 

Find in selected
// select paragraph and then find 
// elements with class ‘header’ inside 
$(“p”).find(“.header”).show();

 // equivalent to:
$(“.header”, $(“p”)).show();

Advanced Chaining
$(“<li><span></span></li>”) // li
	.find(“span”) // span
		.html(“About Us”) // span 
		.andSelf() // span, li
			.addClass(“menu”) // span,li 
		.end() // span 
	.end() // li 
	.appendTo(“ul.main-menu”);

Get Part of Selected Result
$(“div”).slice(2, 5).not(“.green”).addClass(“middle”);

HTML Manipulation

Getting and Setting Inner Content
$(“p”).html(“<div>Hello World!</div>”);

// escape the content of div.b
$(“div.a”).text($(“div.b”).html());

Getting and Setting Values
// get the value of the checked checkbox
$(“input:checkbox:checked”).val();

// set the value of the textbox
$(“:text[name=‘txt’]”).val(“Hello”);

// select or check lists or checkboxes
$(“#lst”).val([“NY”,”IL”,”NS”]);

Handling CSS Classes
// add and remove class
$(“p”).removeClass(“blue”).addClass(“red”);

// add if absent, remove otherwise
$(“div”).toggleClass(“main”);

// test for class existance
 if ($(“div”).hasClass(“main”)) { 
// Your code will come here

}

Inserting new Elements
// select > append to the end
$(“h1”).append(“<li>Hello World</li>”);

// select > append to the beginning
$(“ul”).prepend(“<li>Hello World</li>”);

// create > append/prepend to selector

$(“<li/>”).html(“9”).appendTo(“ul”);

$(“<li/>”).html(“1”).prependTo(“ul”);

Replacing Elements
// select > replace
$(“h1”).replaceWith(“<div>Hello</div>”);

// create > replace selection
$(“<div>Hello</div>”).replaceAll(“h1”);

Replacing Elements while keeping the content
$(“h3”).each(function(){
	$(this).replaceWith(“<div>” + $(this).html() 
					+ ”</div>”);
	});

Deleting Elements
// remove all children
$(“#mainContent”).empty();

// remove selection
$(“span.names”).remove();

// change position
$(“p”).remove(“:not(.red)”).appendTo(“#main”);

Handling attributes
$(“a”).attr(“href”,”home.htm”);
// <a href=“home.htm”>…</a>

// set the same as the first one
$(“button:gt(0)”).attr(“disabled”,$(“button:eq(0)”).attr(“disabled));
// remove attribute - enable
$(“button”).removeAttr(“disabled”)	

Setting multiple attributes
$(“img”).attr({
		“src” : “/images/smile.jpg”,
		“alt” : “Smile”,
		“width”  : 10,
		“height” : 10
});

CSS Manipulations
// get style
$(“div”).css(“background-color”);

// set style 
$(“div”).css(“float”, “left”);

// set multiple style properties
$(“div”).css({“color”:”blue”,
			 “padding”: “1em”
			 “margin-right”: “0”,
			 marginLeft: “10px”});

Dimensions
// get window height
var winHeight = $(window).height();

// set element height
$(“#main”).height(winHeight);

//.width() – element
//.innerWidth() – .width() + padding

//.outerWidth() – .innerWidth() + border
//.outerWidth(true) – including margin

The default unit is Pixel (px)

Positioning
// from the document
$(“div”).offset().top;

// from the parent element
$(“div”).position().left; 

// scrolling position
$(window).scrollTop(); 

So that's it, i try my level best to let you learn jquery from beginners to advanced level with small and handy examples. Third and Final part of this tutorial series will come soon. Stay tuned.

Your feedback always provides me lot of energy.
Read more...

ASP.NET HyperLink - Set alt tag of the image

In this programming tutorial we will learn how to set the alt tag of an image that has been set by asp.net hyperlink using its ImageUrl property which is

HyperLink.ImageUrl

Couple of days ago i am working over a project in which i am fixing the issues reported by SEO Tool Kit (use for site analysis) which is installed in IIS 7 (You can Install it in IIS 5 and IIS 6 as well). The SEO Tool kit is very much helpful if you want to check the errors and violations of the website that are damaging the ranking of your website or specific web pages in the search engine, especially in google. I got lot of violations about alt tag is missing, when i was fixing all these violations then i got an asp:Hyperlink that contains an image which alt tag was missing, i checked all the possible properties of the asp:hyperlink to give alt tag to the image, like ToolTip property but i was fail to achieve what i want, moreover the HyperLink control doesn't have an AlternateText property.
Then surfing the internet i got the solution and it was quite easy and surprised to me. The solution was to give text between starting and ending tag of the asp:hyperlink and then that text will become the alt of the image, like given below
<asp:HyperLink ID="HyperLink1" runat="server" ImageUrl="~/Images/proceed.gif" 
                        NavigateUrl="~/Welcome.aspx">Proceed

So that's it. The word Proceed will become the alt tag of the image located inside the hyperlink.

Stay tune with nice-tutorials.blogspot.com because in future i will write very informative and detailed tutorials about SEO Tool kit, which is used for analysis of website to improve its ranking in the major search engines. Also i will tell you how to deploy a website in windows 2008 R1, you can then open your own hosting company as well if you have servers that are capable to run the websites :). But still bottom line is to stay tune with nice-tutorials.blogspot.com

Do comment. Your feedback gives me energy.
Read more...

spell checker in jquery using php

In this programming tutorial we will learn how to perform spell checking in jquery using php. For this i will use a jquery plugin which is called jquery-spellchecker. By god, i have tried many spell checkers but there are lot of problems in them, some spell checkers that i like was not free of cost, some was not cross browser compatible then i found this spell checker which is pretty good. This jQuery plugin is used to check the spelling of a chunk of text, using google's spell checking service. The plugin also gives you the option of using pspell. If you are able to use pspell then you will have great control over your dictionary to manage spells of words. To communicate with google's api or pspell, php will be used.
The plugin comes with 2 default behaviours:
  • If bound to a HTML element other than textarea, the plugin will highlight the incorrectly spelt words. Clicking on those incorrect words will bring up the suggest box.
  • If bound to a textarea element, the plugin will add the incorrectly spelt words after the textarea. Clicking on those incorrect words will bring up the suggest box.

Server side script
As i told you above, the plugin uses PHP script that supports two type of spell checking engines: php's pspell extension for aspell, or google's spell checking services (API).

using pspell requires you to have aspell installed on the server, as well as the PHP pspell extension using google requires minimal server adjustments.
Note:-

The example PHP file uses the json_encode function, which requires the json package. This package comes default with PHP 5 >= 5.2.0. If you have an older version of PHP then you can install this package via PECL, or use a custom json library.

If you would like to use a different server side language, let's suppose asp.net then wait for my next tutorial, i have working example of this plugin with asp.net, jquery and google's spell checking api in my system and soon it will be uploaded in the form of tutorial.

Check chunk of text:-


checkspelling.php?engine=pspell
Request:
Content type: application/x-www-form-urlencoded;charset=UTF-8
Data: text="a chunk of text without any punctuation"
Response:
Content type: application/json
Example response: ["bbad","speltt","wwords"]
Get suggestions for a word:

checkspelling.php?engine=pspell

Request:
Content type: application/x-www-form-urlencoded;charset=UTF-8
Data: suggest="word"
Response:
Content type: application/json
Example response: ["suggest","snuggest","soggiest"]


Supported languages

Pspell

What is pspell??? Good question, ok :) Pspell is simply a php wrapper to the GNU aspell spell checker. So supporting large range of languages is as easy as installing the relevant aspell language dictionary. These dictionary packs are available in most GNU/Linux distro repositories. In debian/ubuntu, you can install a new dictionary in a following way:
sudo apt-get install aspell-LANG
(you have to replace LANG with the language code)

If you want to search for a particular language dictionary then you can use apt-cache:
sudo apt-cache search aspell


or view the aspell supported languages page.

Don't forget to restart apache after successfully installation of new dictionaries. If you having problems getting pspell to work with personal dictionaries, view the php errors!

Note:- Aspell also works like charm in windows

Google API
I couldn't find any information for the languages google supports, but probably there are lot of languages and in my next tutorial you will see that i will use asp.net with google api to perform spell checking via this jquery plugin.

Usage
Include the following in the head section of your html document:
<link href="css/spellchecker.css" media="screen" rel="stylesheet" type="text/css"></link>
<script src="js/jquery.js" type="text/javascript">
</script>
<script src="js/jquery.spellchecker.js" type="text/javascript">
</script>

Defaut usage
// initiate the spell checker on an element, fire the 'check' function
$("textarea#text-content").spellchecker("check");

Plugin options: (all optional)
$("textarea#text-content")
.spellchecker({
        url: "checkspelling.php",       // default spellcheck url
        lang: "en",                     // default language 
        engine: "pspell",               // pspell or google
        addToDictionary: false,         // display option to add word to dictionary (pspell only)
        wordlist: {
                action: "after",               // which jquery dom insert action
                element: $("#text-content")    // which object to apply above method
        },      
        suggestBoxPosition: "below",    // position of suggest box; above or below the highlighted word
        innerDocument: false            // if you want the badwords highlighted in the html then set to true
});

You only want to execute the above code after an event has occured:
// initiating the spell checker is not necessary if using the default plugin options
$("a.check-spelling").click(function(e){
        e.preventDefault();
        $("textarea#text-content").spellchecker("check");
});

This jquery plugin will fire off a callback function after it has finished checking words:
$("a.check-spelling").click(function(e){
        e.preventDefault();
        $("textarea#text-content").spellchecker("check", function(result){
                // if result is true then there are no incorrectly spelt words
                if (result) alert('There are no incorrectly spelt words.');
        });
});

And for removing all spellchecker html, just do the following:
$("textarea#text-content").spellchecker("remove");


Source
jquery.spellchecker

Simple Demo
Demo

So that's it. I hope you will love this spell checker in jquery using php.
I love your feedback.
Read more...

Firefox 7 release - Enjoy better browsing

Another release of firefox in this year - Firefox 7. Firefox 7 has been released by Mozilla at 27 September 2011. Firefox 7 is actually the first version of the rapid release cycle that is showing big improvements over previous versions. Mozilla claims in its official website about Firefox 7 in these wordings "Made to make the Web a better place".
Firefox 7 arrives with lot of new features. Mozilla managed to improve memory usage of the Firefox drastically (that’s the organization’s word), courtesy of Mozilla's MemShrink project. According to blog post by Nicholas Nethercoate over at Mozilla:

Firefox 7 uses less memory than Firefox 6 (and 5 and 4): often 20% to 30% less, even in some cases 50% less. In particular, Firefox 7′s memory usage will stay steady if you leave it running overnight, and it will free up more memory when you close many tabs.

Saving 50% memory usage is a big achievement. Probably even more important is that the browser won’t feel like eating up all the RAM over time anymore, which is definitely a super stuff, considering that the browser has a reputation for being memory inefficient.

The change log lists addition features
  • Better Javascript garbage collection.
  • Rendering backend that speeds up Canvas operations on Windows. Implements Azure Direct2D for Canvas which increases canvas-based animations in HTML5.
  • Support for text-overflow: ellipsis.
  • Web Timing specification.
  • Faster bookmark.
  • Password changes syncing when using Firefox Sync.


In addition to the memory improvements, there are also are fixes for 11 security vulnerabilities in Firefox 7, including eight critical flaws.

MFSA 2011-45 Inferring Keystrokes from motion data
MFSA 2011-44 Use after free reading OGG headers
MFSA 2011-43 loadSubScript unwraps XPCNativeWrapper scope parameter
MFSA 2011-42 Potentially exploitable crash in the YARR regular expression library
MFSA 2011-41 Potentially exploitable WebGL crashes
MFSA 2011-40 Code installation through holding down Enter
MFSA 2011-39 Defense against multiple Location headers due to CRLF Injection
MFSA 2011-38 XSS via plugins and shadowed window.location object
MFSA 2011-37 Integer underflow when using JavaScript RegExp
MFSA 2011-36 Miscellaneous memory safety hazards (rv:7.0 / rv:1.9.2.23)

Enjoy web browsing with firefox 7.
Read more...

Google is celebrating 13th Birthday with doodle

Today Google is celebrating 13th Birthday with doodle. The search engine giant and number one website (alexa rating) on the internet, Google has just turned 13 today and celebrating by dedicating itself a Google birthday Doodle, marking the 13th anniversary of awesomeness.
Its my perception that no one cannot imagine life without Google. Google search along with its many other awesome services are playing an important role in our life. People love to use Gmail, people love to use Google Adsense, people love to use Google Docs, people love to use Google Analytics, People love to use Blogger and now google has officially launched Google Plus which is targeting Social Network giant the Facebook.

Research conducted by Nielsen earlier this month showed that US internet surfers spend more time on Facebook than any other website on internet.

At the same time, Google is enjoying a 90% share of the global internet search market, according to the most recent figures from metrics firm StatsCounter, although its share varies considerably by country yet Google is number one in Search Engine market.

The seed bowed by Larry Page, Sergey Brin, and Eric Schmidt – the three key persons who founded Google in September 1998, is now become a tree which is giving the shadow and fruits to the world at same time. “Google” itself has become a synonym for “web search”.

Well done Google. Keep Going.
Read more...

Set alt attribute to images dynamically using jquery

In this programming tutorial, we will learn how to set alt attribute to images dynamically using jquery. Once again i say, in jquery doing so is quite easy :). Let's have a look over how to do so.
    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $("img:not([alt])").each(function () {
		$(this).attr('alt', 'image here');
                //alert($(this).attr("src"));
            });
        }); 
        </script>

By using the jquery's built-in attr() function, the above mentioned code snippet will check each and every image in the body of your web page and assign alt attribute dynamically to those images in which alt attribute is missing. Right now i am assigning image here as a hard coded value of alt attribute, but you can assign the image name as a value of alt attribute as well, depends upon your requirement.

Note:- After applying the above mentioned code, please check the required change in source code by using firebug because if you check the source code by right clicking the web page then you will not find any change made by the above mentioned code, as jquery doesn't change the original html of the web page. I can understand most of you are well aware of firebug but those my brothers that don't know about firebug, definitely i will write a tutorial for them very soon.

So that's it. I hope you will find this tutorial very handy.

I love your feedback.
Read more...

How to increase uplaod file size in php

In this programming tutorial we will learn how to increase upload file size in php. Doing so is quite easy in php by changing some default values in php.ini file or in .htaccess file, depends upon your hosting situation. php.ini file is the configuration file that contains all the settings related to your website. So let's have a look over how to accomplish what we want.
How to increase uplaod file size in php
You have to update the values of post_max_size and upload_max_filesize in php.ini file. Since post_max_size is the limit for all the content of your post, many developers want post_max_size to be a multiple of upload_max_filesize to allow multiple files to be uploaded, but this is not necessary. The upload module limits the size of a single attachment to be less than either post_max_size, or upload_max_filesize, whichever is smaller. The default value for upload_max_filesize is 2 MB, and default value for post_max_size is 8 MB.

For instance, to increase the limit on uploaded files to 10 MB:

Perform below mentioned changes to the php.ini file. Remember, for some hosts this is a system-wide setting.
  • upload_max_filesize = 10M
  • post_max_size = 10M
So that's it. I hope you will find this tutorial very handy.

I love your feedback.
Read more...

How to set attribute of any element in jquery

Sometimes it becomes our requirement to set the attribute of any element using jquery. For instance, in my next tutorial i will teach you how to set the alt attribute of images that doesn't contain the alt attribute. Its very easy in jquery by using its attr() function which is built-in in jquery.Let's have a look over the example given below.
How to set attribute of any element in jquery

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
.divclass{
font-family:verdana;
font-size:12px;
color:green;
}
</style>
</head>
<body>
	<div id="myDiv">Welcome to nice-tutorials.blogspot.com</div><br/>
	<span></span>
<script language="javascript" type="text/javascript">
$("#myDiv").attr('class', 'divclass');
</script>
</body>
</html>

Output:-
Welcome to nice-tutorials.blogspot.com

In the above mentioned code snippet i have decalred a css class which is divclass and then by using built-in attr() function of jquery i assigned divclass to the div having id of myDiv. Using this behavior of attr() function we can set one or more attributes for the set of matched elements.

So that's it.

I love your feedback.
Read more...

Get class name of any element in jquery

In this programming tutorial we will learn how to get class name of any element in jquery. It is quite easy in jquery by utilizing its built-in attr() function. This attr() function is quite handy. Let's have a look over the following code snippet.
Get class name of any element in jquery
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
.divclass{
font-family:verdana;
font-size:12px;
color:green;
}
</style>
</head>
<body>
	<div id="myDiv" class="divclass">Welcome to nice-tutorials.blogspot.com</div><br/>
	<span></span>
<script language="javascript" type="text/javascript">
var divClassName=$("#myDiv").attr("class");
$("span").html("Div's class is <strong>"+divClassName+"</strong>")
</script>
</body>
</html>

Output:-
Welcome to nice-tutorials.blogspot.com

Div's class is divclass

In the above given code snippet i declare a css class .divclass and assign it to the div myDiv then using built-in attr() function of jquery i get the class name and display the class name in the span just after the div element. attr() function gets the value of an attribute for the first element in the set of matched elements.

So that's it. This is the way to get class name of any element in jquery.

I love your feedback.

Stay tune with nice-tutorials.blogspot.com
Read more...

Remove a word in a text using jquery

In this programming tutorial we will learn how to remove a word in a text using jquery. Jquery is very powerful and we can achieve this task quite easily in it with the help of built-in replace() function. Let's have a look over the following code snippet that illustrates how to do so.
Remove a word in a text using jquery

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<div id="myDiv">Welcome to nice-tutorials.blogspot.com</div>

<script langiage="javascript" type="text/javascript">
var el = $("#myDiv");
//replace(/word to remove/ig, "");
el.html(el.html().replace(/to/ig, ""));
</script>

</body>
</html>
In the above given example we are removing the word to from div's inner html, so the output will be

Output:-
Welcome nice-tutorials.blogspot.com

So that's it. This is the process to remove a word in a text using jquery.

I always love your feedback.

Stay tune with nice-tutorials.blogspot.com for millions of tutorials of jquery :)
Read more...

Facebook updates its friend list system targeting Google+

Facebook has updated its Friend Lists system to target Google Plus's Circles features.
By adding this, users will now have more control over how their connections are grouped, with some lists, such as family and work, created automatically.

Although Facebook remains the world's most popular social network, Google+ is expected to hit 100m users this year.

The company has been rolling out a range of new features in recent weeks.


The new Smart Lists feature of facebook will create categories totally based on the relationship between a user and their friends. For example, anyone sharing the same workplace will be designated a colleague. Likewise school friends. New "close friends" and "acquaintances" lists will allow Facebook members to filter who they see updates from.

There will be inevitable comparisons to the widely praised Circles feature on Google's social network, which lets users group together people they are following.

Anyway Mike Schroepfer, Facebook's vice president of engineering said the changes were part of the site's gradual evolution. "We've had friend lists since 2007. Groups we made in 2010. We've been experimenting with lots of different ways to share for many, many years now," he told BBC News.

Is Twitter threatening?

While the new friend list setting are an apparently minor change to an existing system, their introduction may provide clues to Facebook's longer term strategy.

On a superficial level, the changes appear to be aimed at users who are attracted by the ability to create groups using Google Circles.

However, coupled with recent updates to the system for sharing content on Facebook, there is also a challenge to Twitter.
By encouraging users to think about attaching different privacy levels to things they post, and to categorise whose status updates they see, Facebook seems to be preparing to encourage more public feeds, visible to anyone online.
Such a strategy could ultimately lead to a Twitter-style "follow" system, where users can sign-up to updates from non friends.
Facebook's Mike Schroepfer said that the company would always offer the option to remain private.

"There are things that people share that they don't want others to see - a personal thought or something with their family, and there is no value in having that shared more publicly," he said.

However, he hinted that more public postings would also play a part in the site's future.

"There's definitely a value in serendipity and getting a chance to connect people. That's a lot of what our product is about."

Courtesy of bbc.

Read more...

Get the total number of matched elements in jquery

In this programming tutorial we will learn how to get the total number of matched elements in jquery. As we all know, jquery is a very powerful javascript library and its selectors play very vital role to select any DOM element. In some cases we need to know the total number of matched elements, for this, let's have a look over the following code snippet.
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<div>Welcome to nice-tutorials.blogspot.com</div><br/>
	<div>Welcome to nice-tutorials.blogspot.com</div><br/>
	<span></span>

<script language="javascript" type="text/javascript">
$("span").html("There are <strong>" + $("div").size() + "</strong> divs in this page.");

</script>

</body>
</html>

Output:-
Welcome to nice-tutorials.blogspot.com
Welcome to nice-tutorials.blogspot.com
There are 2 divs in this page.

Note:-
The .size() method is functionally equivalent to the .length property; however, the .length property is recommended because it does not have the overhead of a function call.

So that's it. This is the code to get the total number of matched elements in jquery.

I love your feedback.
Read more...

Disable right click contextual menu in jquery

In this programming tutorial we will learn how to disable right click contextual menu in jquery. Jquery is a very powerful javascript library and makes things very easier to work with. So let's have a look over how to do so.
$(document).ready(function(){
 $(document).bind("contextmenu",function(e){
        return false;
    });

});
So that's it, this above written jquery code snippet will disable right click contextual menu, moreover, it will also disable the contextual menu when you press key(Application Key) between the alt and ctrl keys in QWERTY keyboard of your pc.

I love your feedback.
Read more...

Server.Transfer vs Response.Redirect

In this programming tutorial we will learn the difference between server.transfer and response.redirect. Server and Response both are objects in ASP.NET use for redirecting the users from one page to another or from one website to another website. Server object provides methods and properties for various tasks related to a server. Transfer is a method of the Server object and it sends information of the current state to another .aspx file for processing. Response object describes methods and properties related to a server’s response. Redirect is a method of the Response object and it sends a message to the browser making it connect to a different URL. Although both the Server.Transfer and Response.Redirect can be used to transfer a user from one page to another yet they are different to each other.
What is Response.Redirect?

Redirect is a method of the Response object. When the Response method is called, it sends the HTTP code 302 and the URL of the requested web page to the user's browser. The HTTP code 302 informs the user’s browser that the requested resource is located under a different URL. So when the browser receives the code, it instantly opens the resource in the new location. The requested web page can reside on the same server (Same Website) as the page that contained the request or it could be located in some other server (Some other website). When requesting a web page residing on the same server, Response method can be used as follows:

Response.Redirect(“Welcome.aspx”);


When requesting a web page residing on another server (another website), Response method can be used as follows:

Response.Redirect(“http://www.yourwebsite.com/Welcome.aspx”);


What is Server.Transfer?

Transfer is a method of the Server Object. When the Transfer method is called, the original request is modified to transfer in to some other page in the same server. When a new page is requested using the Server.Transfer, URL shown in the user’s browser does not change. This is because the transfer happens in the server side and the browser does not have any knowledge about the transfer. If we use the second overload for Server.Transfer(string path, bool preserveForm) and sets the second parameter as true, posted form variables and query strings can be made available to the second page.

Difference between Server.Transfer and Response.Redirect

  1. Response.Redirect can be used to redirect the user to a web page in another server (another website) whereas Server.Transfer can only be used to redirect the user to web pages on the same server (same website).
  2. Response.Redirect makes a roundtrip to the server, while Server.Transfer changes the focus of the web server to a different web page. Therefore, by using Server.Transfer we can save server's resources.
  3. Transfer, properties of the previous page can be accessed from the new page but this is only possible with server.transfer.
  4. Finally, Response.Redirect changes the URL in the address bar of the browser when the new page is accessed but when using the Server.Transfer the original URL is retained and the content of the page is just changed. So the user cannot use it to bookmark the new page as it always refer to the first content that comes with that url.

So that's it. I hope you know better understand the difference between Response.Redirect and Server.Transfer.

I love your feedback.
Read more...

format date time in sql server using getdate() function

In this programming tutorial we will learn how to format date or date time in sql server. As a web developer i know how important this task is because at any time we may get request from our client to display date in any report of our project according to the format that suits him. We must know different formats of date time. So let's have a look over how to do so.

format date time in sql server using getdate() function


Here's a list of the different date formats that come standard in SQL Server as part of the CONVERT function. It is important to note that the output of these date formats are of VARCHAR data types, so if you have to compare any dates that are in varchar data type then again you have to convert them in datetime data type.

SELECT convert(varchar, getdate(), 100)  -- mon dd yyyy hh:mmAM (or PM)

Output:-
Sep 16 2011 5:55PM
SELECT convert(varchar, getdate(), 101)  --mm/dd/yyyy 

Output:-
09/16/2011
SELECT convert(varchar, getdate(), 102)  --yyyy.mm.dd 

Output:-
2011.09.16
SELECT convert(varchar, getdate(), 105)  --dd-mm-yyyy

Output:-
16-09-2011
SELECT convert(varchar, getdate(), 106)  --dd mon yyyy

Output:-
16 Sep 2011
SELECT convert(varchar, getdate(), 107)  --mon dd, yyyy

Output:-
Sep 16, 2011
SELECT convert(varchar, getdate(), 103)  --dd/mm/yyyy

Output:-
16/09/2011
SELECT convert(varchar, getdate(), 104)  --dd.mm.yyyy

Output:-
16.09.2011
SELECT convert(varchar, getdate(), 108)  --hh:mm:ss

Output:-
17:57:08
SELECT convert(varchar, getdate(), 109)  --mon dd yyyy hh:mm:ss:mmmAM (or PM) 

Output:-
Sep 16 2011 5:57:19:720PM
SELECT convert(varchar, getdate(), 110)  --mm-dd-yyyy

Output:-
09-16-2011
SELECT convert(varchar, getdate(), 111)  --yyyy/mm/dd

Output:-
2011/09/16
SELECT convert(varchar, getdate(), 112)  --yyyymmdd

Output:-
20110916
SELECT convert(varchar, getdate(), 113)  --dd mon yyyy hh:mm:ss:mmm

Output:-
16 Sep 2011 17:59:30:943
SELECT convert(varchar, getdate(), 114)  --hh:mm:ss:mmm(24h)

Output:-
17:59:44:887
SELECT convert(varchar, getdate(), 120)  --yyyy-mm-dd hh:mm:ss(24h)

Output:-
2011-09-16 17:59:55
SELECT convert(varchar, getdate(), 121)  --yyyy-mm-dd hh:mm:ss.mmm

Output:-
2011-09-16 18:00:13.497
SELECT convert(varchar, getdate(), 126)  --yyyy-mm-ddThh:mm:ss.mmm

Output:-
2011-09-16T18:00:28.987
SELECT replace(convert(varchar, getdate(), 111), '/', '')  --yyyy mm dd

Output:-
20110916
SELECT convert(varchar(7), getdate(), 126)   --yyyy-mm

Output:-
2011-09
SELECT right(convert(varchar, getdate(), 106), 8) -- mon yyyy

Output:-
Sep 2011

So this is the way to format date or date time in sql server using getdate() function.

I love your feedback.
Read more...

Google Gravity

I love google because google is always a fun and easy to use. Now, you can play with Google. Ricardo Cabello a designer/developer has developed Google Gravity. A fun filled site, in which the elements of the Google Home page are subjected to gravitational force and they fall down in front of your eyes, as illustrated in given below screenshot.
Google Gravity
Despite all fun you can still use Google Gravity to search the web. You can play with all elements in Google Gravity, like the Google logo or the search box or links or buttons. You can drag them and throw them or do whatever you like.

Google Gravity is the best example of the power of html 5.

What requires for Google Gravity

  • To enjoy this fun you need to have Google Chrome (Web Browser developed by Google) installed in your computer. Although it works in Safari and in Firefox too but its working best in Google Chrome.
  • Once you have installed Google Chrome then you are ready to enjoy the fun.
  • Log on to www.google.com or its regional version (www.google.pk etc.)
  • In the Google search type Google Gravity.
  • Now Press the I am feeling Lucky button below the Search bar, on the right or click on very first link or click on this link to enjoy the fun Google Gravity.
  • Now watch what happens :)

Play with Google Gravity and share your experience with me. I always love your feedback.
Read more...

JQuery - $ is not defined error

In this programming tutorial we will learn how to fix this JQuery - $ is not defined error. There are various reasons behind this error. Let's have a look on those reasons.

JQuery - $ is not defined error

  1. You have JavaScript running before the web page is fully loaded, and as such, before jQuery is fully loaded.
  2. Your JavaScript file is not being properly loaded into your web page.
  3. You might have a botched version of jQuery. This could happen because someone edited the core file, or a plugin may have overwritten the $ variable.

If you have firebug installed then you should also check the net panel to see if the file is actually being loaded properly. If not, it will be highlighted red and will say "404" beside it. If the file is loading properly, that means the issue is number 3.

Please confirm that all the javascript code is being run inside a code block such as:

$(document).ready(function () {
  //your code comes here
});

This will ensure that your code is being loaded after jQuery has been initialized.

One more thing that you must check is that you are not loading any jquery plugins before you load jQuery. Plugins extend the "$" object, so if you load a plugin before loading jQuery core, then you'll get the error you described.

So that's it. This is the way to get rid of this JQuery - $ is not defined nasty error.

I hope you will find this tutorial very interesting.

I love your feedback.
Read more...

Difference between .ToString() and Convert.ToString()

In this programming tutorial we will learn the difference between .ToString() and Convert.ToString() in asp.net. It is most commonly asked question in interview for a web developer post.
The only basic difference between them is Convert.ToString() function handles null while .ToString() does not handle null, in fact .ToString() will throw a NULL reference exception error. So for good coding practice always use Convert.ToString().

So that's it. I hope you will find this tutorial very handy.

I love your feedback.
Read more...

Count rows of all tables in a sql server database

In this programming tutorial we will learn how to count rows of all tables in a sql server database. we can find out all the tables present in a database along with their row count with the help of system tables.

Count rows of all tables in a sql server database

Select tbl.name, si.rows from sysindexes si
inner join sys.tables tbl on si.id = tbl.object_id and indid < 2

Sys.tables has each and every information about all the tables in a given database. While sysindexes contains all the information of all the indexes present in the database.


si.rows of the sysindexes give the row count associated with the given index.

Tbl.name gives the table name and comes from the sys.table.

si.id and tbl.object_id gives the unique ID associated with each table present in the database.

As far as indid is concerned, it stands for the ID of the index, 1 is for clustered index and (> 1) is for nonclustered index.

For SQL 2000 we need to do little modification in order to get the desired results.

select tbl.name, dd.rows from sysindexes dd

inner join sysobjects tbl on dd.id = tbl.id where dd.indid < 2 and tbl.xtype = 'U'

So that's it. This is the way to count rows of all tables in a ms sql server database.

I love your feedback.
Read more...

.XXX web domain registration starts

.XXX web domain registration starts. Companies and celebrities are being given the chance to safe their names from porn hijacking ahead of the launch of the .xxx web domain.

Brands/Celebrities can now request to have their name blocked from use with the new suffix, which goes live next year.

Existing adult sites can also submit their application to reserve a place on .xxx
The "red light" suffix is intended to make it easier to find or avoid sexually explicit material online.
ICM Registry, which is administering the launch, said it hoped to "promote a responsible approach to adult content".

Brand and IP holders wanting to register now have 50 days - a so-called "sunrise period" - to submit their application.

For security purpose, Companies and individuals that do not want their name associated with pornography will be able to pay a one-off fee of between $150 and $300 (£100 to £200), depending on which company they register their domain with. For instance, UK adult star Teresa May might wish to bid for a .xxx domain, whereas UK home secretary Theresa May might consider protecting her name.
Conflicts over exact matching names will go through an arbitration process.
"Win, win, win"
Companies are under no obligation to go .xxx, according to ICM Registry's chief executive Stuart Lawley.

But those that did would contribute to an overall "win, win, win" situation, with benefits for adult content providers, web users in search of pornography, and those wishing to avoid it.

"Regardless of what your personal views are on the existence of pornography on the internet, at least .xxx will give people the information they need to make a choice," said Mr Lawley.

However, Jerry Barnet, chairman of the Adult Industry Trade Association, warned that anti-pornography activists would likely increase their efforts to block online adult content.

"I have mixed feeling about it," he told BBC News. "From the industry and freedom of speech point of view, I'm concerned that pro-censorship and morality campaigners will use this as an excuse to try and introduce some form of censorship.

"But from a business point of view it's kind of good for us because there are new names available, and that makes branding and site naming more interesting," he added.
Malware issues
  ICM Registry does not process the applications directly. Firms must first approach a standard domain registrar in their home country, such as Go Daddy or Enom.

To ensure the registered porn sites do not harbour malware or present any other cyber security-related threats, ICM said they will be scanned daily by security firm McAfee - something that would make them safer to visit than many non-xxx sites.

The websites will be overseen by the International Foundation for Online Responsibility, and will be fitted with an electronic label to allow parents to adjust their browser settings and make sure children do not have access to certain sites.

After the sunrise period is over, a "land rush" period will run for 17 days, allowing prospective adult sites to register for the remaining .xxx addresses.

Following that, anyone else will be able to submit an application for non-reserved names on a first come, first served basis.

Source by BBC

 
Read more...

No value given for one or more required parameters. Import to excel error

In this programming tutorial we will learn how to fix this nasty error: No value given for one or more required parameters. Import to excel error. Few days ago one of my friend asked me to provide the code that import excel data to gridview. I gave him the link of the import excel data to gridview tutorial but he suddenly asked me that he is getting the above mentioned error. I checked his code and fixed the error. Let's have a look over how i fixed this error.

No value given for one or more required parameters. Import to excel error

             OleDbConnection oconn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath("~/test.xlsx") + ";Extended Properties=Excel 12.0;");
            oconn.Open();
            //Getting records from Sheet1 of excel file. As you know one excel file may have many sheets, in this case we are getting data from Sheet1                   
            string sqlQuery = "select * from [Sheet1$] where [user_name]=Lauren";
            OleDbCommand ocmd = new OleDbCommand(sqlQuery, oconn);
            DataSet ds = new DataSet();
            OleDbDataAdapter odapt = new OleDbDataAdapter(ocmd);
            odapt.Fill(ds);

My friend was showing the above mentioned code that it was giving this error: No value given for one or more required parameters. I checked the code and found below mentioned line as a guilty line, causing the error.

string sqlQuery = "select * from [Sheet1$] where [user_name]=Humaira Shafique";

The column(Parameter) user_name in excel file was containing string data so the value of column in where clause should be enclosed in single quote like given below.

string sqlQuery = "select * from [Sheet1$] where [user_name]='Humaira Shafique'";

This fix my friend's error but there are some more reasons that cause this error, these are
  1. Parameter name not spell correctly.
  2.  Case-Sensitivity issue in parameter (firstname instead of FirstName)

So that's it. I love your feedback.
Read more...

External table is not in the expected format - asp.net import excel data

In this programming tutorial we will learn how to fix this error: External table is not in the expected format. Few days ago one of my friend asked me to provide the code that import excel data to asp:gridview. I gave him the link of the import excel data to gridview article but he suddenly asked me that he is getting the above mentioned error. I checked his code and fixed the error. Let's have a look over how i fixed this nasty error.
External table is not in the expected format

This error normally occurs when trying to use an Excel 2007 file with a connection string that uses: Microsoft.Jet.OLEDB.4.0 and Extended Properties=Excel 8.0

Using the following connection string seems to fix this error.

public static string path = @"C:\Project\MyWeb\UploadedFiles\users.xlsx"; //Path of your excel located in server
public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";

That's it. Just change the connection string for Excel 2007- 2010 files.

I love your feedback.
Read more...

Get all database name in ms sql server

In this programming tutorial we will learn how to get all database name in ms sql server. It's a quite easy task to do and we just have to execute one line of query. Let's have a look over how to do so.
Get all database name in ms sql server

Select * from sys.databases

This can be used to fetch all the database name in ms sql server.

So that'it. I hope you will find this tutorial very informative.

I love your feedback.
Read more...

IETester - Browser Compatibility Check for Internet Explorer Versions from 5.5 to 10

In this tutorial I want to present a software, actually a web browser that every web developer should use, its name is IETester. IETester is a free (both for personal and professional usage) Web Browser that allows you to have the rendering and javascript engines of IE10 preview, IE9, IE8, IE7 IE 6 and IE5.5 on Windows 7, Vista and XP, as well as the installed IE in the same process.
Most of the time when I develop any website or develop any module and serve it to users then often I get complains that this div is not being shown properly in IE8, this list item is not aligned properly in IE 7, etc. Yeah you are thinking 100% right, we developers get designing issues 90% in Internet Explorer. And on our machine at the same time we have only one version of Internet Explorer installed. Sometime it gives us lot of tension when we have IE9 installed and we get issue related IE7. So to overcome this problem, we have now IETester Browser. Feel free to test your website in all the Versions of Internet Explorer at same time on a single machine.

Requirement: Windows 7, Windows Vista or Windows XP with IE7 minimum (Windows XP/IE6 config has some problems and IE8 instance do not work under XP without IE7)

Note for IE10: IETester installer does not include IE10 files, so you will need to install it itself. Also note that IE10 Preview requires Windows 7 to install on the machine.

IETester


Download IETester

Stay tuned with nice-tutorials.blogspot.com. Coming soon I have lot of software and tools to present in front of you that will enhance the capability and performance of your website.

I love your feedback.
Read more...

Display all the database login names in ms sql server

In this programming tutorial we will learn how to display all the database login names in ms sql server. Ever had a required when you wanted to display all the database login names. You won't believe how simple it is to get the list in ms sql server.
Display all the database login names in ms sql server 
Select * from sys.syslogins

Yeah that's it. This brief query will give you all the database login name(s).

So that's it. I hope you will find this tutorial very handy.

I love your feedback.
Read more...

Facebook is paying for security loopholes

Yeah its true, facebook is paying for security loopholes. Facebook has spent $40,000 (US Dollars) in the first 21 days of a program that rewards the finding of security bugs. The bug finding program aims to encourage security researchers to help harden Facebook against any attack.

One of security researcher has been already rewarded with more than $7,000 for finding six serious security bugs in facebook.com.

The program runs alongside Facebook's efforts to police the code it creates that keeps the social site running.

A blog post by Facebook chief security officer Joe Sullivan revealed some information about the early days of the bug bounty program.

He said the program had made Facebook more secure by introducing the networking site to "novel attack vectors, and helping us improve lots of corners in our code".

The minimum amount paid for a bug is $500, said Mr Sullivan, up to a maximum of $5000 for the most serious loopholes. The maximum bounty has already been paid once, he said.

Many cyber criminals and vandals have targeted Facebook in many different ways to get important information from people, promote spam or fake goods.

He also added that Facebook had internal bug-hunting teams, used external auditors to vet its code and ran "bug-a-thons" to hunt out mistakes but it regularly received reports about glitches from independent security researchers.

Facebook set up a system to handle these reports in 2010 which promised not to take legal action against those that find bugs and gave it chance to assess them.

Paying those that report problems was the logical next step for the disclosure system, he said.
Graham Cluley, senior technology consultant at Sophos, said many other firms, including Google and Mozilla, run similar schemes that have proved useful in rooting out bugs.

However, he said, many criminally-minded bug spotters might get more for what they find if they sell the knowledge on an underground market.

He added that the bug bounty scheme might be missing the biggest source of security problems on Facebook.

"They're specifically not going to reward people for identifying rogue third party Facebook apps, clickjacking scams and the like," he said. "It's those sorts of problems which are much more commonly encountered by Facebook users and have arguably impacted more people."

Facebook must consider setting up a "walled garden" that only allowed vetted applications from approved developers to connect to the social networking site, he said.

"Facebook claims there are over one million developers working for Facebook, so it's hardly surprising that the service is riddled with rogue apps and viral scams," he said.

Source by BBC


Read more...

Difference between delete and truncate commands

In this programming tutorial we will discuss the difference between delete and truncate commands. This is also a very important question asked in interview. The purpose of both delete and truncate is to clear the data but off course there are some differences due to them they both exists in ms sql server. So let's start.
Difference between delete and truncate commands

Delete
  1. Identity column value is not reset on DELETE operation.
  2. We can query with DELETE operation, such as ,
    delete * from users where user_name like '%a%'
  3. As logging is done for each row affected, deleting is a slow process. As when we execute a delete command on a table, log is generated for each row affected in the transaction log. Recording the log for each row, not only slow down the performance but it also increase the size of transaction file to a very large extent, this problem is more visible when you have to delete large amount of data in a table.
  4. We can have triggers associated with DELETE operation.
  5. We can delete one row or all the rows of the the table.
Truncate
  1. Identity column reset on TRUNCATE operation
  2. We cannot have query with TRUNCATE operation
  3. As logging is done only when pages are de-allocated. It is faster than DELETE operation. This is because of TRUNCATE logging is not done for each row affected as a result of the operation. When truncate operation is performed on the table,data is not removed, but actually the whole data pages is de-allocated and pointers to the indexes are removed. As such data remain there until it is over written by new data. At this point you might be thinking that TRUNCATE operation is not logged,but this is not the fact. In case of TRUNCATE operation the de-allocation of pages is logged in the log file.
  4. We cannot have triggers associated with TRUNCATE operation
  5. We can only TRUNCATE the whole table, means we can remove all the rows of the table, if rows exist. We cannot remove single row.


So that's it. These are the differences between delete and truncate commands.

I hope you will find this tutorial very handy.

I love your feedback.
Read more...

Split Function in ms sql server to split comma separated string into table

In this programming tutorial we will learn how to create and use split function in ms sql server to split comma separated string into table. Ms sql server does not have any built-in split function. In this tutorial we will create a split function to convert a comma-separated string value such as (‘adeel fakhar,abdur rehman,Irfan Ghani’) into a temporary table with each string as rows.

Split Function in ms sql server to split comma separated string into table


The below mentioned split function is table-valued function that will help us to split comma separated (or any other delimiter value) string to individual strings.

CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))     
returns @temptable TABLE (username varchar(8000))     
as     
begin     
	declare @idx int     
	declare @slice varchar(8000)     
    
	select @idx = 1     
		if len(@String)<1 or @String is null  return     
    
	while @idx!= 0     
	begin     
		set @idx = charindex(@Delimiter,@String)     
		if @idx!=0     
			set @slice = left(@String,@idx - 1)     
		else     
			set @slice = @String     
		
		if(len(@slice)>0)
			insert into @temptable(username) values(@slice)     

		set @String = right(@String,len(@String) - @idx)     
		if len(@String) = 0 break     
	end 
return     
end

The Split function takes two parameters, first one is the string and second one is the delimiter to split that string. To call this function, you will write the following statement
select * from dbo.split('adeel fakhar,abdur rehman,irfan ghani',',')

Output:-
adeel fakhar
abdur rehman
irfan ghani

So that's it. This is the way to create and use split function in sql server.

I hope you will find this tutorial very informative.

I love your feedback.
Read more...

Using EXCEPT and INTERSECT to compare tables

In this programming tutorial you will learn how to compare tables in ms sql server using EXCEPT and INTERSECT. This feature comes from SQL SERVER 2005, returns distinct values by comparing the results of two queries. They are very easy to understand and work. So let's start.

Using EXCEPT and INTERSECT to compare tables



EXCEPT returns any distinct values from the left side query that are not also found on the right side query.

INTERSECT returns any distinct values that are returned by both the query on the left and right sides of the INTERSECT operand.

The basic rules that you must have to follow for combining the result sets of two queries that use EXCEPT or INTERSECT are the following:

  • The number and the order of the columns must be the same in all queries.
  • The data types must be compatible.

To return all rows in table1 that do not match exactly the rows in table2, we will use EXCEPT like this:

select * from table1 except select * from table2


To return all rows in table2 that do not match exactly in table1, we reverse the EXCEPT:

select * from table2 except select * from table1


And to return all rows in table1 that match exactly what is in table2, we will use INTERSECT:

select * from table1 intersect select * from table2


Note:-  When you compare rows for determining distinct values, two NULL values are considered equal. The column names of the result set that are returned by EXCEPT or INTERSECT are the same names as those returned by the query on the left side of the operand. Column names or aliases in ORDER BY clauses must reference column names returned by the left-side query.
The nullability of any column in the result set returned by EXCEPT or INTERSECT is the same as the nullability of the corresponding column that is returned by the query on the left side of the operand.

we can return a listing of all rows from either table that do not match completely by using UNION ALL to combine the results of both EXCEPT queries:
select 'table1' as tblName, *  from
  (select * from table1
   except
   select * from table2) x
union all
select 'table2' as tblName, *  from
  (select * from table2
   except select * 
   from table1) x

We can also write a simple stored procedure that compares any two tables (Remember the schema of both tables must match) like this:
create procedure CompareTables @table1 varchar(100), @table2 varchar(100)
as
  declare @sql varchar(8000)
  set @sql = 'select ''' + @table1 + ''' as tblName, *  from
      (select * from ' + @table1 + '
       except
       select * from ' + @table2 + ') x
    union all
    select ''' + @table2 + ''' as tblName, *  from
      (select * from ' + @table2 + '
       except
       select * from ' + @table1 +') x'

  exec(@sql)

Definitely, both tables must have primary keys in place; duplicate values in these tables will not make logical sense when trying to determine which rows match or not.

So that's it, EXCEPT and INTERSECT to compare tables are pretty handy.

I hope you will find this tutorial very informative.

I love your feedback.

Read more...

Update data in one table with data of another table

In this programming tutorial we will learn how to update data in one table with data of another table. Let's have a look over the example given below.
Update data in one table with data of another table

Table Structures and values:

TableA consists of four columns: a, b, c, d (a is the primary key)

TableB consists of five columns: a1, b1, c1, d1, e1 (a1 and b1 together made the primary key for this table)

The foreign key relationship between the two tables is based on A.a = B.a1

The data in these 2 tables is as follows:

TableA

a b c d
1 x y z
2 a b c
3 t x z

TableB

a1 b1 c1 d1 e1
1 x1 y1 z1 40
2 a1 b1 c1 50

Now our requirement is to write a query to update columns b, c and d in TableA from the columns b1, c1 and d1 from TableB where-ever the join condition satisfies and e1 > 40 in TABLEB. So let's have a look over the query written below for this task.

UPDATE TABLEA SET b = TABLEB.b1, c = TABLEB.c1, d = TABLEB.d1 FROM TABLEA, TABLEB
WHERE TABLEA.a = TABLEB.a1
AND TABLEB.e1 > 40


When you execute this query then you will find the output given below.

a b c d
- - - - - -
1 x y z
2 a1 b1 c1
3 t x z

So that's it. I hope you will find this tutorial very handy.

I love your feedback.
Read more...

Rename stored procedure in ms sql server

In this programming tutorial we will learn how to rename stored procedure in ms sql server. Its quite easy and a one line command to execute. So let's have a look over the command given below

Rename stored procedure in ms sql server

Syntax:
sp_rename 'procedure_name1', 'procedure_name2'

procedure_name1 is the current name of the stored procedure whereas procedure_name2 is the new name of the stored procedure.

A stored procedure can be renamed. The new name should follow the rules for identifiers.

EXEC sp_rename 'spCurrentName', 'spNewName';

So that's it. Stored Procedure has been renamed successfully.

I hope you will find this tutorial very informative. I love your feedback.
Read more...

Delete duplicate rows without primary key in ms sql server

In this programming tutorial we will learn how to delete duplicate rows without any primary key in ms sql server. This is the most common question asked in interview. In this programming tutorial we will create a temporary table and then insert some duplicate rows in it and finally we will delete these duplicate rows. So let's have a look.

Delete duplicate rows without primary key in ms sql server

Create Temporary Table
create table #my_temp_table
(
user_name varchar(30),
user_type varchar(30)
)
Insert Rows
insert into #my_temp_table values('abdur rehman','admin')
insert into #my_temp_table values('adeel fakhar','admin')
insert into #my_temp_table values('adeel fakhar','admin')
insert into #my_temp_table values('irfan ghani','user')
insert into #my_temp_table values('waqar shafique','moderator')
insert into #my_temp_table values('waqas beg','contributor')
Now we have temporary table in our database, when we perform select * then we will get following records


Retrieving Records - Rows
select * from #my_temp_table

Output:-
Delete Duplicate Rows
In above picture i have highlighted the duplicate row, the row that we want to delete. We will use the built-in function ROW_NUMBER() that comes with ms sql server 2005. ROW_NUMBER() Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.  

Syntax of ROW_NUMBER()
ROW_NUMBER ( )     OVER ( [  ]  )
<partition_by_clause> </partition_by_clause>

Divides the result set produced by the FROM clause into partitions to which the ROW_NUMBER function is applied.

<order_by_clause>

Determines the order in which the ROW_NUMBER() value is assigned to the rows in a partition. For more information, see ORDER BY Clause (Transact-SQL). An integer cannot represent a column when the <order_by_clause> is used in a ranking function.

The return type of ROW_NUMBER() is bigint. Remarks The ORDER BY clause determines the sequence in which the rows are assigned their unique ROW_NUMBER within a specified partition. Ok, we have learn enough about ROW_NUMBER() function, now let's come back to our tutorial.

For generating row number we have to write this query

select * 
from 
(
	SELECT ROW_NUMBER () OVER (ORDER BY ( USER_NAME )) AS sr_no ,* from #my_temp_table 
) as A 


Output:-


As you have seen, we generated unique row number for every row, now its easy for us to delete the duplicate row. For instance i want to delete the third row, so i will query like this.

delete a 
from
(
	SELECT ROW_NUMBER () OVER (ORDER BY ( USER_NAME )) AS sr_no ,* from #my_temp_table 
) as A where sr_no = 3

The above query will delete the third row.

Output:-


Note:- The scope of this tutorial is now limited to the temporary table, you can apply this technique to user tables as well. Moreover, very soon i will write a tutorial that will demonstrate how to delete all duplicate rows without any primary key dynamically in ms sql server, without hard coding any thing.

So that's it. I love your feedback.
Read more...

Get url parameters and their values using javascript

In this programming tutorial, we will learn how to get url parameters and their values using javascript. Recently, while working on a project, i needed to get parameter values from url string of the current web page. So let's have a look over how i made this happen.

Get url parameters and their values using javascript

// Read the page's GET url variables and return them as an associative array.
function getUrlParametersVals()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
Now let's have a look over how to call this getUrlParametersVals() function.

This function returns an associative array with url parameters and their values. For example, let's suppose we have the following URL

http://www.yourwebsitecom/contact.php?name=Adeel&country=Pakistan 

Calling getUrlParametersVals() function would return you the following array:
{
    "name"    : "Adeel",
    "country" : "Pakistan"
}
To get the value of first parameter you will do this
var myName = getUrlParametersVals()["name"];
To get the value of second parameter you will do the same
var myCountry = getUrlParametersVals()["country"];
So that's it. 


I hope you will find this tutorial very informative. 

I love your feedback.
Read more...