Friday, 22 November 2013

Javascript Fundamental

1. Difference between ondocumentready and window.onload  

window.onload :this fires after all images , css and reference load .It is fired later
ondocumentready :this fires after DOM load , fired first

 Then ondocumentready is far better option to manipulate pages

2. Difference between Jscript and Javascript

Both are similar 
Jscript: Developed by Microsoft , for internet explorer
Javascript : Developed by  Netscape ,for Mozilla

3) How to detect a variable is object ?
   var obj
    typeof obl === "object"

4) undefined and null
Undefined : A variable is declared but not assign a value
null: A assigned value,It can be assigned to a variable as a representation of no value.


5) “==” and “===”
 “==” :check the equality
 “===” :check the equality as well as type

6) This keyword
This keyword refer to current object

Example 1.
In a page this is written 
this.student_name : will refer the variable (student_name)  of   current page 


Example2.
In a function this is written 
this.student_name : will refer the variable (student_name)  of   current function

 7) IsNan() function
IsNan stands for not a number.It check a variable /value is number or not
alert(isNaN(“red”)) will return true
alert(isNaN(5)) will return false

8) decodeURI(), encodeURI()
A url can not be send in a  in a URL, but must be converted to their hex encoding. These functions are used to convert an entire URI  to and from a format that can be sent via a URI.
<script type="text/javascript">
var myurl = "http://www.google.com/search?key=A6p-jeArypeJW5-GHWai56-ASIowYjw5"
document.write(myurl );
document.write("encoded: "+encodeURI(myurl ));
</script>

9)What is eval()
eval is a method ,it has power to execute small amount/space of code during execution
<script type="text/javascript">
var myvar = "this my javascript";
document.write(eval(myvar ));
</script>
Result
this my javascript

10)Javascript object properties
var obj  // object declared

Set the value
obj.name="Maria Gomes"
obj.age="17"
obj.sex="female"

Get the value
document.write(obj.name);
document.write(obj.age);
document.write(obj.sex);
 


11) Event Handlers &  addEventListener

We can add event handler in javascript also
Example 1.
function defined separately
document.getElementById("myControl").onclick = myfunction;

function myfunction()
{
alert('function is working') ;
//define function here
}


Example 2.
function defined included
document.getElementById("myControl").onclick = function ()
{
alert('function is working') ;
//define function here
 }

Examplie 3.
addEventListener , but does not work in IE yet
if(document.getElementById("myControl").addEventListener)
   {
    document.getElementById("myControl").addEventListener("click", myfunction, false);
 }
function myfunction()
{
alert('function is working') ;
//define function here
}

12)How to convert numbers to strings and  strings to numbers 

//number to string
var myvalue = "14";
var mystring = myvalue .toString()

// string to number
var myvalue = "14";
var mynumber=parseInt(myvalue )

13) What is shift and unshift

var numbers = ["A", "B", "C", "D"];
numbers.unshift("A");
document.write(" "+numbers.shift());
document.write(" "+numbers.shift());
document.write(" "+numbers.shift());
Output
B,C,D

14)cookies stored in the location
Mozila
c:\Program Files\Netscape\Users\username\cookies.txt
IE
 c:\Windows\Cookies\username@Websitename.txt --file

15) exception handling in javascript
Like java,C,C# javascript also uses exception handling by try,catch, finally

try
{
//Code to execute
}
catch(e)
{
//exeption part
}
finally
{
//finalized
 }


16) window.navigator
this code is used to get information of user browser
navigator.appName-->Browser Name
navigator.appVersion-->Browser Version
navigator.systemLanguage-->User -Agent Language
navigator.cookieEnabled--->Browser cookie enabled ot not
 

 17)How to stop Execution of setTimeout()
 window.clearTimeout(interval


18) for each loop in javascript

var obj = {prop1: 12, prop2: 24, prop3: 36}; 
for each (var item in obj)  
{
  document.write (item);
}

