Friday, January 31, 2014

Understanding Cisco UCS VIF Paths

Understanding Cisco UCS VIF Paths


In the Cisco UCS world where a virtual NIC on a virtual server is connected to a virtual port on a virtual switch by a virtual cable, it is not surprising that there can be confusion about what path packets are actually taking through the UCS infrastructure.
Similarly knowing the full data path through the UCS infrastructure is essential to understanding troubleshooting and testing failover.
I’m sure you have all seen the table below in UCS Manager where it details the path that each virtual NIC or HBA takes through the infrastructure. But what do all these values mean? And where are they in the infrastructure? That is the objective of this post.
vif paths
Figure 1
I will also detail the relevant CLI commands to confirm, and troubleshoot the complete VIF (Virtual Interface) Path.
If you have ever seen and understood the film “Inception” you should have no problem understanding Cisco UCS, where virtual machines are run on virtual hosts which run on virtual infrastructure and abstracted hardware :-) but in all seriousness it’s really not that complicated.
The diagram below shows a Half width blade with a vNIC called eth0 created on a Cisco VIC (M81KR) with its primary path mapped to Fabric A. For simplicity only one IO Module to Fabric Interconnect link is shown in the diagram, as well as only one of the Host Interfaces (HIFs / Server facing ports) on the IO module. In this post I will focus in on eth0 which is assigned virtual circuit 749.
Figure 2
Virtual Circuit
First column in figure 1, Virtual Circuit number, this is a unique value assigned to the virtual circuit which comprises the virtual NIC, the virtual cable (red dotted line in figure 2) and the virtual switch port. The virtual switch port and virtual circuit have the same identifier in this case 749.
If you do not know which virtual circuit will be used for the particular MAC address you are interested in, or which Chassis and Server that virtual circuit resides on, you can use the below commands to find out.
Figure 3
The above output shows that the MAC address is behind Veth749, now in order to find out which Chassis and Server is using Veth749 issue the below command.
Figure 4
The Interface to which Veth749 is bound to is Ethernet 1/1/2 which equates to Chassis1 Server 2 (you can ignore the middle value) the description field also confirms the location and virtual interface name on the server (eth0)
As you know, (having read my blog post on “Adapter FEX”:-) ) the M81KR “PALO” adapter is actually a mezzanine fabric extender just like the IO Module (FEX) in the Chassis. What this means is when I create a virtual interface on the adapter, that interface is actually created and appears as a local interface on the Fabric Interconnect (FI), whether it’s a vNIC which appears as a Veth port on the FI or a vHBA which appears as a Vfc interface.
This means we will have many virtual circuits or “virtual cables” going down the physical cable, Cisco UCS obviously needs to be able to differentiate between all these “virtual cables”, and it does so by attaching a Virtual Network TAG (VN-TAG) to each virtual circuit. This way the Cisco UCS can track and switch packets between virtual circuits, even if both of those virtual circuits are using the same physical cable, which the laws of Ethernet would not normally allow.
Adapter Port
The Cisco VIC (M81KR) has two physical 10Gbs traces (paths / ports) one trace to Fabric A and one trace to Fabric B. This is how the VIC can provide hardware fabric failover and fabric load balancing to its virtual interfaces.These adapter ports are listed as 1/1 to Fabric A and 2/2 to Fabric B.
In the case of a Full Width blade, which can take 2 Mezzanine adapters this obviously doubles the number of paths to four.
In the case of the VIC 1240 and VIC 1280 which have 20Gbs and 40Gbs to each fabric respectively there is still only a single logical path to each fabric as the links are hardware port channels 2x10Gbs per fabric for the VIC 1240 and 4x10Gbs per fabric in the case of the VIC 1280.
The new M3 servers which have LAN on board (mLOM) provide additional on board paths.
Fex Host port
In the lab setup I am using, the FEX modules are 2104XP’s which have 8 internal Server facing ports (Sometimes referred to as Host Interfaces (HIFs)),which connect to the Blade slots, port 1 to blade slot 1, port 2 to blade slot 2 and so on
Fex Network Port
The 2104XP IO Modules also have 4 Network Interfaces (NIFs / Fex Uplinks) which connect to its upstream Fabric Interconnect.
Figure 5
Fabric Interconnect 
The 2 FI interfaces listed in Figure 1 are FI Server Port and FI Uplink
The server facing ports on the Fabric Interconnect are called FI Server Ports and can be confirmed in the output of the “Show Interface fex-fabric” command. The FI server ports are listed in the second column “Fabric Port”. In figure 5
The FI Uplink interface can be found by checking the pinning of the Veth interface.
Figure 6
As can be seen from the above figure, Veth749 is pinned to FI Uplink (Border Interface) Port-Channel 1
If using VIC1240 or VIC1280′s then there are mandatory hardware port channels for all the ports of those cards that are in the same port-port group (fabric) that’s why you see a port-channel Id as the adapter port in the VIF paths tab.
You can see this by connecting into the NXOS element of the FI and you can do. “Sh port-channel summary” and you will see you port-channels I.e Po1292 and the member ports will be the Host interfaces (HIFs) on the IOM that map to that blade slot.

