Monday, 25 September 2017

Convert JSON to HTML Table

The following jQuery code will create a table element, populates the table data from JSON data and appends the table element to the HTML body. The function uses jQuery syntax for different table elements like header row and table row. Inside the JSON array loop, it appends the data in appropriate objects, and finally it is added to the HTML body.

function ConvertToTable(jData) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var $table = $('');
  var $headerTr = $('');

  for (var index in arrJSON[0]) {
    $headerTr.append($(' ').html(index));
  }
  $table.append($headerTr);
  for (var i = 0; i < arrJSON.length; i++) {
   var $tableTr = $('');
    for (var index in arrJSON[i]) {
      $tableTr.append($(' ').html(arrJSON[i][index]));
    }
    $table.append($tableTr);
  }
  $('body').append($table);
}

Here the table formatting needs to be handled via CSS. You can also incorporate the same in this code with slight modifications.

Convert JSON to CSV

If you want to convert JSON data to CSV for export purpose, the following jQuery code will help you. The following jQuery code defines a function called ConvertToCSV which takes JSON string, converts to CSV and returns it. Since it’s not compulsory to have comma as a delimiter for CSV, the delimiter is passed from outside which helps in changing the delimiter in the future without changing the actual function. The function first converts the JSON data into an array and then loops through the array to create a delimited string.

var jData = '[{"fname":"Mark", "lname":"Wood", "company":"Apple"},' +
  '{"fname":"Steve", "lname":"Jones", "company":"Amazon"},' +
  '{"fname":"Bill", "lname":"Peterson", "company":"HP"},' +
  '{"fname":"Peter", "lname":"Jacobs", "company":"Dell"}]';

var seperator = ',';
var sCSV = ConvertToCSV(jData, seperator);

function ConvertToCSV(jData, delimiter) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var sReturnVal = '';
  for (var i = 0; i < arrJSON.length; i++) {
    var sLine = '';
    for (var index in arrJSON[i]) {
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    }
    sReturnVal += sLine + '\r\n';
  }
  return sReturnVal;
}

The above function just creates a delimited string, it doesn’t allow you to save it as a .csv file. If you wish to export/download the JSON data into a CSV file with column headings and an optional report title, the following jQuery code provides a solution for the same. The modified function now expects 3 more parameters: report title, flag to display header, and a file name. While calling the function, please consider following things:


  • If you don’t wish to have a report title, pass an empty string.
  • In case you don’t need a column header, pass ShowHeader as false.
  • Pass the file name without the .csv extension.


The function does the following things:


  • First, parses the JSON data in an object, if not already.
  • If report title is not empty, appends the title to the variable.
  • If ShowHeader is true, then loop through the array’s 0th element to get the header columns and then appends them in the variable.
  • Then loop the array to get the data and creates a delimiter separated string.
  • Once the loop is completed, check the variable for any errors. An empty value means the JSON data is not correct. In such a case, it logs the error and exits the function.
  • If everything is correct, then initialize file format. The file format is CSV in this case.
  • Then it creates a temporary anchor tag and appends it to the HTML body with hidden visibility. Assigns the href and download attribute values and calls the anchor click function. Finally, removes it again from the body as it’s no longer needed.

function ConvertToCSV(jData, title, ShowHeader, fileName, delimiter) {
  var arrJSON = typeof jData != 'object' ? JSON.parse(jData) : jData;
  var strCSV = '';
  //Set title first.
  if (title.length > 0)
    strCSV += title + '\r\n\n';
  if (ShowHeader) {
    var headerRow = "";
    for (var index in arrJSON[0]) {
      if (headerRow != '') headerRow += delimiter;
      headerRow += index;
    }
    strCSV += headerRow + '\r\n';
  }
  for (var i = 0; i < arrJSON.length; i++) {
    var sLine = '';
    for (var index in arrJSON[i]) {
      if (sLine != '') sLine += delimiter;
      sLine += arrJSON[i][index];
    }
    strCSV += sLine + '\r\n';
  }
  if (strCSV == '') {
    console.log('Error while converting due to invalid data');
    return;
  }
  var uri = 'data:text/csv;charset=utf-8,' + escape(strCSV);
  var link = document.createElement("a");
  link.href = uri;
  link.style = "visibility:hidden";
  link.download = fileName + ".csv";
  $('body').append(link);
  link.click();
  $('body').remove(link);
}

Call this function on any event to convert the JSON data into a downloadable CSV file like:

ConvertToCSV(jData, "Employee Data", true, "EmployeeReport", seperator);

