Wednesday 27 December 2017

Access Modifiers

Access specifiers are keywords used to specify the declared accessibility of a member or a type.

Why to use access modifiers?
Access modifiers are an integral part of object-oriented programming. They support the concept of encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define who does or doesn't have access to certain features.

All types and type members have an accessibility level, which controls whether they can be used from other code in same assembly or other assemblies.

There are four access modifiers:
  • public
  • protected
  • internal
  • private
The following six accessibility levels can be specified using the access modifiers:
  • public: Access is not restricted.
  • protected: Access is limited to the containing class or types derived from the containing class.
  • internal: Access is limited to the current assembly.
  • protected internal: Access is limited to the current assembly or types derived from the containing class.
  • private: Access is limited to the containing type.
  • private protected: Access is limited to the containing class or types derived from the containing class within the current assembly.


public

The public keyword is an access modifier for types and type members. Public access is the most permissive access level. There are no restrictions on accessing public members.

Accessibility:
  • Can be accessed by objects of the class.
  • Can be accessed by derived classes.
Example:
In the following example, two classes are declared, TestClass and MainClass. The public members x and y of TestClass are accessed directly from MainClass.

Class TestClass
{
       public int x;
       public int y;
}

Class MainClass
{
      static void Main()
      {
           TestClass t = new TestClass();
           t.x = 15;
           t.y = 25;  //Direct access to public members.
           Console.WriteLine("x = {0}, y = {1}", p.x, p.y);
      }
}

Output : x = 15; y = 25;

If you change the public access level to private or protected, you will get the error message: 'TestClass.y' is inaccessible due to its protection level.


protected

A protected member is accessible within its class and by derived class instances.
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.

Accessibility:
  • Cannot be access by object.
  • By derived classes.
Example:
In this example, the class DerivedPoint is derived from Point. Therefore, you can access the protected members of the base class directly from the derived class.

class Point
{
      protected int x;
      protected int y;
}

class DerivedPoint: Point
{
      static void Main()
      {
           DerivedPoint dpoint = new DerivedPoint();
           
           // Direct access to protected members:
           dpoint.x = 15;
           dpoint.y = 25;
           Console.WriteLine("x = {0}, y = {1}", dpoint.x, dpoint.y);

           Point p = new Point();
           p.x = 15; //Error CS1540, because x can only be accessed
                          //by classes derived from Point.
      }
}

Output: x = 15, y = 25

If you change the access levels of x and y to private, the compiler will issue the error messages:

'Point.x' is inaccessible due to its protection level.
'Point.y' is inaccessible due to its protection level.

The statement p.x = 15 generates an error because it is made within the static method Main, and not an instance of class DerivedPoint.

Struct members cannot be protected because the struct cannot be inherited.


private

Private access is the least permissive access level.
Private members are accessible only within the body of the class or the struct in which they are declared.
Nested types in the same body can also access those private members.
It is a compile-time error to reference a private member outside the class or the struct in which it is declared.

Accessibility:
  • Cannot be accessed by object.
  • Cannot be accessed by derived classes.
Example:
In this example, the Employee class contains two private data members, name and salary. As private members, they cannot be accessed except by member methods. Public methods named GetName and Salary are added to allow controlled access to the private members. The name member is accessed by way of a public method, and the salary member is accessed by way of a public read-only property.

class Employee
{
    private string name = "FName, LName";
    private double salary = 200.0;

    public string GetName()
    {
        return name;
    }

    public double Salary
    {
        get { return salary; }
    }
}

class PrivateTest
{
    static void Main()
    {
        Employee e = new Employee();

        // The data members are inaccessible (private), so
        // they can't be accessed like this:
        //    string n = e.name;
        //    double s = e.salary;

        // 'name' is indirectly accessed via method:
        string n = e.GetName();

        // 'salary' is indirectly accessed via property
        double s = e.Salary;
    }
}


internal