Armed with all the above you should now have the information necessary to understand the packet flow within the UCS and be able to troubleshoot as well as monitor and understand failover.
Hope this helps.

Getting to Know your UCS Fabric Interconnect Neighbors

Getting to Know your UCS Fabric Interconnect Neighbors


Cisco devices use the Cisco Discovery Protocol (CDP) to know to what and how they are connected.  This CDP information is important to know and can usually help trouble shoot an issue or help you map out your network. Now that UCS firmware version 2.0 supports disjoint layer 2 networks CDP is even more import as your Fabric Interconnects can be connected to more than just one pair of upstream switches.
The Cisco UCS Fabric Interconnect supports CDP and “show” commands can be used to see the CDP information.  However, the CDP information is tucked away in the nxos context of the Fabric Interconnect. When you first connect to a UCS Command Line Interface (CLI) you are placed into the UCS Manager.
There are other contexts that can be accessed from the CLI, among them are the local management (local-mgmt) context and the nxos context. The CDP information can be accessed by connecting the nxos context and running the appropriate show commands.
Readers that are familiar with nxos as well as other Cisco CLI commands for CDP information should feel comfortable enough with to gather the CDP information. However if you are new to nxos and/or the UCS Fabric Interconnect, here is how a session to get CDP information might go.
login as: admin
Cisco UCS 6100 Series Fabric Interconnect
Using keyboard-interactive authentication.
Password:
dcn-ucs-6100-A# connect nxos
dcn-ucs-6100-A(nxos)# show cdp neighbors
Capability Codes: R - Router, T - Trans-Bridge, B - Source-Route-Bridge
S - Switch, H - Host, I - IGMP, r - Repeater,
V - VoIP-Phone, D - Remotely-Managed-Device,
s - Supports-STP-Dispute
Device-ID             Local Intrfce Hldtme Capability  Platform      Port ID
dcn-ucs-6100-B(SSI13360G3N)mgmt3         135    S I s     N10-S6100     mgmt3
DCN-N5K1(SSI13030DFR) Eth1/9        126    S I s     N5K-C5020P-BF Eth1/27
DCN-N5k2(SSI130205W5) Eth1/10       177    S I s     N5K-C5020P-BF Eth1/27
N1KV-VSM-1(1448598099128304034)Eth1/1/1      152    R S I s   Nexus1000V    Eth5/1
N1KV-VSM-1(6188615601316121710)Eth2/1/5      176    S I s     Nexus1000V    Eth3/1
N1KV_VSM(1088889199130439530)Eth2/1/6      172    S I s     Nexus1000V    Eth3/1

I can see what the Fabric Interconnect is connected to and from which port, plus I can see the peer ports to which the Fabric Interconnect is connected.
The output above is from the primary Fabric Interconnect, because when you connect to the UCS Manager virtual IP address (VIP) the connection is made to the primary Fabric Interconnect, however when the connection to the nxos context is made you can choose which Fabric Interconnect nxos context to connect to as shown below;
dcn-ucs-6100-A# connect nxos a
dcn-ucs-6100-A(nxos)#
or
dcn-ucs-6100-A# connect nxos b
dcn-ucs-6100-B(nxos)#