19) Recursion  in JavaScript

calling a function repetedly

var reverseArray = function(x,indx,str) 
{
    if (indx === 0) { // Termination condition
        return str; // return default
    } else {
        return reverseArray(x, --indx, str + " " + x[indx]); 
    }
}


20) Javascript key detection
It is a easy way to detect which key was press.As like normal programming languages like C#, vb.net , they
same way developer can detect key .There are two different type of way to detect key press and other event like mouse click, mouse over.
keyCode and charCode are the keyword to detect event .Some browser support keyCode , some charCode.

we can detect this by

var myCode;

if ( e.keyCode )
{
    myCode= e.keyCode;
}
else
{
    myCode= e.charCode;
}

in short form
var myCode= e.keyCode ? e.keyCode : e.charCode
e stands for event.

Here is an example how to detect the event

<script type="text/javascript">
function detectcode(e){
var myCode=e.keyCode? e.keyCode : e.charCode
alert(myCode)
}
</script>
<form>
<input type="text"  onkeyup="detectcode(event);" />
</form>
 
This example will return alert box the code of when a key press on the textbox

Now , there are some other ways to detect keys ie, Alt, Shift, Ctrl
 
here is an example
function detectcode(e)
{
var eventtobj=window.event? event : e
if (eventtobj.altKey || eventtobj.ctrlKey || eventtobj.shiftKey)
alert("you pressed one of the 'Alt', 'Ctrl', or 'Shift' keys")
}
document.onkeypress=detectcode
</script> 
 
 charCode works NS/Firefox only
 
 
 
Key Code
backspace 8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222



21) DOM Element properties
 attributes[] :Returns the array of attributes

         var obj=document.getElementById("myimage").attributes;
         var  objval= obj[0].value;
         var  objname= obj[0].name;
         var  objsrc= obj[0].src; 
        
childNodes[] :Returns the array of childndes

     var obj=document.getElementById("someList").attributes;
     for (i=0; i<obj.childNodes.length; i++)
   {
       if (obj.childNodes[i].nodeName=="LI")
   }

className :Returns css class name of the object
 var objclass=document.getElementById("myobject").className;

clientWidth  &  clientHeight :Returns viewable width ,height of the content on the page
 does not consider scrollbars,borders, margins
 var vwidth=document.body.clientWidth 
 var vheight=document.body.clientHeight

dir :Returns text direction left to write and right to left.Terms as ltr,rtl
 document.getElementById("mytext").dir="rtl"



firstChild :Returns the first child of the node
    var obj=document.getElementById("mytext").firstChild;
    obj contain first child of  mytext

innerHTML :Return the html string contain by the object;
var myhtml="<p>I am learing javascript<p><b>How am i learing ?"
document.getElementById("myDiv").innerHTML=myhtml ;

offsetLeft & offsetTop & offsetParent & offsetWidth & offsetHeight
 offset position of the current element relative to its offset container.Left,top,Parent object , width, height of
the object related to the parent who contains it

<body>
<form id="myform">
<div id="offset_test">This is my test control</div>
</form>
<body>

<script type="text/javascript">
        var objleft  =document.getElementById("offset_test").offsetLeft ;
        var objtop=document.getElementById("offset_test").offsetTop ;
        var objparent=document.getElementById("offset_test").offsetParent ;
        var objwidth=document.getElementById("offset_test").offsetWidth ;
        var objheight=document.getElementById("offset_test").offsetHeight;
</script>


scrollLeft &  scrollTop & scrollHeight & scrollHeight


22) SessionStorage & LocalStorage 
Both  allows to save key/value pairs in a web browser. The value must be a string, and save js objects 
var user = {'abc':'cde'};
sessionStorage.setItem('user', user);
var obj = sessionStorage.user; 

23) How to set and get values of cookies ?
cookies are data , which stored in your local computer , as a text file.cookies are set on local machine , i.e client machine only

 document.cookie="YourName=Joe Smith";

