Wednesday, July 4, 2012

Establish Remote Connection to Microsoft SQL Server Database


Establish remote connection in database using following process.
  • Use SQL Server Surface Area Configuration Tool for enabling the remote connection in database. 
  • Click on Surface Area Configuration for Services and Connections.
  • Click on SQLEXPRESS/Database Engine/RemoteConnections
  • Select the radio button: Local and Remote Connections and select ‘Using TCP/IP only’ under Local and Remote Connections.
  • Click on OK button / Apply button.


Linked Server in Microsoft SQL Server


Microsoft SQL Server supports the connection to different OLE DB on an ad hoc basis. This persistent connection is referred as Linked Server.
To use Linked Server for any OLE DB, follow these steps.

  • Open SQL Server Management Studio in SQL Server 2005
  • Expand Server Objects in Object Explorer.
  • Right-click on Linked Servers. Click on New Linked Server.
  • Select General page in the left pane and  
  • Type any name for the linked server in the first text box
  • Select the Other Data Source option.
  • Click on Microsoft Jet 4.0 OLE DB Provider from the Provider list. 
  • Type the Excel as the name of the OLE DB data source.
  • Type the full path and file name of the Excel file in Data Source box.
  • Type the Excel version no. (7.0, 8.0 etc) in the Provider String. 
  • Use Excel 8.0 for Excel 2000, Excel 2002 or Excel 97.
  • To create a linked server click on OK.


Trace frag in Sqlserver


Temporary setting of specific server characteristics is done by trace tags. 

DBCC TRACEON is the command to set the trace flags. Once activated, trace flag will be in effect until the server is restarted. Trace frags are frequently used for diagnosing performance issues.

For example, the trace flag 3205 is used for disabling hard compression for tape drives, when an instance of SQL Server starts.

Buffer Cache and Log Cache in Sql Server


Buffer cache is a memory pool in which data pages are read. It performance of the buffer cache is indicated as follows: 95% indicates that pages that were found in the memory are 95% of time. Another 5% is needed for physical disk access. If the value falls below 90%, it is the indication of more physical memory requirement on the server.

Log cache is a memory pool used to read and write the log pages. A set of cache pages are available in each log cache. The synchronization is reduced between log and data buffers by managing log caches separately from the buffer cache.

Tuesday, July 3, 2012

Create CLR Trigger


Steps for creating CLR Trigger


Follow these steps to create a CLR trigger of DML (after) type to perform an insert action:
Create a .NET class of triggering action
Make an assembly (.DLL) from that Class
Enable CLR environment in that database.
Register the assembly in SQL Server
Create CLR Trigger using that assembly

CLR Triggers

CLR Triggers


A CLR trigger could be a Date Definition or Date Manipulation Language trigger or could be an AFTER or INSTEAD OF trigger. Methods written in managed codes that are members of an assembly need to be executed provided the assembly is deployed in SQL 2005 using the CREATE assembly statement. The Microsoft.SqlServer.Server Namespace contains the required classes and enumerations for this objective.

Custom Exceptions


What are Custom Exceptions?


Custom Exceptions are user defined exceptions. There are exceptions other than the predefined ones which need to be taken care of. For example, The rules for the minimum balance in a Salary A/C would be different from that in a Savings A/C due to which these things need to be taken care of during the implementation.


Implement Delegates in C#.NET


Explain how to implement Delegates in C#.NET?


Here is an implementation of a very simple delegate that accepts no parameters.


public delegate void MyDelegate();// Declaration
class MyClass
{
     public static void MyFunc()
     {
         Console.WriteLine("MyFunc Called from a Delegate");
     }
     public static void Main()
     {
            MyDelegate myDel = new MyDelegate(MyFunc);
            myDel();
      }
}


What is assembly in .NET


Define assembly.


An assembly is the primary unit of a .NET application. It includes an assembly manifest that describes the assembly.


Monday, July 2, 2012

How Obfuscator works


Explain how Obfuscator works?