Here is the output from the B Fabric Interconnect
dcn-ucs-6100-B(nxos)# show cdp neighbors
Capability Codes: R - Router, T - Trans-Bridge, B - Source-Route-Bridge
S - Switch, H - Host, I - IGMP, r - Repeater,
V - VoIP-Phone, D - Remotely-Managed-Device,
s - Supports-STP-Dispute
Device-ID             Local Intrfce Hldtme Capability  Platform      Port ID
dcn-ucs-6100-A(SSI13360FZ4)mgmt3         166    S I s     N10-S6100     mgmt3
DCN-N5K1(SSI13030DFR) Eth1/9        139    S I s     N5K-C5020P-BF Eth1/28
DCN-N5k2(SSI130205W5) Eth1/10       159    S I s     N5K-C5020P-BF Eth1/28
N1KV-VSM-1(1448598099128304034)Eth1/1/1      170    R S I s   Nexus1000V    Eth5/2
N1KV-VSM-1(6188615601316121710)Eth1/1/5      165    S I s     Nexus1000V    control0
N1KV-VSM-1(1448598099128304034)Eth2/1/1      122    R S I s   Nexus1000V    Eth4/2
N1KV-VSM-1(6188615601316121710)Eth2/1/5      179    S I s     Nexus1000V    Eth3/2
N1KV_VSM(1088889199130439530)Eth2/1/6      174    S I s     Nexus1000V    Eth3/2

Either the A or B Fabric Interconnect can be the primary, roles can change based on events, outages, firmware upgrades, forced role change, etc.
From the output shown so far, Fabric Interconnect A is the primary it was the Fabric Interconnect that was connected to when the ssh session was started with the UCS VIP.  The Fabric Interconnect is named at setup to have a “-A” or “-B” suffixed to the UCS name. From command line either the primary or subordinate Fabric Interconnect nxos contexts can be connected to, just supply the Fabric Interconnect letter at the end of the connect command.
So far this may not be new to most, but what if automation is needed to find the CDP neighbor information from all your UCS systems, possibly hundreds of Fabric Interconnects. A simple expect,http://www.nist.gov/el/msid/expect.cfm, script can do the job. The script shown below will connect to the CLI of the Fabric Interconnect, connect to the nxos context of each Fabric Interconnect and issue the “show cdp neighbors” command.
Script
 #!/usr/bin/expect --  
 #  
 # show-fi-cdp.sh  
   
 #  
 # Execute a show for cdp neighbors on both Fabric Interconnects  
 #  
 # John McDonough (jomcdono)  
 #  
   
 set timeout -1  
 set ucsUser [lindex $argv 0]  
 set ucsPass [lindex $argv 1]  
 set ucsHost [lindex $argv 2]  
   
 #check if all were provided  
   
 if { $ucsUser == "" || $ucsPass == "" || $ucsHost == "" }  {  
  puts "\n   Usage: $argv0   \n"  
  puts "   Where:\n"  
  puts "         User - UCS user name"  
  puts "         Pass - UCS user password"  
  puts "         Host - UCS host\n"  
  puts "\n"  
  puts "         Displays UCS CDP information:\n"  
   
 exit 1  
 }  
   
 # Open and ssh connection to UCS  
   
 log_user 0  
 spawn ssh $ucsUser@$ucsHost  
   
 expect {  
  "Are you sure you want to continue connecting*" {  
  send "yes\r"  
   
  expect "*assword:"  
  send "$ucsPass\r"  
  }  
   
  "*assword:" {  
   send "$ucsPass\r"  
  }  
 }  
   
 expect "# "  
   
 set command "show cdp neighbors | no-more"  
   
 # connect nxos  
   
 send "connect nxos a\r"  
 expect "A(nxos)#"  
 send "$command\r"  
 expect "A(nxos)#"  
   
 puts [string trimleft $expect_out(buffer) $command]  
 send "exit\r"  
   
 expect "# "  
 send "connect nxos b\r"  
 expect "B(nxos)#"  
 send "$command\r"  
 expect "B(nxos)#"  
   
 puts [string trimleft $expect_out(buffer) $command]  
   
 # Finished  
   
 exit 0 