Object Class in .NET


  • Object class supports all classes in the .NET framework class hierarchy.
  • Provide low level services to derived classes.
  • It is the root of the type hierarchy.


The object class has following methods:

1) Equals(Object): Determines whether the specified object is equal to the current object.

2) GetType(): Get the type of the current instance OR returns type of the object.

3) ReferenceEquals(): Determines whether the specified object instances are the same instance.

4) ToString(): Converts an instance to a string type.

5) GetHashCode(): Returns hashcode for an object OR serves as the default has function.

6) MemberwiseClone(): Creates a shallow copy of the current object.

7) Finalize(): Allows an object to try to free resources & perform other cleanup operations before it is reclaimed by garbage collection.

-Derived classes can & do override some of these methods like equals, finalize, GetHashCode, ToString.


Read data from json File using jquery in .NET

1) Add json file in your solution. like sample.json

2) Create a function in jQuery

function ReadJsonFile()
    {
        var obj = {};
        obj.fileName = '<%=ResolveUrl("sample.json") %>';
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetData",
            data: JSON.stringify(obj),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                debugger;
                var array = $.parseJSON(response.d);
             
               // $('[id*=Name]').val(array[0].Name);
                //$('[id*=age]').val(array[0].Age);
            },
            failure: function (response) {
                alert('hello');
                alert(response.d);
            },
            error: function (response) {
                alert('hru');
                alert(response.d);
            }
        });
    }

3) [WebMethod]
    public static string GetData(string fileName)
    {
        using (StreamReader sr = File.OpenText(HttpContext.Current.Server.MapPath(fileName)))
        {
            string json = sr.ReadToEnd();
            return json;
        }
    }

4) Set the limit of json in web.config file if json file contains the binary data

<system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="50000000"/>
           </webServices>
       </scripting>
   </system.web.extensions>

Sunday, 24 September 2017

Some key benefits of the .NET platform

The .NET platform were first introduced to the world in 2002 & were intended to offer a much more powerful, more flexible, and simpler programming model than COM.

Some key benefits of  .NET platform are:

Interoperability with existing code:

The existing COM binaries can commingle i.e. interop with newer .NET software and vice versa. As of .NET 4.0 onward, interoperability has been further simplified with the addition to the 'dynamic' keyword.

Support for numerous programming languages:

.NET applications can be created using any number of programming languages(C#, VB, F#, etc).

A common runtime engine shared by all .NET aware languages:

All .NET aware languages share common runtime engine i.e. CLR(Common Language Runtime).

Language Integration:

.NET supports cross-language inheritance, cross-language exception handling and cross-language debugging of code.
For eg:- you can define a base class in C#, and extend this type in VB.

A comprehensive base class library:

This library provides shelter from the complexities of low-level API calls and offer a consistent object model used by all .NET aware languages.

A simplified deployment model:

Unlike COM, .NET libraries are not registered into the system registry. The .NET platform allows multiple versions of the same .dll to exists in harmony on a single machine.

ASP.NET Page Life Cycle Events

Pre Init:

  • Check for "IsPostBack" property to determine whether this is the first time the page is being processed.
  • Create or recreate dynamic controls.
  • Set master page dynamically & theme property also.
  • Read or set profile property values.
  • This event can be handled by overloading the OnPreInit method or creating the Page-PreInit handler.

Init:

  • In the Init event of the individual controls occurs first, later the Init event of the page takes place.
  • This event is used to initialize control properties.
  • This event can be handled by overloading the OnInit method or creating a Page-Init handler.

InitComplete:

  • This event allows tracking of View State.
  • Raised at the end of the page's initialization stage.
  • View state tracking enables controls to persists any values that are programmatically added to the view state collection.
  • Untill view state  tracking is turned on, any values added to view state are lost across postbacks.
  • Controls typically turn on view state tracking immediately after they raise their Init event.
  • Any changes made to the view state in this event are persisted even after the next postback.

PreLoad:

  • This event process the postback data that is included with the request.

Load:

  • In this event the page object calls the onload method on the page object itself, later the onload method of the controls is called.
  • This load event of the individual controls occurs after the load event of the page.

Control Events:

  • This event is used to handle specific control events such as button control's click event or a textbox control's TextChanged event.

LoadComplete:

  • This event occurs after  the event handling stage.
  • This event is used for tasks such as loading all other controls on the page.

PreRender:

  • PreRender event of the pageis called first and later for the child controls.
  • This event is used to make the final changes to the controls on the page like assigning the DataSourceID and calling the DataBind Method.
  • Prerender event occurs just before the output is rendered.
  • By handling this event, pages & controls can perform any updates before the output is rendered.

Prerender Complete:

  • This event is raised after each control's Prerender property is completed.

SaveState Complete:

  • This event is raised after the control state & view state have been saved for the page and for all controls.
  • The HTML markup is generated.

Render Complete:

  • The page object calls this method on each control which is present on the page.
  • This method write's the control's markup to send it to the browser.

Unload:

  • This event is raised for each control and then for the page object.
  • Use this event in controls for final cleanup work, such as closing open database connections, closing open files, etc.

Difference between ASP(Classic ASP) and ASP.NET

Classic ASP:

  • ASP is interpreted based on scripting languages like JScript or VBScript.
  • ASP has mixed HTML & coding logic.
  • Limited development and debugging tools available.
  • Limited OOPS support.
  • Limited session & application state management.


ASP.NET:

  • ASP.NET is supported by compiler and has a compiled language support.
  • Separate code and design logic possible.
  • Variety of compilers and tools available including the visual studio .NET.
  • Completely object oriented.
  • Complete session and application state management.
  • Full XML support for easy data exchange.

Versions of .NET Framework:

  1. .NET Framework 1.0
  2. .NET Framework 1.1
  3. .NET Framework 2.0
  4. .NET Framework 3.0
  5. .NET Framework 3.5
  6. .NET Framework 4.0
  7. .NET Framework 4.5

Command to start visual studio from command prompt: deven

Handling JSON with jQuery



  • JSON (JavaScript Object Notation) is a way to store information in an organized manner.
  • It is the preferred data-interchange format as its shorter, lightweight, human-readable and requires no tags like XML.
  • This allows faster processing and transmission, and also the serializing and deserializing becomes much faster when compared to XML.
  • JSON returned via REST APIs is used in different ways on the client side.
     
  • You can populate data in HTML elements, display the JSON on the UI after formatting and convert it to CSV for exporting. 


Format JSON in jQuery


  • Unformatted JSON is not human-readable and most of the time the JSON returned by REST APIs are not formatted, hence can’t be displayed directly on the UI.
  • There are different ways to format it. Either using your own implementation or third-party plugins. 

Formatting the JSON using jQuery can be done easily and requires only 2 function calls:

1) JSON.parse() / jQuery.parseJSON() – To parse a JSON string and convert it to a JavaScript object.