Obfuscators protect the source code from being hacked. Encryption and Decryption are processes from where you can get the data back. However these differ from what obfuscation is. In obfuscation, a program become out of the reach of hackers although it functions the same way it is supposed to. Optimizations too get applied to the process of obfuscation in order to make the program fast.



Obfuscator simply renames all types and namespace etc to meaningless code making it non human readable. This diminishes the possibility of reverse engineering. For example


private void AddEmp(Employee employee) 
{
   {
      this.EmpList.Add(employee);
   }
}


It gets converted to following code.


private void a(a b) 
{
    {
      a.a.Add(b);
    }
}


Abstract classes in C#.NET


Define abstract class in C#.NET.


Abstract classes in C#.NET has following features :
Abstract class cannot be instantiated.
Same concept in C++ known as pure virtual method. 
A class that must be inherited and have the methods over-ridden. 
A class without any implementation.

Constructor and Destructor in .NET


What is a Constructor? 


It is the first method that are called on instantiation of a type. It provides way to set default values for data before the object is available for use. Performs other necessary functions before the object is available for use.


What is a Destructor?


It is called just before an object is destroyed. It can be used to run clean-up code. You can't control when a destructor is called since object clean up by common language runtime.

Implement a Web Service in .NET

Explain with code sample how to Implement a Web Service in .NET?

Following is code in VBScript and C# both respectively.

In VBScript :


<%@ WebService Language="VBScript" Class="KmToMConvert" %>

Imports System
Imports System.Web.Services

Public Class KmToMConvert :Inherits WebService
   <WebMethod()> Public Function KilometerToMeter(ByVal Kilometer As String) As String 
         return (Kilometer * 1000)
         end function
end class

In C# :