Output

./show-fi-cdp.sh admin password 10.10.10.10
Capability Codes: R - Router, T - Trans-Bridge, B - Source-Route-Bridge
S - Switch, H - Host, I - IGMP, r - Repeater,
V - VoIP-Phone, D - Remotely-Managed-Device,
s - Supports-STP-Dispute
Device-ID             Local Intrfce Hldtme Capability  Platform      Port ID
dcn-ucs-6100-B(SSI13360G3N)mgmt3         126    S I s     N10-S6100     mgmt3
DCN-N5K1(SSI13030DFR) Eth1/9        120    S I s     N5K-C5020P-BF Eth1/27
DCN-N5k2(SSI130205W5) Eth1/10       170    S I s     N5K-C5020P-BF Eth1/27
N1KV-VSM-1(1448598099128304034)Eth1/1/1      174    R S I s   Nexus1000V    Eth5/1
N1KV-VSM-1(1448598099128304034)Eth2/1/1      126    R S I s   Nexus1000V    Eth4/1
N1KV-VSM-1(6188615601316121710)Eth2/1/5      139    S I s     Nexus1000V    Eth3/1
dcn-ucs-6100-A(nxos)#0439530)Eth2/1/6      134    S I s     Nexus1000V    Eth3/1
Capability Codes: R - Router, T - Trans-Bridge, B - Source-Route-Bridge
S - Switch, H - Host, I - IGMP, r - Repeater,
V - VoIP-Phone, D - Remotely-Managed-Device,
s - Supports-STP-Dispute
Device-ID             Local Intrfce Hldtme Capability  Platform      Port ID
dcn-ucs-6100-A(SSI13360FZ4)mgmt3         170    S I s     N10-S6100     mgmt3
DCN-N5K1(SSI13030DFR) Eth1/9        144    S I s     N5K-C5020P-BF Eth1/28
DCN-N5k2(SSI130205W5) Eth1/10       164    S I s     N5K-C5020P-BF Eth1/28
N1KV-VSM-1(1448598099128304034)Eth1/1/1      169    R S I s   Nexus1000V    Eth5/2
N1KV-VSM-1(6188615601316121710)Eth1/1/5      164    S I s     Nexus1000V    control0
N1KV-VSM-1(1448598099128304034)Eth2/1/1      121    R S I s   Nexus1000V    Eth4/2
N1KV-VSM-1(6188615601316121710)Eth2/1/5      178    S I s     Nexus1000V    Eth3/2
dcn-ucs-6100-B(nxos)#0439530)Eth2/1/6      173    S I s     Nexus1000V    Eth3/2

Whether you take this script and modify it or just use the commands manually, knowing your Fabric Interconnect neighbors is going to come in handy at some point.

Sunday, January 5, 2014

Syntax Differences Between C++ And Java

Syntax Differences Between C++ And Java  
 
Syntactical differences between Java and C++ are small, but important. It can become difficult for a coder, especially when they are moving from C++ to Java.  
 Are you having a tough time differentiating between C++ and Java? Do you keep using the semicolon when you're not supposed to? While the two languages are similar, there are certain syntactical differences that can be confusing. Here’s something that will come in handy.
C++, Java, java programming, C++ programming, programming tips, C++ Java difference, C++ syntax, Java syntax, Java C++ syntax difference, Java tips, C++ tips, tech news, news




The main function

C++

int main( int X, char* Y[])
{
printf( "Hello, world" );
}

Java

Every function in Java has to be made a part of a class. So, the main function also has to be a part of a class. Moreover, in Java there is one main() function for every class. This can come in handy when writing unit tests for the class.

class HelloWorld
{
public static void main(String X[])
{
System.out.println( "Hello, World" );
}
}

Compiling

C++

In C++, you will be compiling as,

g++ X.cc -o outfile

This will then be run with,