2) JSON.stringify() – Convert a JavaScript object into a string. You can also apply indentation by passing an optional value.

The following jQuery code formats a JSON string:

Example:-
var jData = '[{"fname":"Mark", "lname":"Wood", "company":"Apple"},' +
'{"fname":"Steve", "lname":"Jones", "company":"Amazon"},' +
'{"fname":"Bill", "lname":"Peterson", "company":"HP"},' +
'{"fname":"Peter", "lname":"Jacobs", "company":"Dell"}]';

var tmpData = JSON.parse(jData);
var formattedJson = JSON.stringify(tmpData, null, '\t');

Here, the formattedJson variable will have the formatted JSON string, indented using tab.
To display formatted JSON on UI, use the <pre> tag only. If you want to display inside a div, you would need to first append the <pre> tag in the div element.

example:- :$('#dvText').append($('<pre>').text(formattedJson));

jQuery.parseJSON vs JSON.parse


  • JSON.parse() and jQuery.parseJSON(), both are used to parse a JSON string and returns resulting JavaScript value or object described by the string.
  • jQuery.parseJSON() is available only when jQuery library is used where JSON.parse() is JavaScript’s standard built-in JSON object method. 

So the question is if jQuery library is used, then which one should be used or both gives same performance and result?

Well, the answer is that both are equal. As you know, jQuery’s library is written on top of JavaScript.
So  jQuery.parseJSON() makes use of JSON.parse() internally.

Here is the code of jQuery.parseJSON() method from jQuery 1.9.1 library.
As you can see, it first checks if JSON.parse is supported or not.
If supported, then it makes use of JSON.parse only. Otherwise, it tries to evaluate string data with new Function.

// Attempt to parse using the native JSON parser first
if (window.JSON && window.JSON.parse) {
    return window.JSON.parse(data);
}

if (data === null) {
    return data;
}

if (typeof data === "string") {
    // Make sure leading/trailing whitespace is removed (IE can't handle it)
    data = jQuery.trim(data);
    if (data) {
        // Make sure the incoming data is actual JSON
        // Logic borrowed from http://json.org/json2.js
        if (rvalidchars.test(data.replace(rvalidescape, "@")
                .replace(rvalidtokens, "]")
                .replace(rvalidbraces, ""))) {

            return (new Function("return " + data))();
        }
    }
}
jQuery.error("Invalid JSON: " + data);
}