[WebService(Namespace = http://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
     [WebMethod]
     public string HelloWorld()
     {
            return "Hello World";
     }
}

Private virtual methods in C#.NET


Can private virtual methods be overridden in C#.NET? 


No, moreover, you cannot access private methods in inherited classes, They have to be protected in the base class to allow any sort of access. 

Multiple inheritance in C#.Net


Does C#.Net support multiple inheritance?


No, C#.Net does not support multiple inheritance,  but we can use interfaces to achieve functionality of multiple inheritance.

What is serialization


Explain serialization ?


Serialization is a process of converting an object into a stream of bytes. .Net has 2 serializers namely XMLSerializer and SOAP/BINARY Serializer. Serialization is maily used in the concept of .Net Remoting.

How to force garbage collector to run


Is this possible to force garbage collector to run? 


Yes, we can force garbage collector to run using following code.
System.GC.Collect().

Role of .Net data provider


What is the role of data provider?


The .NET data provider layer resides between the application and the database. Its task is to take care of all their interactions. The .NET Data provider can be demonstrated to be:
SQL Server data provider 
OLEDB data provider 
ODBC Data Provider


ADO.NET supports the following OLE DB Providers:
- SQLOLEDB - Microsoft OLE DB Provider for SQL Server.
- MSDAORA - Microsoft OLE DB Provider for Oracle.
- Microsoft.Jet.OLEDB.4.0 - OLE DB Provider for Microsoft Jet.

Compilation and Execution of .Net application


Describe how a .Net application is compiled and executed?


From the source code, the compiler generates Microsoft Intermediate Language (MSIL) which is further used for the creation of an EXE or DLL. The CLR processes these at runtime. Thus, compiling is the process of generating this MSIL. The way you do it in .Net is as follows:
Right-click and select Build / Ctrl-Shift-B / Build menu, Build command
F5 - compile and run the application. 
Ctrl+F5 - compile and run the application without debugging.


Compilation can be done with Debug or Release configuration. The difference between these two is that in the debug configuration, only an assembly is generated without optimization. However, in release complete optimization is performed without debug symbols.

Event and Delegate


What is an Event?


When an action is performed, this action is noticed by the computer application based on which the output is displayed. These actions are called events. Examples of events are pressing of the keys on the keyboard, clicking of the mouse. Likewise, there are a number of events which capture your actions.


Delegate :


Delegates are kind of similar to the function pointers. But they are secure and type-safe. A delegate instance encapsulates a static or an instance method. Declaring a delegate defines a reference type which can be used to encapsulate a method having a specific signature.


Language Integrated Query ( LINQ )


What is Language Integrated Query (LINQ)? 


LINQ is a set of extensions to .NET Framework that encapsulate language integrated query, set and other transformation operations. It extends VB, C# with their language syntax for queries. It also provides class libraries which allow a developer to take advantages of these features.

.NET Mobile overview

.NET Mobile overview


.NET Mobile is a platform for developing applications for mobile phones. It’s an extension to .NET Framework and is called Microsoft Mobile Internet Toolkit. It is a set of server side forms controls. These controls produce different output formats i.e. WML, HTML or even compact HTML. This allows developers to create an application using a single paradigm instead of developing an application multiple times using different paradigms based on what different mobiles support. The advantage is standardization, less redundancy, and Microsoft support.

Handle Exceptions in .NET 2.0


Explain how to Handle Exceptions in .NET 2.0.


There are different methods for handling the exceptions. For example


Method 1 :


try
{
     // code here
}
catch(Exceptiontype *etype_object)
{
     // code here.
}


Method 2 :
try
{
       // code
}
catch(Exceptiontype *etype_object)
{
        throw new Custom_Exception();
}

Difference between object pooling and connection pooling


How does object pooling and connection pooling differ?


In Object pooling, you can control the number of connections. In connection pooling, you can control the maximum number reached.


When using connection pooling, if there is nothing in the pool, a connection is created since the creation is on the same thread.


In object pooling, the pool decides the creation of an object depending on whether the maximum is reached which in case if it is, the next available object is returned. However, this could increase the time complexity if the object is heavy.

Sunday, July 1, 2012

Object Pooling in .NET


What is an object pool in .NET?


An object pool is a container of objects that holds a list of other objects that are ready to be used. It keeps track of following:
Objects that are currently in use
The number of objects the pool holds
Whether this number should be increased
The request for the creation of an object is served by allocating an object from the pool.


This reduces the overhead of creating and re-creating objects each time an object creation is required.

Why is an Object Pool required

Why is an Object Pool required?


To enhance performance and reduce the load of creating new objects, instead re using existing objects stored in memory pool. 
Object Pool is a container of objects that are for use and have already been created. Whenever an object creation request occurs, the pool manager serves the request by allocating an object from the pool. This minimizes the memory consumption and system's resources by recycling and re-using objects. 
When the task of an object is done, it is sent to the pool rather than being destroyed. This reduces the work for garbage collector and fewer memory allocations occur.

GetCommandLineArgs() method in C# .NET


What is the use of GetCommandLineArgs() method in C#.NET?


With GetCommandLineArgs() method, the command line arguments can be accessed. 
The value returned is an array of strings.

Compare C# .NET Generics and C++ Templates


How does C#.NET Generics and C++ Templates compare?


C# generics and templates in C++ are more or less similar syntactically.


C# Generic types are strong typed. C++ Templates are loosely typed.
C# Generic types are instantiated at the runtime. C++ templates are instantiated at the compile time.
C# Generic types do not permit the type parameters to have default values. C++ templates do.

Achieve polymorphism in C# .NET


How to achieve polymorphism in C#.NET?


Polymorphism is when a class can be used as more than one type through inheritance. It can be used as its own type, any base types, or any interface type if it implements interfaces.It can be achieved in the following ways.


Derived class inherits from a base class and it gains all the methods, fields, properties and events of the base class.


To completely take over a class member from a base class, the base class has to declare that member as virtual.

Use of System.Environment class in C# .NET


What is the use of System.Environment class in C#.NET?


The System.Environment class can be used to retrieve information like below :

  • Command-line arguments.
  • The exit code.
  • Environment variable settings.
  • Contents of the call stack.
  • Time since last system boot.
  • The version of the common language runtime.


Prevent class from being inherited in C#.NET


How to prevent a class from being inherited in C#.NET?


The sealed modifier is used to prevent derivation from a class. An error occurs if a sealed class is specified as the base class of another class. A sealed class cannot also be an abstract class.


Add ReadOnly property in C#.NET?


How to add a ReadOnly property in C#.NET?


Properties can be made read-only by having only a get accessor in the implementation. For example


public class X
{
          public X(int id)
          {
               x_id = id;
          }
          public int ID
          {
              get
              {
                   return x_id;
              }
          }
}

Implementation inheritance and interface inheritance

What are implementation inheritance and interface inheritance?


Implementation inheritance is achieved when a class is derived from another class in such a way that it inherits all its members.


Interface inheritance is when a class inherits only the signatures of the functions from another class.

C# interview questions with answers, Part 3


C# developer interview questions and answers.


What is the difference between Finalize() and Dispose()?


Dispose() is called by as an indication for an object to release any unmanaged resources it has held. 
Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object. 
Dispose() operates determinalistically due to which it is generally preferred.



What is the difference between Debug.Write and Trace.Write? When should each be used?


Debug.Write: Debug Mode, Release Mode, It used while debuging a project.
Trace.write: Release Mode, It used in Released verion of Applications.



Explain the use of virtual, sealed, override, and abstract.


The virtual keyword enables a class to be overridden. If it has to be prevented from being overridden, then the sealed keyword needs to be used. If the keyword virtual is not used, members of the class can even then be overridden. However, its usage is advised for making the code meaningful.


The override keyword is used to override the virtual method in the base class. Abstract keyword is used to modify a class, method or property declaration. You cannot instantiate an abstract class or make calls to an abstract method directly.


An abstract virtual method means that the definition of the method needs to be given in the derived class.



What benefit do you get from using a Primary Interop Assembly (PIA)?


A primary interop assembly contains type definitions (as metadata) of types implemented with COM. Only a single PIA can exist, which needs to be signed with a strong name by the publisher of the COM type library.
One PIA can wrap multiple versions of the same type library.


A COM type library imported as an assembly can be a PIA only if it has been signed and published by the same publisher.


Therefore, only the publisher of a type library can produce a true PIA, that can be considered as the unit of an official type definition for interoperating with the underlying COM types.



Explain the use of static members with example using C#.NET.


Static members are not associated with a particular instance of any class. 
They need to be qualified with the class name to be called. 
Since they are not associated with object instances, they do not have access to non-static members.
i.e.: "this" cannot be used, which represents the current object instance.





C# interview questions with answers, Part 2


C# developer interview questions with answers.


What is a delegate?

  1. A strongly typed function pointer.
  2. A light weight thread or process that can call a single method.
  3. A reference to an object in a different process.
  4. An inter-process message channel.
Answer :
1. A strongly typed function pointer.



How does assembly versioning in .NET prevent DLL Hell?

  1. The runtime checks to see that only one version of an assembly is on the machine at any one time.
  2. .NET allows assemblies to specify the name AND the version of any assemblies they need to run.
  3. The compiler offers compile time checking for backward compatibility.
  4. It doesn't.

Answer :
2. .NET allows assemblies to specify the name AND the version of any assemblies they need to run.



Which .Gang of Four. design pattern is shown below?
public class A {
    private A instance;
    private A() {
    }
    public
static A Instance {
        get
        {
            if ( A == null )
                A = new A();
            return instance;
        }
    }
}

  1. Factory
  2. Abstract Factory
  3. Singleton
  4. Builder


Answer :
3. Singleton



In the NUnit test framework, which attribute must adorn a test class in order for it to be picked up by the NUnit GUI?

  1. TestAttribute
  2. TestClassAttribute
  3. TestFixtureAttribute
  4. NUnitTestClassAttribute


Answer :
3. TestFixtureAttribute



Which of the following operations can you NOT perform on an ADO.NET DataSet?

  1. A DataSet can be synchronised with the database.
  2. A DataSet can be synchronised with a RecordSet.
  3. A DataSet can be converted to XML.
  4. You can infer the schema from a DataSet.

Answer :
2. A DataSet can be synchronised with a RecordSet.


In Object Oriented Programming, how would you describe encapsulation?

  1. The conversion of one type of object to another.
  2. The runtime resolution of method calls.
  3. The exposition of data.
  4. The separation of interface and implementation.
Answer :
4. The separation of interface and implementation.


C# interview questions with answers, Part 1

C# developer interview questions with answers.



The C# keyword .int. maps to which .NET type?

  1. System.Int16
  2. System.Int32
  3. System.Int64
  4. System.Int128

Answer : 
2. System.Int32


Which of these statements correctly declares a two-dimensional array in C#?

  1. int[,] myArray;
  2. int[][] myArray;
  3. int[2] myArray;
  4. System.Array[2] myArray;


Answer : 
1. int[,] myArray;




Which of these string definitions will prevent escaping on backslashes in C#?

  1. string s = #.n Test string.;
  2. string s = ..n Test string.;
  3. string s = @.n Test string.;
  4. string s = .n Test string.;
Answer : 
3. string s = @.n Test string.;



If a method is marked as protected internal who can access it?

  1. Classes that are both in the same assembly and derived from the declaring class.
  2. Only methods that are in the same class as the method in question.
  3. Internal methods can be only be called using reflection.
  4. Classes within the same assembly, and classes derived from the declaring class.


Answer : 
4. Classes within the same assembly, and classes derived from the declaring class.



What is boxing?

  1. Encapsulating an object in a value type.
  2. Encapsulating a copy of an object in a value type.
  3. Encapsulating a value type in an object.
  4. Encapsulating a copy of a value type in an object.


Answer : 
4. Encapsulating a copy of a value type in an object.



What compiler switch creates an xml file from the xml comments in the files in an assembly?

  1. /text
  2. /doc
  3. /xml
  4. /help
Answer : 
2. /doc


What is a satellite Assembly?

  1. A peripheral assembly designed to monitor permissions requests from an application.
  2. Any DLL file used by an EXE file.
  3. An assembly containing localized resources for another assembly.
  4. An assembly designed to alter the appearance or .skin. of an application.
Answer : 
3. An assembly containing localized resources for another assembly.


How to count vowels in a string using c#

You can find vowel's occurrence in a string by many ways, one of them is below :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string s1 = "This is test string";
            int count = findVowel(s1);
            Console.WriteLine( "No of vowels in '" + s1 + "' is : " + count); 


        }


        private static int findVowel(string str)
        {
            int count = 0;
            for (int i = 0; i < str.Length - 1; i++)
            {
                switch (str[i])
                {
                    case 'a':
                        count++;
                        break;


                    case 'A':
                        count++;
                        break;


                    case 'e':
                        count++;
                        break;


                    case 'E':
                        count++;
                        break;


                    case 'i':
                        count++;
                        break;


                    case 'I':
                        count++;
                        break;


                    case 'o':
                        count++;
                        break;


                    case 'O':
                        count++;
                        break;


                    case 'u':
                        count++;
                        break;


                    case 'U':
                        count++;
                        break;
                }  // end switch
                
            }  // end for loop


            return count;
        }


    }
}