./outfile

Java

In Java, you will compile the classes in X.java.

javac X.java

You have to run this by invoking the static main method.

Class declarations

While C++ requires a semicolon at the end of class declarations, Java does not have any such requirement.

C++

class X{};

Java

class X{}

Method declarations

A method declaration in Java must be a part of a class always. Otherwise, both the languages are quite the same syntactically on this front. You can also use the public, private and protected access specifications in Java.

Constructors and destructors

In the case of constructors, the syntax in both C++ and Java is the same. Java though has no exact replacement for destructors.

Static members

Static members (variables and functions) are also declared in the same way in both the languages. But, Java allows for static initialisation blocks in order to initialise static variables.

class Foo
{
static private int x;
// static initialization block
{ x = 5; }
}

Scoop static namespaces and methods

C++

In C++, you will use the Class::method form in order to scoop static methods.

class MyClass
{
public:
static do();
};

Use this by,

MyClass::do();

Java

In Java, on the other hand, scooping comes with the use of the .again parameter. This is similar to accessing the fields of a class.

class MyClass
{
public static do()
{
// do something
}
}

To use the static method.

MyClass.doStuff();

Object declarations
C++

// on the stack
myClass x;

// or on the heap
myClass *x = new myClass;

Accessing fields from various objects

C++

In order to access fields from classes and other such objects, the programmer has to use dots.

myClass x;
x.field;

If a pointed is involved, then the narrow operator (->) has to be used.

myClass x = new MyClass();
x->field;

Java

In Java, only the dot is used. Since we always use references in Java, even pointers are accessed using the dot.

myClass x = new MyClass();
x.field;

Protection levels

They are specified in a different manner.

C++

public:
void X();
void Y();

Java

public void X();
public void Y();


Virtual functions

C++

virtual int X();

Virtual functions can also be used non virtually. You can simply say into X().

Java

int foo(); // or, final int foo();

In Java, functions are always virtual by default. You use ‘final’ in order to avoid them from being overridden.

Abstract Classes

C++

All you need to do is include public virtual functions./

class X{ public: virtual void X() = 0; };

Java

In Java the syntax allows the programmer to be explicit.

abstract class X{ public abstract void X(); }

If you want to specify an interface, then say,
interface X{ public void foo(); }

In that case though, you will have to implement it by,
class Y implements X
{
public void M() { /* do something */ }
}

Memory management

This is also pretty much the same in both the languages, except that Java has garbage collection, so no delete for Java. 
9 Extensions To Make Your Internet Browser Safer!  
 
Browser extensions act as your first line of defense against attacks. Here we bring some for you...  
 Secure browsing is the order of the day. A number of websites use ad networks and tracking scripts and many of these are responsible for putting you in the sight of a hacker. Fortunately, there are many browser extensions that can help you protect yourself from such attacks. Here are nine of them!
Firefox, Chrome, Internet Explorer, Safari, Mozilla, Microsoft, Google, Apple, Chrome extensions, Firefox extensions, Mozilla extensions, browser extensions, secure browsing, technology news, news




1. NoScript Security Suite: This extension for Mozilla’s Firefox Internet browser blocks unsafe scripts from running on the browser. It protects the user from XSS, Cross-zone DNS binding, router hacking, Clickjacking and other attacks. The user has to define what kind of websites can launch their scripts on the browser.

2. Webutation: This extension runs on both the Firefox and Google Chrome browsers. It is one of the quickest and best ways to find out how safe a particular website is. It is an open source resource that collects data from the users in the community and scores websites’ security from 0 to 100 with 100 being the best score.

3. Secure Sanitizer: This is a tool that makes the Firefox browser more secure. It clears your web browser cache using the file system simple deletion, random data overwriting or the US DoD 5220 methods.

4. WOT: Compatible with the Chrome browser, this adds three icons to your search results. The icons denote whether a website is safe, questionable or completely unsafe. There is a green, amber and red icon for each respectively.

5. Disconnect: This extension is available for Firefox, Chrome, Internet Explorer and Safari and is very useful for preventing the tracking of your cookies. The extension shows you whenever tracking requests come in and you can choose whether to allow them or not.