The internal keyword is an access modifier for types and type members. We can declare a class as internal or its member as internal. Internal members are accessible only within files in the same assembly (.dll).
In other words, access is limited exclusively to classes defined within the current project assembly.

Accessibility:
In same assembly (public)
  • Can be accessed by objects of the class.
  • Can be accessed by derived classes.

In other assembly (internal)
  • Cannot be accessed by object.
  • Cannot be accessed by derived classes.

A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate by using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.

It is an error to reference a type or a member with internal access outside the assembly within which it was defined.

Example:
This example contains two files, Assembly1.cs and Assembly1_a.cs. The first file contains an internal base class, BaseClass. In the second file, an attempt to instantiate BaseClass will produce an error.

// Assembly1.cs  
// Compile with: /target:library  
internal class BaseClass   
{  
   public static int intM = 0;  
}  


// Assembly1_a.cs  
// Compile with: /reference:Assembly1.dll  
class TestAccess   
{  
   static void Main()   
   {  
      BaseClass myBase = new BaseClass();   // CS0122  
   }  
}  

Example:
In this example, use the same files used in example 1, and change the accessibility level of BaseClass to public. Also change the accessibility level of the member IntM to internal. In this case, you can instantiate the class, but you cannot access the internal member.

// Assembly2.cs  
// Compile with: /target:library  
public class BaseClass   
{  
   internal static int intM = 0;  
}  


// Assembly2_a.cs  
// Compile with: /reference:Assembly1.dll  
public class TestAccess   
{  
   static void Main()   
   {  
      BaseClass myBase = new BaseClass();   // Ok.  
      BaseClass.intM = 444;    // CS0117  
   }  
}  

Saturday 23 December 2017

Nullable Types


  • Nullable types represent value-type variables that can be assigned the value of null.
  • You cannot create a nullable type based on a reference type. (Reference type already support the n ull value.)
  • The syntax T? is shorthand for Nullable<T>, where T is a value type. The two forms are interchangeable.
  • Assign a value to a nullable type just as you would for an ordinary value type.
    eg:- int?X = 10; OR double?D = 4.190.
  • A nullable type can also be assigned the value null.
    eg:- int?X = null.
  • Use the Nullable<T>.GetValueOrDefault method to return either the assigned value, or the default value for the underlying type if the value is null.
    eg:- int?X = 10;
            int J = X.GetValueOrDefault();
  • Use the Hashvalue and Value read-only properties to test for null and retrieve the value.
    eg:- if(X.Hashvalue)J = X.Value;

    - The Hashvalue property returns true if the variable contains a value, or false if it is null.
    - The value property returns a value if one is assigned. Otherwise, a system.InvalidOperationException is thrown.
    - The default value for Hashvalue is false. The value property has no default value.
  • You can also use the '==' and '!=' operators with nullable type.
    eg:- if(X!=null)Y=X;
  • Use the '??' operator to assign a default value that will be applied when a nullable type whose current value is 'null' is assigned to a non-nullable type.
    eg:- int?X = null';
           int Y = X ?? -1;
  • Nested nullable types are not allowed. The following line will not compile:
    Nullable<Nullable<T>>n;

Anonymous Types


  • Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object.
  • The compiler provides a name for each anonymous type, although your application cannot access it.
  • You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type.
  • You cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type.
  • To pass an anonymous type, or a collection that contains anonymous type, as an argument to a method, you can declare the parameter as type object.
  • Two instances of the same anonymous type are equal only if all their properties are equal.
  • anonymous types typically used in the 'Select' clause of a query expression to return a subset of properties from each object in the source sequence.
    eg:- LINQ Query expression.
    var anonymousData = from pl in data select new {pl.Fname, pl.Lname};
  • Anonymous type contain one or more public read-only properties.
  • We can create anonymous types by using 'new' keyword together with the object initializer.
    eg:- var anonymousData = new {Fname="Vivek", Lname="Sharma"};
  • Anonymous type is a way to define read-only properties into a single object without having to define type explicitly.
  • Anonymous type throws compile time errors.