23)How to add html object in javascript with value

There is the code

function add_Form_Field(form_object, field_type, field_name, field_value) {
            if (form_object) {
                var input = document.createElement('INPUT');
                if (document.all) {
                    input.type = field_type;
                    input.name = field_name;
                    input.value = field_value;
                } else if (document.getElementById) {
                    input.setAttribute('type', field_type);
                    input.setAttribute('name', field_name);
                    input.setAttribute('value', field_value);
                }
                form_object.appendChild(input);
            }
        }
form_object=ID of form
field_type=textbox,listbox,option ect
field_value=Value of the field

24)Form action Property


Set the action property URL of a form

document.getElementById("FormToken").action="../All_Pages/myForm.aspx";

The action property sets or returns the value of the action attribute in a form.
The action attribute specifies where to send the form data when a form is submitted.


var my_action = document.getElementById("myForm").action;

Return the URL for where to send the form data when a form is submitted

25) Form target Property


_blank
Opens in a new window
_self
Opens in the same frame as it was clicked (default)
_parent
Opens in the parent frameset
_top
Opens in the full body of the window
framename
Opens in a named frame









formObject.target="_blank|_self|_parent|_top|framename"

Change where to display the response that is received after submitting a form (open the response in a new window instead of the same frame as it was clicked):


26)  document.getElementById and document.all


           if (document.getElementById)
              div = document.getElementById('popupWindow' + n);
          else if (document.all)
              div = document.all['popupWindow' + n];

document.getElementById, one of the primary methods of the DOM that any modern browser supports
 document.all is a proprietary property of IE introduced in IE4

27) Switch statement of javascript

function MyObjectType(obj) 
{
    switch (obj.constructor) {
        case Date:
            document.write("Object is a Date.");
            break;
        case Number:
            document.write("Object is a Number.");
            break;
        case String:
            document.write("Object is a String.");
            break;
        default:
            document.write("Object is unknown.");
    }
}
 
28) IIF 

var a = 2;
var b = 0;
var c = (a > b || b == 0)? "do something" : "do something else";

Wednesday, 13 November 2013

Inheritance & polymorphism