6. LastPass: This is a password manager that is compatible with Google Chrome. It puts in a master password for all your separate web logins. You can login to all your accounts using that one master password.

7. NotScripts: This Chrome extension was inspired by the NoScript extension for Firefox. It prevents JavaScript on webpage from running and lets you choose where it is allowed to run.

8. Adblock Plus: This is available for both the Google Chrome and Firefox browsers and blocks tracking scripts. In the default settings it blocks both ads and tracking scripts.

9. Ghostery: This does the same job as Adblock Plus. It is compatible with Google Chrome and blocks advertisements and tracking scripts. It also provides you with information on ad networks and links to their privacy policy.

10 Video Tutorials With Over 200 Videos To Learn PHP Programming

10 Video Tutorials With Over 200 Videos To Learn PHP Programming!   
 
Get ready to make your own dynamic websites with these useful video tutorials on PHP programming.  
 When designing web pages, many programmers prefer to use PHP over HTML. While HTML creates static web pages, PHP is known for its dynamic web pages. These videos will show you how to code in PHP along with the programming language's history and a little more. We hope it helps!
PHP, PHP tips, programming tips, PHP commands, PHP methods, PHP news, PHP tricks, special methods in PHP, PHP coding, video tutorials on PHP, PHP video tutorials, PHP tutorials




1. Learn PHP in 15 minutes

This tutorial starts from the beginning and shows you how to start writing scripts in PHP.

2. PHP Tutorial 1 - Introduction (PHP For Beginners)

This tutorial covers a short presentation on what PHP is and what is required to learn it. It serves as a good introduction to the popular programming language.

3. Introduction To PHP - A Complete PHP Tutorial for Absolute Beginners

This tutorial covers the basics such as what is PHP, some past, present and future notes on PHP and what it's used for as well as how it works.

4. Lecture 1 "PHP". Building Dynamic websites. Harvard OpencourseWare. CS E-75

Harvard instructor David J. Malan talks about the programming language in this Harvard lecture on PHP.

5. PHP UK Conference 2013 - Richard Johnson - PHP is evil (Defensive programming)

This talk will attempt to cover a wide range of web system security considerations, including evolution of PHP's security features, general PHP development best practices, considerations when using underlying C libraries, fun PHP functions and unexpected results, cool “features” in browsers, LAMP stack design and configuration for security, common mistakes and gotcha’s, security antipatterns and fallacies, how to review code and think securely.

6. PHP Tutorials

This playlist from TheNewBoston consists of 200 videos on PHP and how to go about programming in this language. It starts with installing PHP and goes up to the depths of the language.

7. PHP Tutorials: Create a CMS

This is the first of a seven part video that teaches you how to create a CMS with the PHP programming language.

8. PHP Programming Part 5: HTML Forms and PHP Programming

This video teaches you how to create forms in HTML and then pass them to PHP. HTML creates static web pages, while PHP creates dynamic web pages.

9. Intermediate OOP in PHP

This is the Intermediate OOP in PHP talk from the Front Range PHP User Group meeting held in June 2013.

10. PHP - Classes and Object Instantiation

This tutorial video covers many basic concepts of PHP that are hard to find elsewhere. It can be a treasure for those learning the language. 

21 Tips And Tricks For JavaScript Programmers

21 Tips And Tricks For JavaScript Programmers  
 
If you work on the popular JavaScript programming language, we bring you some useful tips and tricks. Read on...  

 Have you been programming in JavaScript? It's an important language, but you may be missing out on some of the important tips and tricks here. Use them to make your webpages better and more advanced!
JavaScript, Java programming, JS programming, programming tips, JavaScript tips and tricks, JavaScript tutorials, JS tutorials, JS tips and tricks, JS news, JS tips, JS programming tips




1. Convert a JavaScript Array into the Comma Seperated Value (CSV) format

The valueOf() method is used to convert a javascript array into the CSV format.

var arr = ['abc', 'bcd', 'cde', 'def'];

var str = arr.valueOf();

//print str: abc,bcd,cde,def