Different type of conversions


  1.  Implicit Conversions:
    - No special syntax is required because the conversion is type safe and no data will be lost.
    - eg: Conversion from smaller to larger integral types, and conversion from derived classes to base classes.
  2.  Explicit Conversions (Casts):
    - Explicit conversion requires a cast operator.
    - Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons.
    - eg: Numeric conversion to a type that has less precision or a small range, and conversion of a base class instance to a derived class.
  3.  User-defined Conversions:
    - Performed by special methods that you can define to enable explicit and implicit conversions between custom types that do not have a base class- derived class relationship.
  4.  Conversion with helper classes:
    - To convert between non-compatible types, such as integers and system datetime objects, or hexadecimal strings and byte arrays, you can use the system.bitconverter class, the system.convert class, and the parse method of the built-in numeric types, such as Int32.Parse.

Monday 2 October 2017

Boxing and Unboxing

Boxing- Implicit conversion of a value type (int, char, etc) to a reference type (object) is known as BOXING.

In boxing process, a value type is being allocated on the heap rather than the stack.


Unboxing- Explicit conversion of reference type (object) to a value type is known as UNBOXING.

In unboxing process, boxed value type is unboxed ffrom the heap and assigned to a value type which is being alloccated on the stack.

example: int stackvar = 15;
                Object boxedvar = stackvar; //Boxing = int is created on the heap (reference type)
                int Unboxed = (int) boxedvar; // Unboxing = boxed int is unboxed from the heap
                                                                 // and assigned to an int stack variable.      

example: int i = 5;
                Arraylist arr = new Arraylist(); 
                // Arraylist contains object type value.
                arr.Add(i);n //Boxing occurs automatically.
                int j = (int) arr[0]; //Unboxing occurs.

Issues with boxing and unboxing:

  • Sometime boxing is necessary, but avoid it if possible, since it slow down the performance and increase memory requirements.
  • Attempting to unbox a null causes a NullreferenceException.
       example:  int? stackvar = null;
                       object boxedvar = stackvar;
                       //NullReferenceException
                        int unboxed = (int) boxedvar;
                       // Object reference not set to an instance of an object.

  • Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.
       example:  int stackvar = 15;
                       object boxedvar = stackvar;
                       // InvalidCastException
                       float unboxed = (float) boxedvar; // Specified cast is not valid;

Difference between Value type and Reference type


Difference between stack and heap memory


Reference Type & Value Type


  • The types are either treated by value type or by reference type.
  • Reference type variables are stored in the heap while value type variables are stored in the stack.
  • A value type holds the data within its own memory allocation and a reference type contains a pointer to another memory location that holds the real data.


Value Type:

  • When you created a value type, a single space in the memory is allocated to store the value and that variable directly holds a value.
  • If you assign it to another variable, the value is copied directly and both variables work independently.
  • Value type can  be created at compile time and stored in stack memory, because of this, garbage collector can't access the stack.
  • All the values are derived implicitly from the System.ValueType.
  • You cannot derive a new type from a value type. However, like reference types, structs can implement interfaces.
  • eg:- int X = 25;
  • Here the value 25 is stored in an area of memory called the stack.
  • When the variable X goes out of scopebecause the method in which it was defined has finished executing, the value is discarded from stack.
  • Using the stack is efficient, but the limited lifetime of value types makes them less suited for sharing data between different classes.
  • Each value type has an implicit default constructor that initialize the default value of that type.
  • Value type cannot contain the null value.
  • The nullable types features does allow for value types to be assigned to null.

Reference Type:

  • Reference types represent the address of the variable rather than the data itself.
  • Assigning a reference variable to another doesn't copy the data. Instead it created a second copy of the reference, which refers to the same location of the heap as the original value.
  • When a reference type variable is no longer used, it can be reclaimed by garbage collector.
  • Reference type is created at run time.
  • eg: Classes, objects, arrays, indexers, interfaces, etc.


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.