This was done as JSON.parse is natively available on some browsers, and jQuery is browser independent. So if JSON.parse is not available, then it falls back to jQuery implementation.

JSON.parse was not supported in old browsers like IE 7 and Safari 3, but over the period of time, browsers have also evolved. And now most of the browsers support JSON.parse. Therefore, the implementation of jQuery.parseJSON() is also changed after jQuery 2.0 release.
Here is the code of new implementation from jQuery 2.2.4 library:

// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function(data) {
    return JSON.parse(data + "");
};

And the big news is that with jQuery 3.0, jQuery.parseJSON is deprecated. So now to parse JSON objects, use the native JSON.parse method instead.

Monday, 18 September 2017

PACKAGE in Oracle


  • A package is a schema object that groups logically related PL/SQL types, variables, constants, procedures, subprograms, cursors, and exceptions.
  • A package is compiled and stored in the database, where many applications can share its contents. You can think of a package as an application.
  • Every cursor or subprogram declaration in the package specification must have a corresponding definition in the package body.
  • The headings of corresponding subprogram declarations and definitions must match word for word, except for white space.


  • The cursors and subprograms declared in the package specification and defined in the package body are public items that can be referenced from outside the package.
  • The package body can also declare and define private items that cannot be referenced from outside the package, but are necessary for the internal workings of the package.
  • The body can have an initialization part, whose statements initialize public variables and do other one-time setup steps.
  • The initialization part runs only the first time the package is referenced. The initialization part can include an exception handler.

Package Instantiation and Initialization:

  • When a session references a package item, Oracle Database instantiates the package for that session. Every session that references a package has its own instantiation of that package.
  • When Oracle Database instantiates a package, it initializes it. Initialization includes whichever of the following are applicable:
    - Assigning initial values to public constants.
    - Assigning initial values to public variables whose declarations specify them.
    - Executing the initialization part of the package body
Advantages of Packages:

  • Cohesion: all the procedures and functions relating to a specfic sub-system are in one program unit. This is just good design practice but it's also easier to manage, e.g. in source control.
  • Constants, sub-types and other useful things: Anything we can define in a package spec can be shared with other programs, for instance user-defined exceptions.
  • Overloading: the ability to define a procedure or function with the same name but different signatures.
  • Security: defining private procedures in the package body which can only be used by the package because they aren't exposed in the specification.
  • Sharing common code: another benefit of private procedures.
  • We only need to grant EXECUTE on a package rather than on several procedures.

Datatypes in Oracle

Each value manipulated by Oracle Database has a datatype. The datatype of a value associates a fixed set of properties with the value. These properties cause Oracle to treat values of one datatype differently from values of another. For example, you can add values of NUMBER datatype, but not values of RAW datatype.

Oracle Database provides a number of built-in datatypes as well as several categories for user-defined types that can be used as datatypes.

Oracle Built-in Data Types:




Oracle supports 4 datetime types:

- DATE: fixed length of 7 bytes and comprises the century, year, month, day, hour, minute and second of a date between 1 January 4712 BC and 31 December 9999 AD.
The default date values are determined as follows:
  • The year is the current year, as returned by SYSDATE.
  • The month is the current month, as returned by SYSDATE.
  • The day is 01 (the first day of the month).
  • The hour, minute, and second are all 0.
eg: SELECT TO_DATE('2017', 'YYYY') FROM DUAL;

TO_DATE
01-Jan-2017
TO_DATE function converts a character or numeric value to a date.

You can use the date format model "J" with date functions TO_DATE and TO_CHAR to convert between Oracle DATE values and their Julian equivalents. The following statement returns the Julian equivalent of January 1, 2017 :

SELECT TO_CHAR(TO_DATE('01-01-2015', 'MM-DD-YYYY'),'J') FROM DUAL;  
      TO_CHAR  
      -------  

      2457024  

- TIMESTAMP: extend the DATE data type and enable fractions of a second to be stored (with a precision of up to 9 digits) along with the year, month, day, hour and minute.
This datatype is useful for storing precise time values.

Syntax: TIMESTAMP [(fractional_seconds_precision)]

- TIMESTAMP WITH TIME ZONE: also stores the time zone region name or offset from UTC (GMT) to enable local time zone information to be preserved.

Syntax: TIMESTAMP [(fractional_seconds_precision)] WITH TIME ZONE

- TIMESTAMP WITH LOCAL TIME ZONE: data is converted to the database time zone when it is stored and to the time zone of the user when it is retrieved.