You can also use the pipe (|) instead of commas. For this you have to use the join() method.

var arr = ['abc', 'bcd', 'cde', 'def'];

var str = arr.join("|");

//print str: abc|bcd|cde|def


2. Converting CSV into Javascript array

For this you will use the split() method. The method can be used to split a string separated by any token into a Javascript array.

var str = "a, b, c, d";

var arr = str.split(",");

//print arr[0]: a


3. Remove elements of an array by their index

Use the splice() method for this. The splice method can add and remove elements from an array.

function removeByIndex(arr, index) {
arr.splice(index, 1);
}

test = new Array();
test[0] = 'Apple';
test[1] = 'Ball';
test[2] = 'Cat';
test[3] = 'Dog';

alert("Array before removing elements: "+test);

removeByIndex(test, 2);

alert("Array after removing elements: "+test);


4. Remove elements of an array by value

function removeByValue(arr, val) {
for(var i=0; i if(arr[i] == val) {
arr.splice(i, 1);
break;
}
}
}

var somearray = ["mon", "tue", "wed", "thur"]

removeByValue(somearray, "tue");

//somearray will now have "mon", "wed", "thur"


A method (removeByValue in example) has to be defined for removing elements by their value. New functions can be defined to classes at runtime in Javascript using prototypes.

In the code fragment given below, a removeByValue() method has been created inside the Array class.

Array.prototype.removeByValue = function(val) {
for(var i=0; i if(this[i] == val) {
this.splice(i, 1);
break;
}
}
}
//..

var somearray = ["mon", "tue", "wed", "thur"]

somearray.removeByValue("tue");

//somearray will now have "mon", "wed", "thur"


5. Call a JavaScript function as a string

The code fragment given below allows you to call a function simply by its name.

var strFun = "someFunction"; //Name of the function to be called
var strParam = "this is the parameter"; //Parameters to be passed in function

//Create the function
var fn = window[strFun];

//Call the function
fn(strParam);


6. Generating a random number between 1 to n

This code is useful in generating random numbers for games etc.

//random number from 1 to N
var random = Math.floor(Math.random() * N + 1);

//random number from 1 to 10
var random = Math.floor(Math.random() * 10 + 1);

//random number from 1 to 100
var random = Math.floor(Math.random() * 100 + 1);


7. Capturing a browser close button event or to exit the page in JavaScript

The browser’s close event is usually captured in order to tell the user about unsaved data that they may need to save.





8. Capture a back button

The usage is quite similar to above, except you capture the back button event rather than close.

window.onbeforeunload = function() {
return "You work will be lost.";
};


9. Check if the form is dirty

For this, forsIsDirt is used. The function returns a Boolean value (true of false) based on whether the user has made any virtual changes to the HTML form of a website,

/**
- Determines if a form is dirty by comparing the current value of each element
- with its default value.
=*
* @param {Form} form the form to be checked.
* @return {Boolean} true if the form is dirty, false
* otherwise.
*/
function formIsDirty(form) {
for (var i = 0; i < form.elements.length; i++) {
var element = form.elements[i];
var type = element.type;
if (type == "checkbox" || type == "radio") {
if (element.checked != element.defaultChecked) {
return true;
}
}
else if (type == "hidden" || type == "password" ||
type == "text" || type == "textarea") {
if (element.value != element.defaultValue) {
return true;
}
}
else if (type == "select-one" || type == "select-multiple") {
for (var j = 0; j < element.options.length; j++) {
if (element.options[j].selected !=
element.options[j].defaultSelected) {
return true;
}
}
}
}
return false;
}
window.onbeforeunload = function(e) {
e = e || window.event;
if (formIsDirty(document.forms["someForm"])) {
// For IE and Firefox
if (e) {
e.returnValue = "You have unsaved changes.";
}
// For Safari
return "You have unsaved changes.";
}
};


10. Disabling Back button

For this, you have to put the code in the page that you don’t want the user to go back to.



onpageshow="if (event.persisted) noBack();" onunload="">


11. To delete multiple values from the listbox

You have to create a function to remove multiple values.