Hit Like, if it help full to you... :)

const and readonly in C# .NET


What is the difference between const and readonly in C#.NET?


The read only can be modified by the class it is contained in. However, the const cannot be modified. It needs to be instantiated only at the compile time.

Generics in C# .NET


What are generics in C#.NET?


Generic types to maximize code reuse, type safety, and performance. They can be used to create collection classes. Generic collection classes in the System.Collections.Generic namespace should be used instead of classes such as ArrayList in the System.Collections namespace.


or


Generics allow you to define type-safe data structures, without committing to actual data types. It allows writing less but more effective code. Generic provides flexibility and power but the developer needs to be responsible while using it.

Friday, June 29, 2012

Java Script Tutorial 25 : JavaScript RegExp Object


A regular expression (RegExp) is an object that describes a pattern of characters. When you search in a text, you can use a pattern to describe what you are searching for. A simple pattern can be one single character. A more complicated pattern can consist of more characters, and can be used for parsing, format checking, substitution and more. 
Regular expressions are used to perform powerful pattern-matching and search-and-replace functions on text. Syntax of RegExp is as follow :


var patterntxt=new RegExp(somepattern,modifiers);
or
var patt=/somepattern/modifiers;


In above code, somepattern specifies the pattern of an expression. modifiers specify if a search should be global, case-sensitive, etc.