Syntax: TIMESTAMP [(fractional_seconds_precision)] WITH LOCAL TIME ZONE


Oracle supports 2 interval types: 

To store a period of time rather than a specific date and time.

- INTERVAL YEAR TO MONTH: stores a period of time as years (with a precision from 0 to 9 digits) and months (with a value from 0 to 11).

Syntax: INTERVAL YEAR [(year_precision)] TO MONTH


- INTERVAL DAY TO SECOND: stores a period of time as days (with a precision from 0 to 9 digits), hours, minutes and seconds (with a fractional second precision from 0 to 9 digits).

Syntax: INTERVAL DAY [(day_precision)]  TO SECOND [(fractional_seconds_precision)]

where


  • day_precision is the number of digits in the DAY datetime field. Accepted values are 0 to 9. The default is 2.
  • fractional_seconds_precision is the number of digits in the fractional part of the SECOND datetime field. Accepted values are 0 to 9. The default is 6.

RAW and LONG RAW Datatypes:

The RAW and LONG RAW datatypes store data that is not to be interpreted (that is, not explicitly converted when moving data between different systems) by Oracle Database. These datatypes are intended for binary data or byte strings. For example, you can use LONG RAW to store graphics, sound, documents, or arrays of binary data, for which the interpretation is dependent on the use.

Oracle strongly recommends that you convert LONG RAW columns to binary LOB (BLOB) columns.
RAW is a variable-length datatype like VARCHAR2, except that Oracle Net (which connects user sessions to the instance) and the Import and Export utilities do not perform character conversion when transmitting RAW or LONG RAW data.
When Oracle automatically converts RAW or LONG RAW data to and from CHAR data, the binary data is represented in hexadecimal form, with one hexadecimal character representing every four bits of RAW data. For example, one byte of RAW data with bits 11001011 is displayed and entered as CB.

Large Object (LOB) Datatypes:

The built-in LOB datatypes BLOB, CLOB, and NCLOB (stored internally) and BFILE (stored externally) can store large and unstructured data such as text, image, video, and spatial data.

The size of BLOB, CLOB, and NCLOB data can be up to (4 gigabytes -1) * (the value of the CHUNK parameter of LOB storage).
LOB columns contain LOB locators that can refer to in-line (in the database) or out-of-line (outside the database) LOB values. Selecting a LOB from a table actually returns the LOB locator and not the entire LOB value. 


  •  BLOB datatype stores unstructured binary large objects. BLOB objects can be thought of as bitstreams with no character set semantics.
  • The CLOB datatype stores single-byte and multibyte character data. Both fixed-width and variable-width character sets are supported, and both use the database character set.
  • The NCLOB datatype stores Unicode data.
  • BFILE: Contains a locator to a large binary file stored outside the database. Enables byte stream I/O access to external LOBs residing on the database server. Maximum size is 4 gigabytes.
    You can change the filename and path of a BFILE without affecting the base table by using the BFILENAME function.

BLOB, CLOB and NCLOB objects have full transactional support.

ANSI, DB2, and SQL/DS Data Types

Oracle recognizes the ANSI or IBM data type name that differs from the Oracle Database data type name and it converts the data type to the equivalent Oracle data type. Following table shows the conversions :


Oracle-Supplied Types

Oracle provides some new data types which are not present in built-in or ANSI-supported types. These types can be implemented in C/C++, Java, or PL/ SQL. Here is the details :


Any Types :

The Any types provide highly flexible modeling of procedure parameters and table columns where the actual type is not known. These data types let you dynamically encapsulate and access type descriptions, data instances, and sets of data instances of any other SQL type. These types have OCI and PL/SQL interfaces for construction and access.



XML Types :

This Oracle-supplied type can be used to store and query XML data in the database. XMLType has member functions you can use to access, extract, and query the XML data using XPath expressions. XMLType is a system-defined type, so you can use it as an argument of a function or as the data type of a table or view column. You can also create tables and views of XMLType. When you create an XMLType column in a table, you can choose to store the XML data in a CLOB column, as binary XML (stored internally as a CLOB), or object relationally.

URI Data Types:

Oracle supplies a family of URI types—URIType, DBURIType, XDBURIType, and HTTPURIType—which are related by an inheritance hierarchy.



Spatial Types:

Oracle Spatial is designed to make spatial data management easier and more natural to users of location-enabled applications, geographic information system (GIS) applications, and geoimaging applications. After the spatial data is stored in an Oracle Database, you can easily manipulate, retrieve, and relate it to all the other data stored in the database. The following data types are available only if you have installed Oracle Spatial.