l Inheritance
  1. Inheritance allows a software developer to derive a new  class from an existing one.
  2. The existing class is called the parent, super, or base class.
  3. The derived class is called a child or subclass.
  4. The child inherits characteristics of the parent.
  5. Methods and data defined for the parent class.
  6. The child has special rights to the parents methods and data.
  7. Public access like any one else
  8. Protected access available only to child classes (and their descendants).
  9. The child has its own unique behaviors and data.
     
                 Base class &  Derived class


        class BaseClass
        {
        class DerivedClass : BaseClass
        {
        }
        A child class inherits the methods and data defined for the parent class; however, whether a data or method member of a parent class is accessible in the child class depends on the visibility modifier of a member.

        Private
        Variables and methods declared with private visibility are not accessible in the child class
        However, a private data member defined in the parent class is still part of the state of a derived class.
        Public

        Variables and methods declared with public visibility are accessible; but public variables violate our goal of encapsulation

        Protected
        There is a third visibility modifier that helps in inheritance situations: protected

        Variables and methods declared with protected visibility in a parent class are only accessible by a child class or any class derived from that class

        Some languages, e.g., C++, allow Multiple inheritance, which allows a class to be derived from two or more classes, inheriting the members of all parents.
        C# and Java support single inheritance, meaning that a derived class can have only one parent class


        Override
        A child class can override the definition of an inherited method in favor of its own
        That is, a child can redefine a method that it inherits from its parent
        The new method must have the same signature as the parent's method, but can have a different implementation.
        The type of the object executing the method determines which version of the method is invoked


        Inheritance is transitive
        An inherited member is continually passed down the line.Good class design puts all common features as high in the hierarchy as is reasonable. Avoids redundant code.

        References and Inheritance 
        An object reference can refer to an object of its class, or to an object of any class derived from it by inheritance.

        For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference can be used to point to a Christmas object


        Holiday day;
        day=new Holiday();
        day=new Christmas();

        Dynamic Binding 
        A polymorphic reference is one which can refer to different types of objects at different times. It morphs!

        The type of the actual instance, not the declared type, determines which method is invoked.


        Polymorphic references are therefore resolved at run-time, not during compilation.
        This is called dynamic binding.



        Suppose the Holiday class has a method called Celebrate, and the Christmas class redefines it (overrides it).Now consider the following invocation:

        day.Celebrate();
        If day refers to a Holiday object, it invokes the Holiday version of Celebrate;  if it refers to a Christmas object, it invokes the Christmas version



        virtual, override and new
        C# requires that all class definitions communicate clearly their intentions.

        The keywords virtual, override and new provide this communication.


        If a base class method is going to be overridden it should be declared virtual.


        A derived class would then indicate that it indeed does override the method with the override keyword


        If a derived class wishes to hide a method in the parent class, it will use the new keyword.
        This should be avoided



        Widening and Narrowing

        Assigning an object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment

        Holiday day = new Christmas();


        Assigning an ancestor object to a reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast:


        Christmas christ = new Christmas();
        Holiday day = christ;
        Christmas christ2 = (Christmas)day;



        Question and Answer
        1.How to prevent  a class being inherited ?
         
        Sealed

        sealed class A
        {
        public int A,
        public int B
        } No class can be inherited from class A

        2.When you are using shadowing if you want to access the base class method with derived class how can you access it?

        public class Baseclass
        {
             public void Method1()
            {
            string a="Base Method" ;
             }


        public class Deriveclass:BaseClass
        {
           public new void Methaod1()
            {
             string a="Derive Methaod";
            }


        public class testApp
        {
            public static void main()
             {
              DeriveClass deriveObj=new DerideCalss();
                  BaseClass obj2=(BaseClass)deriveclass;
                  obj2.Method1() 
            }
        }

        3)What is the different between Class & object

        Class:User defined datatype, method,property,abstarct charateistic
        Object :instance of a class,which is created at rutime 

        4)Overloading and overrriding

        overloading:more than one method with same name 
        overriding:Change behaviour of class in derive class using dynamic polymorphism


        5)What is the difference between shadowing and overriding?

        6) Common interface in C#

                 System.Data.IDataAdopter
                 System.Data.IDataParameter
                 System.Data.IDataReader
                 System.Data.IDataConnection
                 System.Data.IHttpModule


         Common Sealed class in C#

                 System.Data.SqlClient.Sqlcommand
                 System.Data.SqlClient.Sqlconnetion
                 System.Data.SqlClient.SqlDataAdopter         System.Data.SqlClient.SqlconnetionStringBuilder      


        Common abstract class in C#

                System.Data.Common.DbCommand
                System.Data.Common.DbConnection
                System.Data.Common.DbDataReader
                System.Data.Xml.Node 

        System.Data.Xml.Node 

        Common static classes
           
               System.Math
               System.Convert
               System.Net


         
        7.How many types of inheritances are there in C#?
        Ans. There are two types of inheritance in C#.
        a) Interface inheritance : When a class or interface is inheriting from another interface, is called interface inheritance.
        b)Implementation inheritance : When a class is inheriting from another class, is called implementation inheritance.

        8.What is Interface?
        Ans. An interface is used to declare methods, properties, events etc. Interface dose not contain any definitions of these contructs. The class that inherit from interface has to define/implement all the members of that interface.
        A class can inherit from more than one interfaces.

        9.What is Abstract class?
        Ans. An abstract class is a class that cant be instantiated. A class can be abstract if any one of the following occures:
        a) Class is declared as Abstract
        b) class is inherited from another abstract class but not implemented all abstract methods of the base class.
        c) class that has some abstract methods 

                public abstract class SampleClassAbstract
                {
                    public static void DisplayMessage()
                    {
                        Console.WriteLine("Static Method within Abstract Class Executed");
                        
                    }           
        
                }
         

        10)Static Classes and Static Class Members
        A static class cannot be instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself

        public static class TemperatureConverter
            {
                public static double CelsiusToFahrenheit(string temperatureCelsius)
                {
                    // Convert argument to double for calculations. 
                    double celsius = Double.Parse(temperatureCelsius);
        
                    // Convert Celsius to Fahrenheit. 
                    double fahrenheit = (celsius * 9 / 5) + 32;
        
                    return fahrenheit;
                }
        
                public static double FahrenheitToCelsius(string temperatureFahrenheit)
                {
                    // Convert argument to double for calculations. 
                    double fahrenheit = Double.Parse(temperatureFahrenheit);
        
                    // Convert Fahrenheit to Celsius. 
                    double celsius = (fahrenheit - 32) * 5 / 9;
        
                    return celsius;
                }
            }

        public static class TemperatureConverter
            {
                public static double CelsiusToFahrenheit(string temperatureCelsius)
                {
                    // Convert argument to double for calculations. 
                    double celsius = Double.Parse(temperatureCelsius);
        
                    // Convert Celsius to Fahrenheit. 
                    double fahrenheit = (celsius * 9 / 5) + 32;
        
                    return fahrenheit;
                }
        
                public static double FahrenheitToCelsius(string temperatureFahrenheit)
                {
                    // Convert argument to double for calculations. 
                    double fahrenheit = Double.Parse(temperatureFahrenheit);
        
                    // Convert Fahrenheit to Celsius. 
                    double celsius = (fahrenheit - 32) * 5 / 9;
        
                    return celsius;
                }
            }
        
            class TestTemperatureConverter
            {
                static void Main()
                {
                    Console.WriteLine("Please select the convertor direction");
                    Console.WriteLine("1. From Celsius to Fahrenheit.");
                    Console.WriteLine("2. From Fahrenheit to Celsius.");
                    Console.Write(":");
        
                    string selection = Console.ReadLine();
                    double F, C = 0;
        
                    switch (selection)
                    {
                        case "1":
                            Console.Write("Please enter the Celsius temperature: ");
                            F = TemperatureConverter.CelsiusToFahrenheit(Console.ReadLine());
                            Console.WriteLine("Temperature in Fahrenheit: {0:F2}", F);
                            break;
        
                        case "2":
                            Console.Write("Please enter the Fahrenheit temperature: ");
                            C = TemperatureConverter.FahrenheitToCelsius(Console.ReadLine());
                            Console.WriteLine("Temperature in Celsius: {0:F2}", C);
                            break;
        
                        default:
                            Console.WriteLine("Please select a convertor.");
                            break;
                    }
        
                    // Keep the console window open in debug mode.
                    Console.WriteLine("Press any key to exit.");
                    Console.ReadKey();
                }
            }
            /* Example Output:
                Please select the convertor direction
                1. From Celsius to Fahrenheit.
                2. From Fahrenheit to Celsius.
                :2
                Please enter the Fahrenheit temperature: 20
                Temperature in Celsius: -6.67
                Press any key to exit.
             */
        The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name

        public class Automobile
        {
            public static int NumberOfWheels = 4;
            public static int SizeOfGasTank
            {
                get
                {
                    return 15;
                }
            }
            public static void Drive() { }
            public static event EventType RunOutOfGas;
        
            // Other non-static fields and properties...
        }
         
        11)Can you declare a private class in a namespace ?
         The classes in a namespace are internal, by default. However, you can 
         explicitly declare them as public only and not as private, protected, or protected 
         internal. The nested classes can be declared as private, protected, or  
         protected internal.

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...