RegExp Modifiers are used to perform case-insensitive and global searches. For example we use i modifier for case-insensitive matching and g modifier for global match. Global match means, find all matches rather than stopping after the first match. For example 



var str1 = "This is some text.";
var pattern = /some text/i;
document.write(str1.match(pattern));


The result of above case-sensitive search will be : some text 



The test() method searches a string for a specified value, and returns true or false, depending on the result. For example


var pattern=new RegExp("s");
document.write(pattern.test("The sun rises in the east"));


Result of above code will be "true", as it contains the "s" string.


The exec() method searches a string for a specified value, and returns the text of the found value. It return null,  in case no match found. For example


var pattern=new RegExp("s");
document.write(pattern.exec("The sun rises in the east."));


Result of above code will be "s", as it contains the "s" string.

Java Script Tutorial 24 : JavaScript Math Object

The Math object allows you to perform mathematical tasks. The Math object includes several mathematical constants and methods. Syntax for using properties/methods of Math is as follows:


var x=Math.PI;
var y=Math.sqrt(16);


There is eight mathematical constants in JavaScript that can be accessed from the Math object. These mathematical constants are : 


E
PI
square root of 2
square root of 1/2
natural log of 2
natural log of 10
base-2 log of E
base-10 log of E.


We can call/reference these constants from JavaScript as below:


Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E