Media Types:


Oracle Multimedia uses object types, similar to Java or C++ classes, to describe multimedia data. An instance of these object types consists of attributes, including metadata and the media data, and methods. The Multimedia data types are created in the ORDSYS schema. Public synonyms exist for all the data types, so you can access them without specifying the schema name. 
Oracle Multimedia provides the following object types:





Friday, 15 September 2017

SEQUENCE in Oracle


sequence is an object in Oracle that is used to generate a number sequence. This can be useful when you need to create a unique number to act as a primary key.

Use the CREATE SEQUENCE statement to create a sequence, which is a database object from which multiple users may generate unique integers. You can use sequences to automatically generate primary key values.

 - When a sequence number is generated, the sequence is incremented, independent of the transaction committing or rolling back.

CREATE SEQUENCE sequence_name
  MINVALUE value
  MAXVALUE value
  START WITH value
  INCREMENT BY value
  CACHE value;

* MAXVALUE: Specify the maximum value the sequence can generate. This integer value can have 28 or fewer digits. MAXVALUE must be equal to or greater than START WITH and must be greater than MINVALUE.

* NOMAXVALUE: Specify NOMAXVALUE to indicate a maximum value of 1027 for an ascending sequence or -1 for a descending sequence. This is the default.

* MINVALUE : Specify the minimum value of the sequence. This integer value can have 28 or fewer digits. MINVALUE must be less than or equal to START WITH and must be less than MAXVALUE.

* NOMINVALUE: Specify NOMINVALUE to indicate a minimum value of 1 for an ascending sequence or -1026 for a descending sequence. This is the default.

* CYCLE: Specify CYCLE to indicate that the sequence continues to generate values after reaching either its maximum or minimum value. After an ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its maximum value.

* NOCYCLE : Specify NOCYCLE to indicate that the sequence cannot generate more values after reaching its maximum or minimum value. This is the default.

* CACHE: Specify how many values of the sequence the database preallocates and keeps in memory for faster access.

* NOCACHE: Specify NOCACHE to indicate that values of the sequence are not preallocated. If you omit both CACHE and NOCACHE, then the database caches 20 sequence numbers by default.

* ORDER: Specify ORDER to guarantee that sequence numbers are generated in order of request. This clause is useful if you are using the sequence numbers as timestamps. Guaranteeing order is usually not important for sequences used to generate primary keys.

* NOORDER: Specify NOORDER if you do not want to guarantee sequence numbers are generated in order of request. This is the default.


Little description about Oracle Database

Overview:

- A database is a organised collection of data. eg: address book, either on your phone or in a physical book.

- A Relational Database is a database in which the data is organised according to type with the relationships being maintained between the differing types.

The latest version of the database is Oracle 12c.


Different editions of Oracle database:

* Enterprise Edition: It is the most robust and secure edition. It offers all features, including superior performance and security.

* Standard Edition: It provides the base functionality for users that do not require Enterprise Edition's robust package.

* Express Edition (XE): It is the lightweight, free and limited Windows and Linux edition.

* Oracle Lite: It is designed for mobile devices.


Some important terms:

TNSNAMES.ORA: This files contains the information which is used by the system to connect to oracle database.

TNS file contains :
1) PROTOCOL ( Mostly TCP..TransmissionControlProtocol)
2) HOST IP ADDRESS (Where the Database is resided ..Generally we call it as Server.Even the DSCP number acts as substitute)
3) PORTNUMBER ( 1521..Widely used by oracle)
4) SID (the name we provide for DataBase)

5) SERVER (Dedicated/Shared Which is defined at DB CREATION LEVEL)


- SID: System Identifier is the unique name of the database.

To switch between Oracle databases, users must specify the desired SID. The SID is included in the CONNECT DATA parts of the connect descriptors in a TNSNAMES.ORA file, and in the definition of the network listener in the LISTENER.ORA file.
This file is usually located at the following path:

.....\oracle\product\10.2.0\db_1\NETWORK\ADMIN

- DATABASE LINK: A database link is a schema object in one database that enables you to access objects on another database.

 The other database need not be an Oracle Database system. However, to access non-Oracle systems you must use Oracle Heterogeneous Services.

Use the CREATE DATABASE LINK statement to create a database link.

create public database link mylink
connect to remote_username
identified by mypassword
using 'myserver:1621/MYSID'

The data accessible on the remote database depends on the identity the database link uses when connecting to the remote database:

- If you specify CONNECT TO user IDENTIFIED BY password, then the database link connects with the specified user and password.