function selectBoxRemove(sourceID) {

//get the listbox object from id.
var src = document.getElementById(sourceID);

//iterate through each option of the listbox
for(var count= src.options.length-1; count >= 0; count--) {

//if the option is selected, delete the option
if(src.options[count].selected == true) {

try {
src.remove(count, null);

} catch(error) {

src.remove(count);
}
}
}
}


12. Select or Deselect All from Listbox

The code fragment below allows you to do this.

function listboxSelectDeselect(listID, isSelect) {
var listbox = document.getElementById(listID);
for(var count=0; count < listbox.options.length; count++) {
listbox.options[count].selected = isSelect;
}
}


13. To move selected items up or down

To do this, make a function like below.

function listbox_move(listID, direction) {

var listbox = document.getElementById(listID);
var selIndex = listbox.selectedIndex;

if(-1 == selIndex) {
alert("Please select an option to move.");
return;
}

var increment = -1;
if(direction == 'up')
increment = -1;
else
increment = 1;

if((selIndex + increment) < 0 ||
(selIndex + increment) > (listbox.options.length-1)) {
return;
}

var selValue = listbox.options[selIndex].value;
var selText = listbox.options[selIndex].text;
listbox.options[selIndex].value = listbox.options[selIndex + increment].value
listbox.options[selIndex].text = listbox.options[selIndex + increment].text

listbox.options[selIndex + increment].value = selValue;
listbox.options[selIndex + increment].text = selText;

listbox.selectedIndex = selIndex + increment;
}
//..
//..

listbox_move('countryList', 'up'); //move up the selected option
listbox_move('countryList', 'down'); //move down the selected option


14. Move options to the left or right using Listbox

function listbox_moveacross(sourceID, destID) {
var src = document.getElementById(sourceID);
var dest = document.getElementById(destID);

for(var count=0; count < src.options.length; count++) {

if(src.options[count].selected == true) {
var option = src.options[count];

var newOption = document.createElement("option");
newOption.value = option.value;
newOption.text = option.text;
newOption.selected = true;
try {
dest.add(newOption, null); //Standard
src.remove(count, null);
}catch(error) {
dest.add(newOption); // IE only
src.remove(count);
}
count--;
}
}
}
//..
//..

listbox_moveacross('countryList', 'selectedCountryList');


15. To initialize an Array using the series of numbers

The code fragment given below will help with this.

var numbers = [];
for(var i=1; numbers.push(i++)<100;);
//numbers = [0,1,2,3 ... 100]


16. Rounding off numbers to ‘x’ decimal places

var num = 2.443242342;
alert(num.toFixed(2)); // 2.44

The toFixed(x) method used here provides x length after the decimal point. On the other hand, toPrecision(x) provides x total length.

num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2


17. To check if a string contains a substring

Use the code below.

if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(obj, start) {
for (var i = (start || 0), j = this.length; i < j; i++) {
if (this[i] === obj) { return i; }
}
return -1;
}
}

if (!String.prototype.contains) {
String.prototype.contains = function (arg) {
return !!~this.indexOf(arg);
};
}


18. Removing duplicates

Use the removeDuplicates method for this.

function removeDuplicates(arr) {
var temp = {};
for (var i = 0; i < arr.length; i++)
temp[arr[i]] = true;

var r = [];
for (var k in temp)
r.push(k);
return r;
}

//Usage
var fruits = ['apple', 'orange', 'peach', 'apple', 'strawberry', 'orange'];
var uniquefruits = removeDuplicates(fruits);
//print uniquefruits ['apple', 'orange', 'peach', 'strawberry'];


19. Trimming a string

This can be used to remove spaces from both sides of a string.

if (!String.prototype.trim) {
String.prototype.trim=function() {
return this.replace(/^\s+|\s+$/g, '');
};
}

//usage
var str = " some string ";
str.trim();
//print str = "some string"


20. Redirect a webpage

window.location.href = "http://viralpatel.net";

21. Encoding a URL

The envodeURIcomponent function should be used for this.

var myOtherUrl =
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);


Sourceviralpatel.net