There are many mathematical methods also available in JavaScript. For example Math.round() is used to round a number, e.g  


document.write(Math.round(9.8));


Result of above code will be : 10


Math.random() method of the Math object is used to generate random numbers. For example


document.write(Math.random());


Result of above code can be anything between 0 and 1.


We can set the limit of random number generation( by using arguments ). For example, the following code return random number between 0 and 20.


Math.random()*21)


To generate random number from 0 and 100 change 21 to 101.

Thursday, June 28, 2012

Java Script Tutorial 23 : JavaScript Boolean Object


The JavaScript Boolean object represents two values, "true" or/and "false". We can create a Boolean object in javascript as follows :


var myBooleanObj=new Boolean();


Javascript boolean object will set to false, if we do not set its initial value or has one of the following values:


0
-0
null
""
false
undefined
NaN


It will be true for any other value.

Java Script Tutorial 22 : JavaScript Array Object


An array is a special variable, which can hold more than one value, at a time. For example, if you have a list of items, storing the country names in single variables could look like as follow :


var country1="Pakistan";
var country2="USA";
var country3="Russia";


An array can hold all your variable values under a single name. And you can access the values by referring to the array name. Each element in the array has its own ID so that it can be easily accessed. We can defined array in following ways :


var country=new Array(); 
country[0]="Pakistan";
country[1]="USA";
country[2]="Russia";


or


var country=new Array("Pakistan","USA","Russia");


or


var country=["Pakistan","USA"," Russia"];


You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0. For example


document.write(country[1]);


Result of above code will be : USA


To modify a value in an existing array, just add a new value to the array with a specified index number:


country[1]="Germany";


This code change the value USA to Germany inside array object.


document.write(country[0]);


Now It will result as : Germany


Java Script Tutorial 21 : JavaScript Date Object


The JavaScript Date object is used to work with dates and times. Date objects are created with the Date() constructor. We can initiate date by four ways:

  • new Date()
  • new Date(milliseconds)
  • new Date(dateString)
  • new Date(year, month, day, hours, minutes, seconds, milliseconds)

We can operate a number of methods after creating a date object. These method allow you to get and set value of year, month, day, hour, minute, second, and milliseconds of the object. All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
For example


var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)


Set/Manipulate Dates :
We can easily manipulate the date by using the methods available for the Date object. For example


var myDateobj=new Date();
myDateobj.setFullYear(2011,0,15);


Adding days to a date shifts the month or year, the changes are handled automatically by the Date object itself.