- If you specify CONNECT TO CURRENT_USER, then the database link connects with the user in effect based on the scope in which the link is used.

- If you omit both of those clauses, then the database link connects to the remote database as the locally connected user.

Specify PUBLIC to create a public database link visible to all users. If you omit this clause, then the database link is private and is available only to you.

Specify SHARED to create a database link that can be shared by multiple sessions using a single network connection from the source database to the target database.


Basic jQuery interview questions


Q)  Which command will give a version of jQuery?

The command $.ui.version returns jQuery UI version.

Q)  In what scenarios jQuery can be used?

jQuery can be used in following scenarios:

- Apply CSS static or dynamic
- Calling functions on events
- Manipulation purpose
- Mainly for Animation effects

Q) What is the difference between find and children methods?

find method is used to find all levels down the DOM tree but children find single level down the DOM tree.

Q) What is jQuery connect?

A ‘ jQuery connect’  is a plugin used to connect or bind a function with another  function. Connect is used to execute function from any other function or plugin is executed.

Q)  How to use connect?

Connect can be used by downloading jQuery connect file from jQuery.com and then include that file in the HTML file. Use $.connect function to connect a function to another function.

Q) What are the browser related issues for jQuery?

Browser compatibility of jQuery plugin is an issue and needs lot of time to fix it.

Q) Whether we need to add jQuery file in both Master and Content page?

jQuery file should be added to the Master page and can use access from the content page directly without having any reference to it.

Q) What are the basic selectors in jQuery?

Following are the basic selectors in jQuery:

- Element ID
- CSS Name
- Tag Name
- DOM hierarchy

Q) What is the use jQuery.data method?

jQuery.data methods is used to associate the data with the DOM nodes and the objects. This data method makes the jQuery code clear and concise.

Q) What is the use of each function in jQuery?

Each function is used to iterate each and every element of an object. It is used to loop DOM elements, arrays and the object properties.

Q) What is the difference between size and length of jQuery?

Size and length both returns the number of element in an object. But length is faster than the size because length is a property and size is a method.

Q) Can we add more than one ‘document.ready’ function in a page?

Yes, we can add more than one document.ready function in a page. But, body.onload can be added once in a page.

Q) What is the use of jQuery load method?

jQuery load method is a powerful AJAX method which is used to load the data from a server and assign the data into the element without loading the page.

Q) Whether our own specific characters are used in place of $ in jQuery?

Yes, We can use our own variable in place of $ by using the method called no Conflict () method.

var sample = $.noConflict()

Q) What is the use of jQuery filter?

The jQuery filter is used to filter the certain values from the object list based on the criteria. Example is to filter certain products from the master list of products in a cart website.

Q) Which program is useful for testing jQuery?

QUnit is used to test jQuery and it is very easy and efficient.

Q) What is the script build up by jQuery?

jQuery is a Javascript file and it is single javascript file that contains common DOM, event effects and Ajax functions.

Q) How can we debug jQuery?

There are two ways to debug jQuery:

Debugger keyword

- Add the debugger to the line from where we have to start debugging and then run Visual Studio in Debug mode with F5 function key.
- Insert a break point after attaching the process

Q) What are all the ways to include jQuery in a page?

Following are the ways to include jQuery in a page:

- Local copy inside script tag
- Remote copy of jQuery.com
- Remote copy of Ajax API
- Local copy of script manager control
- Embedded script using client script object

Q) What is the use of jQuery.ajax method ()?

jQuery.ajax method is used for asynchronous HTTP requests.

Q) Is jQuery is a replacement of JavaScript?

No, jQuery is not a replacement of JavaScript.

Q) What is called chaining?

Chaining is used to connect multiple events and functions in a selector.

Q) What is the difference between onload() and document.ready()?

In a page, we can have only one onload function but we can have more than one document.ready function. Document.ready function is called when DOM is loaded but body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.

Q) How method can be called inside code behind using jQuery?

$.ajax can be called and by declaring WebMethod inside code behind using jQuery.

Q) Which is the fastest selector in jQuery?

ID and Element are the fastest selectors in jQuery.

Q) What is the slowest selector in jQuery?

Class selectors are the slowest selectors in jQuery.

Q) What is the difference between .js and .min.js?

Ans: jQuery library comes in 2 different versions Development and Production/Deployment. The deployment version is also known as minified version. So .min.js is basically the minified version of jQuery library file. Both the files are same as far as functionality is concerned. but .min.js is quite small in size so it loads quickly and saves bandwidth.

Q) Why there are two different version of jQuery library?

Ans: jQuery library comes in 2 different versions.
Development 
Production/Deployment
The development version is quite useful at development time as jQuery is open source and if you want to change something then you can make those changes in development version. But the deployment version is minified version or compressed version so it is impossible to make changes in it. Because it is compressed, so its size is very less than the production version which affects the page load time.

Q) What does $("div.parent") will select?

Ans: All the div element with parent class.

Q) How jQuery selectors are executed?

Ans: Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class ".myCssClass" and after that it will reject all the other elements which are not in "p#elmID".

$("p#elmID .myCssClass");

Q) Which is fast document.getElementByID('txtName') or $('#txtName').?

Ans: Native JavaScipt is always fast. jQuery method to select txtName "$('#txtName')" will internally makes a call to document.getElementByID('txtName'). As jQuery is written on top of JavaScript and it internally uses JavaScript only So JavaScript is always fast.

Q) Difference between $(this) and 'this' in jQuery?

Ans: this and $(this) refers to the same element. The only difference is the way they are used. 'this' is used in traditional sense, when 'this' is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.

$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert($(this).text());
  });
});

In below example, this is an object but since it is not wrapped in $(), we can't use jQuery method and use the native JavaScript to get the value of span element.

$(document).ready(function(){
    $('#spnValue').mouseover(function(){
       alert(this.innerText);
  });
});

Q) How do you check if an element is empty?

Ans: There are 2 ways to check if element is empty or not. We can check using ":empty" selector.

$(document).ready(function(){
    if ($('#element').is(':empty')){
       //Element is empty
  }
});  
And the second way is using the "$.trim()" method.

$(document).ready(function(){
    if($.trim($('#element').html())=='') {
       //Element is empty
  }
});  

Q) What is the difference between $('div') and $('<div/>') in jQuery?

Ans: $('<div/>') : This creates a new div element. However this is not added to DOM tree unless you don't append it to any DOM element.

$('div') : This selects all the div element present on the page.

Q) What is the difference between parent() and parents() methods in jQuery?

Ans: The basic difference is the parent() function travels only one level in the DOM tree, where parents() function search through the whole DOM tree.

Q) What is the difference between eq() and get() methods in jQuery?

Ans: eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element within that set and returns it. That means that you can use jQuery functions on it.

get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can't be used. 

Q) How do you implement animation functionality?

Ans: The .animate() method allows us to create animation effects on any numeric CSS property. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

Syntax is:

(selector).animate({styles},speed,easing,callback)
styles: Specifies one or more CSS properties/values to animate.
duration: Optional. Specifies the speed of the animation.
easing: Optional. Specifies the speed of the element in different points of the animation. Default value is "swing".
callback: Optional. A function to be executed after the animation completes.
Simple use of animate function is,

$("btnClick").click(function(){
  $("#dvBox").animate({height:"100px"});
});

Q) How to disable jQuery animation?

Ans: Using jQuery property "jQuery.fx.off", which when set to true, disables all the jQuery animation. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.

Q) How do you stop the currently-running animation?

Ans: Using jQuery ".stop()" method.

Q) What is the difference between .empty(), .remove() and .detach() methods in jQuery?

Ans: All these methods .empty(), .remove() and .detach() are used for removing elements from DOM but they all are different.

.empty(): This method removes all the child element of the matched element where remove() method removes set of matched elements from DOM.

.remove(): Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

.detach(): This method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

Q) What is wrong with this code line "$('#myid.3').text('blah blah!!!');"

Ans: The problem with above statement is that the selectors is having meta characters and to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").
So the correct syntax is,

$('#myid\\.3').text('blah blah!!!');

Q) How to check data type of any variable in jQuery?

Ans: Using $.type(Object) which returns the built-in JavaScript type for the object.

To convert image into binary using jQuery

<img id="imgBeforeConvert" src="image/download.jpg" />
 //'imgBeforeConvert' image tag contains image which we have to convert into binary.

 <img id="imgAfterConvert"/>
//'imgAfterConvert' image tag is used to display the image after conversion to binary and again convert binary into image.

STEPS:

1) Find the 'imgBeforeConvert' image tag
 var source = document.getElementById("imgBeforeConvert");

2) pass the source variable  to getBase64Image() function:

function getBase64Image(source) {
 var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;

        // Copy the image contents to the canvas
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        // Get the data-URL formatted image
        // Firefox supports PNG and JPEG. You could check img.src to guess the
        // original format, but be aware the using "image/jpg" will re-encode the image.

        var dataURL = canvas.toDataURL("image/png");
        $('#imgAfterConvert').attr("src", dataURL);
        return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    }