Compare Two Dates :
We can also use Date object to compare two dates. For example


var y=new Date();
y.setFullYear(2110,0,16);
var current = new Date();
if  ( y > current )
   {
       alert("Current Date is before 16th January 2110");
   }
 else
   {
       alert("Current Date is after 14th January 2100");
   }

Java Script Tutorial 20 : JavaScript Objects


JavaScript is an Object Based Programming language, and allows you to define your own objects and make your own variable types. 
An object is just a special kind of data. An object has properties and methods. We can create our own objects in java script, which will be discussed in future tutorials. 


Properties :
Properties are the values associated with an object. For example


<script type="text/javascript">
     var txt="This is text.";
     document.write(txt.length);
</script>


In above code, txt is an object and length is its property. Result displayed in browser will be : 13


Methods :
Methods are the actions that can be performed on objects. For example


<script type="text/javascript">
     var txt="This is Text";
     document.write(txt.toUpperCase());
</script>


In above code txt is an object and toUpperCase() is method.  Result displayed in browser will be : 
THIS IS TEXT


Tuesday, June 26, 2012

Java Script Tutorial 19 : JavaScript Special Characters


In JavaScript, Special characters can be added to a text string by using the backslash sign. For example we want to display following text in JavaScript code. 


var txt="This "This is a "big" Apple.";


In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: 


This is a  


We must place a backslash (\) before each double quote in "big" to solve this problem. This result string will look like this :


var txt="This "This is a \"big\" Apple.";


After executing in browser, it will display string as : 


This is a "big" Apple. 


There are many other special characters that can be added to a text string with the backslash sign, these are :


\'          (  single quote  )
\"         (  double quote  )
\\          (  backslash  )
\n         (  new line  )
\r          (  carriage return  )
\t          (  tab  )
\b         (  backspace)
\f          (  form feed  )

Java Script Tutorial 18 : JavaScript Throw


JavaScript throw statement allows you to create an exception. If you use this statement together with the try .. catch statement, you can control program flow and generate error messages. The exception can be a string, integer, Boolean or an object. Syntax of throw is as:


throw exception


For example


<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 2 and 5:","");
try

       if(x>5)
         {
             throw "Error 1";
         }
       else if(x<2)
         {
             throw "Error 2";
         }
 }
 catch(err)
 {
       if(err=="Error 1")
         {
              document.write("The value is higher then 5.");
         }
       if(err=="Error 2")
         {
              document.write("The value is lower then 2.");
         }  
 }
</script>
</body>
</html>


Java Script Tutorial 17 : JavaScript Try .. Catch

JavaScript try .. catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. Syntax of JS try .. catch is :


try
  {
       // code
  }
catch()
  {
       // Handle errors
  }


For example


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var txt="";
function Showmessage()
{
     try
       {
            adddlert("JS try .. catch testing ....");
       }
     catch(err)
       {
            txt="There was an error on this page.";
            alert(txt);
       }
}
</script>
</head>
<body>
   <input type="button" value="Click to View message" onclick="Showmessage()" />
</body>
</html>

Friday, June 22, 2012

Java Script Tutorial 16 : JavaScript Events

Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags. Following are some events we use in javascript.
  • A mouse click
  • A web page loading
  • Mousing over
  • Selecting an input field
  • Submitting an HTML form
  • A keystroke
Details of some some events are below.


onLoad and onUnload :
The onLoad and onUnload events are triggered when the user enters or leaves the page. The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.


Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page.


onFocus, onBlur and onChange :
The onFocus, onBlur and onChange events are often used in combination with validation of form fields. In following example the validateEmail() function will be called whenever the user changes the content of the field.


<input type="text" size="30" id="email" onchange="validateEmail()" />


onSubmit :
The onSubmit event is used to validate ALL form fields before submitting it. In following example, the validateForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be cancelled. The function validateForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled.


<form method="post" action="mypage.htm" onsubmit="return validateForm()">


onMouseOver :
The onmouseover event can be used to trigger/call a function when the user mouses over an HTML element.