Learning Horizon | For Learners

ASP.NET, SQL SERVER, JQUERY,JAVASCRIPT, WEBSPHERE

Showing posts with label Interview Question. Show all posts
Showing posts with label Interview Question. Show all posts

Saturday, 11 February 2017

Difference Between ToString() and Convert.ToString()

This article is about the Difference Between ToString and Convert.ToString Method in C#.

ToString and Convert.ToString Method in C#

Both methods have the ability to convert a value to a string. The main difference between the two methods is that ToString() method can’t handle Null values, so if you use this method, you will experience a Null Reference Exception in your code at some point in time (as shown below Example). On the other hand Convert.ToString() method can handle Null values. So, as a good coding practice and to be on the safe side, experts recommend always use Convert.ToString() method.

We have used below mentioned examples to demonstrate the difference between ToString and Convert.ToString methods.

.ToString() Example:

In C#, if you declare a string variable and do not assign any value to the variable, the variable takes a null value by default. In this case, if you use the ToString() method, the program will raise a null reference exception.


 using System;

namespace DemoToString
{
    public class Program
    {
        static void Main(string[] args)
        {
            Object objStr = null;
            //Below line will throw NullReference Exception
            //Because .ToString() can't handle Null values
            string val = objStr.ToString(); 
            Console.WriteLine(val);
            Console.ReadLine();
        }
    }
}
tostring-and-convert-tostring

When we run the program it will give us null reference exception because the ToString() method in C# expects that the object cannot be NULL when called on it. In our example, the object objStr is Null, and we call ToString() on the NULL object, so it gives a NULL Reference exception.

Convert.ToString() Example:

Let's see what happens when we utilize the Convert.Tostring() method in the above example. Now, after making the changes, run the program, and it should execute correctly. So to put it plainly, the Convert.ToString() method handles null, and the ToString() method does not deal with Null and tosses an exception.


using System;

namespace DemoConvertToString
{
    public class Program
    {
        static void Main(string[] args)
        {
            Object objStr = null;
            //Below line will Return Null Or Blank
            string val = Convert.ToString(objStr);
            Console.WriteLine(val);
            Console.ReadLine();
        }
    }
}

Convert is a static class in the .Net System namespace, and if you noticed that when you write.ToString() It is in a dark blue color(which means that this method is only available in C#) and Convert.ToString() is in light blue color which means it is global and available in other .Net languages as well.

I will go through the difference between object, var, and dynamic keywords through some examples in my next article. Today, I have tried to explain the difference between .tostring and convert.tostring methods. I trust this article will assist you with your requirements. I hope to receive your feedback. Please post your criticism, questions, or remarks on this article.

Friday, 4 September 2015

What Is Chaining In Jquery?

jQuery is an exceptionally incredible framework of JavaScript. With jQuery, we can utilize chaining which intends to chain together different methods in a solitary statement on a single element.

We have been using a solitary statement at once, but now utilizing the chain technique we can bind multiple methods to shorten the code. This way, browsers do not have to look for the same element(s) multiple times.

Advantage of Jquery Method Chaining:

When using chaining technique in jQuery, it means to connect multiple functions to same element/selectors or it allow us to run multiple JQuery functions/commands on same element(s)/selector(s).

Excessive use of selectors will severely slow down your code, because each call to the selector will force the browser to look for it. By combining or "linking" multiple methods, you can greatly reduce the number of times the browser finds the same element without setting any variables. Let's understand the concept with the help of examples.

Implementation of Simple Technique:

    $(document).ready(function () {

            $("#dvDemo").addClass('hor-minimalist-c');
            $("#dvDemo").css('color','red');
            $("#dvDemo").fadeIn('fast');

        });

Implementation of Chaining Technique:

         
$(document).ready(function () {

   $("#dvDemo").addClass('hor-minimalist-c').css('color', 'red').fadeIn('fast');

  });

While chaining, the line of code could turn out to be very long. However, jQuery isn't extremely strict on the syntax structure; you can organize it like you need, including line breaks and spaces.

         
$(document).ready(function () {

   $("#dvDemo").addClass('hor-minimalist-c')
               .css('color', 'red')
               .fadeIn('fast');

  });

Both the codes above will perform same as far as functionality is concerned but the difference is that second code is shorter and faster because we have use chaining concept in it. The first technique has a problem and that is JQuery have to find "dvDemo" three times in the whole DOM and then execute the functions attached to it.

Monday, 22 April 2013

Difference Between Local And Global Temporary Tables

In this tutorial we will learn about local and global temporary tables in MicroSoft Sql Server. Temporary table are very handy when you need to process data or perform calculation using same selection. They are also very useful when you need data temporarily because when client session disconnet they vanishes away. There are two type of temporary tables and below are the details of each type.

Local Temporary Table:-


To create local temporary table we use below statement.

                        create table # temp

Now this table is only visible to connection(same query window) that creates it.And it will be deleted when the connection(query window) will be closed. local temporary tables cannot be shared between multiple users.All temp tables are stored in tempdb database.

Global Temporary Table:-


To create Global temporary table we use below statement.

                        create table ## temp

Now this table is available to all connections and not cleared until unless the last connection is closed. These tables can be shared to multiple users as well and they are also stored in tempdb database.

Thursday, 18 April 2013

Holding document.ready() using jQuery.holdReady() function

Today in this tutorial we will learn about an important function holdReady() of Jquery. I was searching about Jquery on Google and I found it informative for me and I decided it to post this article.

We can hold or release the execution of jQuery’s ready event by using jQuery.holdReady() function.This method should be call before we run ready event.To delay the ready event, we need to call jQuery.holdReady(true);

Whenever we want to release the ready event then we need to call jQuery.holdReady(false);

UseFull Scenario:-


Whenever we want to load any Jquery plugins before the execution of ready event.

Example : -


$.holdReady(true);

$.getScript("abcplugin.js", function() {

$.holdReady(false);

});

Hope it will be informative and helpfull for you.

Sunday, 10 March 2013

Difference Between Inline, Embedded and External CSS

What is CSS:

CSS is the abbreviation of a cascading style sheet and is used to represent (to make beautiful) the HTML document. It is known as cascading because whenever we apply one or more styles to any HTML element, CSS will follow a rule according to which the most specific style declaration got the priority. I've explained the difference between inline, embedded, and external CSS in this post, so please read till the end and perform some practice to get a better understanding of the concept. In this way, you can use the idea when presenting your HTML documents.

Types of CSS?

There are three types of CSS that are known as:

  1. Inline CSS
  2. Embedded or Internal CSS
  3. External CSS

Let me describe all the three types one by one with examples for each of them.

Inline CSS:

When we need to apply styles to a small section of HTML elements, we can use inline CSS. To apply inline styles, use the style attribute in the relevant HTML markup/tag, which contains any property. In the example below, I used the "margin-left" and "color" attributes to apply styles on the paragraph tag.

Inline Style Example:

Inline styles are written inside the "style" attribute of the respective tag.

<p style="margin-left:25px;color:blue;">This is my first paragraph</p>

Advantages of Inline Style:

  • Inline Style: has a high priority among these three styles, which is the main advantage.
  • Single HTML document: When you add the CSS code in the same HTML document you don't need to upload multiple files on the server.
  • Lower HTTP Requests: When you use Inline Style all the code will be in a single HTML document which mean lower HTTP requests and ultimately your website will load faster than External CSS
  • It is recommended to use Inline Style on small (1 to 5 pages) websites or blogs because there is a limited number of pages. It will help service providers as well as users.

Disadvantages of Inline Syle:

  • It is a time-consuming task because you add inline style rules to every HTML element which makes your HTML document structure dirty. For example, If you want all your headings(h1) to have font size "20" you have to add an inline style to each <h1> tag in your document.
  • In terms of performance, using Inline CSS styles does not seem to be a very persuasive approach because all of your CSS code is in the same HTML document which increases the page size and ultimately leads to increase load time as well.

Embedded or Internal CSS:

In embedded or internal style sheet we put all our style declarations in the head section of the HTML document/page. To do this we have to wrap our style declaration in between the <style> and </style> tag in the head of the HTML document/page.

Internal CSS Example:

Internal styles are written in "style" tag, within the "head" section of an HTML document.

<head>

   <style type="text/css">

    div{margin-top:20px;}
    p{margin-left:10px;}

   </style>

</head>

Advantages of Internal CSS:

  • Internal style saves time because If you want all your headings (h1) to have the font size of “20” you have to add an Inline style <h1> tag in the Internal Style Sheet.
  • Because you only need to add the CSS code to the same HTML file, there is no need to upload multiple files which also saves your time.
  • Because style information is in the same HTML file, we have fewer HTTP requests.

Disadvantages of Internal CSS:

  • When you add CSS code to the same HTML document it will increase the page size and load time.

When we need to add a unique style to a single HTML document, we usually use embedded or internal style sheet.

External CSS:

When we put all style declarations in a separate file and save them with a .css extension, it is called external style sheet or external css. To make an external style sheet, open Notepad, Save it with the name something.css, and boom. Now to use external style sheet on your web page, you need to link it with your web page. To do this, use the <link> tag in the header of an HTML document or web page. E.g

External or Linked CSS Example:

External styles are written in a separate file, and then you can link inside the head element of the HTML document. You can write the external style sheet in any text editor such as notepad or notepad ++ and after that saved with the .css extension.

<head>

    <link rel="stylesheet" type="text/css" href="something.css">

</head>

Advantages of External CSS:

  • Clean Code: Your HTML document structure is clean because all of your CSS code is in a separate .css file.
  • Reduced Document Size: By including CSS styles for text in a separate file, you can significantly reduce the file size of the page. Moreover, the ratio of content to code is much greater than that of simple HTML pages, thus making the page structure easier to read for programmers and search engine spiders.
  • High Search Engine Ranking: In SEO, the use of external CSS is very important. In SEO, everyone knows that content is king, not the amount of code on the page. Search engine spiders can index your pages faster because important information can be placed higher in the HTML document. Likewise, the amount of related content will be greater than the amount of code on the page. Search engines don’t have to spend too much time in the code to find the real content. You actually provide it to the spider "on the plate" which ultimately helps in getting a higher ranking in search engines.
  • Change Whole Website Appearance: It is ideal when many web pages need the same style. Using this method, you only need to change one file to change the overall appearance of the website.

Disadvantages of External CSS:

  • In case, you are linking your HTML document with multiple CSS files it can increase your website's load time.
  • Before the external CSS is loaded, the page may not render correctly.

I hope after reading this article everyone understands the idea and purpose of using external and internal styles. Please do write in the comment box if you have any questions related to all three styles. i.e., inline, embedded, and external styles.

Monday, 4 February 2013

Difference Between setTimeout() And setInterval() Functions

Today, we will discuss the difference between setTimeout and setInterval functions, because my friend used these functions in his project and asked me about these functions and their purpose, so I decided to write the basics.

setTimeout():-

setTimout() is a function that takes two parameters.

  • Javascript code/statement to execute
  • Time in milliseconds

When we use setTimout() the JavaScript code or statement (which we specified as the first parameter) runs only once after the specified time (mentioned as the second parameter).

Code Example:-

 function Hello(){

               alert("Hi, How are you?????");

 }

<input type="button" id="btnSubmit" value="Click Me!!!" onclick="setTimout('Hello()',500)" />

In this example, clicking the button will call Hello() function after 5 milliseconds.

setInterval():-

setInterval() is a function that takes two parameters as well.

  • Javascript code/statement to execute
  • Time in milliseconds

The difference between the two lies here that when we use setInterval() the JavaScript code(which we specified as the first parameter) executes repeatedly after the specified time interval.

Code Example:-

  function Hello(){

            alert("Hi, How are you?????");

   }

<input type="button" id="btnSubmit" value="Click Me!!!" onclick="setInterval('Hello()',500)" />

In this example, we use setInterval() so you will see that Hello() function will call repeatedly after every 5 milliseconds.

Thursday, 13 September 2012

ALTER Statements in SQL Server

Today we will learn about the SQL alter statements and look into scenarios in which we can use them and how.So here we go


To create table use the following.

    CREATE TABLE [dbo].[person](

      [PERSON_ID] [varchar](20) NOT NULL,

      [PERSON_NAME] [varchar](15) NULL,

      [PERSON_ADDRESS] [varchar](20) NULL,

      [Department] [varchar](20) NULL
)


To change the table name and column name, use the following:

 1.                    -- To change table name

 sp_rename 'person_table','person'

 2.                    -- To change column name

 sp_rename 'person.designation','Department','column' 

 

To alter tables use the following queries:

3.                    -- To Add a column

 alter table person

 add Designation varchar(20)

4.                    -- To Drop a column

 alter table person

 drop column designation 

5.                    -- To change data type of column

 alter table person

 alter column person_id int 

6.                   -- To Add primary key constraint

 alter table person

 add constraint pk_person_id primary key(person_id)

7.                    -- To Drop primary key constraint

 alter table person

 drop constraint pk_person_id

8.                    -- To Add foreign key constraint

 alter table person

 add constraint fk_person_id foreign key(person_id) references department(person_id)

9.                    -- To Drop foreign key constraint

 alter table person

drop constraint fk_person_id

Wednesday, 29 August 2012

Difference Between DataAdapter And DataReader

A significant number of programmers have been using DataAdapter and DataReader, but most of them don't have time or they don't pay attention to the distinction between them. Today in this article, we will examine the primary difference between a DataAdapter and a DataReader.

DataAdapter:

The DataAdapter object works as a two-way bridge among the data source and the DataSet object. DataSet is a disconnected data container, and the adapter is responsible for filling data and submitting its data back to a specific data source. From an abstract point of view, a dataadapter is similar to a command/query and represents another way of executing commands against a data source. The biggest difference between commands and data adapters is how they return the retrieved data. The dataadapter accesses the data to obtain the data and packs it into an in-memory container (DataSet or DataTable). The important point about the data adapter is that it is a two-way channel used to read data from the data source to the memory table and write the data in the memory back to the data source.

In Simple Words:

We can read multiple lines. It is the bridge between the database and the DataSet.

It is not always connected to the database. This is a multi-purpose method, we can (read from the database, update to the database)

DataReader:

The DataReader is also used to obtain data from the data source. By using the datareader object, we can read one row at a time. It is the first choice when you need direct data access because it uses a real-time connection. And due to the nature of optimization, its retrieval speed is fast and the performance is the best as compare to DataSet.

Like other ADO.NET objects, each data provider has a datareader class. OleDbDataReader is the datareader class of the OleDb data provider. SqlDataReader and ODBC DataReader are also data reader classes for SQL and ODBC data providers.

The datareader object can only be used to read data forward. When using a datareader object, make sure to open the connection first, and then close the data reader and connection after reading all records. Normally developers use ExecuteReader object to bind data with datareader. Below is the example:

Example:


  Public void BindGridView() {  
    using(SqlConnection conn = new SqlConnection("Data Source=XYZ;Integrated Security=true;Initial Catalog=DemoDB")) {  
        con.Open();  
        string qry = "Select UserName, First Name,LastName FROM Users";
        SqlCommand cmd = new SqlCommand(qry, conn);  
        SqlDataReader sdr = cmd.ExecuteReader();  
        GridViewUser.DataSource = sdr;  
        GridViewUser.DataBind();  
        conn.Close();  
    }  
}
 

In Simple words:

We can read a single row. It uses a live connection. It is read-only and forward only.

I hope that after reading this article, you have understood the difference between DataAdapter and DataReader. In case there is something missing in the article, please do write us in the comment section.

Thursday, 23 August 2012

Difference Between Delete, Drop, Truncate | SQL Server

Today we will learn the difference between Delete, Drop, and Truncate commands.

DELETE:

Delete is a DML command and is used to remove tuples/rows/records from a table (the structure of the table exists in the database, and only records remove from the table). We can remove one or multiple rows from a table by using the where clause because Delete is a DML (Data Manipulation Language) command so, it can be ROLLBACK as well.

Example:-

Delete from person It will delete all rows/records from a table named person
Delete from person where name='Amir' It will delete all those rows/records where the name filed contains Amir.

DROP:

Drop command is used to remove/drop table from the database (the structure of the table will be removed with records as well). Drop command cannot be ROLLBACK.

Example:-

Drop table person.

TRUNCATE:

Truncate command also remove/delete rows/records from a database table (structure will exist in the database and only records will be removed). It is much faster than a DELETE command. Also, this command cannot be ROLLBACK.

Example:-

Truncate table person.

Note: - Truncate and Drop are DDL commands but Delete is a DML command. That is the reason Delete operation can be ROLLBACK but Drop and Truncate cannot.

Wednesday, 8 August 2012

Difference between document.ready and window.onload

Today, we will become familiar with both document ready event of Jquery and the window onload event of JavaScript. Secondly, we will discuss the difference between document ready and window onload events because both events are often confusing. Using one event rather than the other can cause such problems inside the code, which may be tough to trace sometimes because of the elusive difference.

Also the difference between jQuery ready event and JavaScript onload event is one of the favorite questions of interviewers. They asked both beginners and experienced web developers.

Document.ready() or Jquery.ready():

document.ready() is JQuery event.
The Jquery ready event is called once after the DOM(Document object model) is loaded. DOM means the entire HTML page or all the HTML tags/script i.e. (div tag, table tag, paragraph tags, anchor tags etc etc.). It will not wait for the image or video to get load. It means that it is the earliest stage in the page loading process.

The document.ready() method executes when the ready event is fired. Below is the syntax to write it.

Example: -


	$(document).ready(function() {
	 // executes when HTML-Document
	 //is loaded and DOM is ready
	 alert("document is ready to perform operation");
	});
    
document-ready-event

The ready() method does have an argument which is a callback function. You can write your code inside this callback function that will execute when DOM will finish loading. The following is the short form of the above code.

    
     $(function () {
  	  //place your code here
     });

Window.onload():

window.onload() is a JavaScript event.
The window load event is called when all the content (including the DOM and images) on the website page or document is loaded. It will wait for all the DOM elements ( HTML tags, for example, paragraph tags, div tags, h1, anchor tags) as well as content and all other dependent resources like images, stylesheets, videos, scripts.

Example: -

Suppose a large image on your web page window.onload() will wait for that image to finish its load. The execution will be slow when we use the window.onload() function, but it will be fast in the case of the document.ready() because it will not wait for the image to load completely.

 
	$(window).load(function() {
	  // Executes when complete page is 
       //fully loaded, including frames,
       //objects and images
	alert("window is loaded to perform operations");
	});
    

Major Differences:

  1. The difference between document ready event and window onload event is we can have more than one document ready event handler in a web page but only one onload event handler. In this case, the browser will invoke document ready events in the order they are written in the document.
  2. Because the document ready is a Jquery event, it is only available in the Jquery library, and the window onload is a JavaScript event. It is available in all most all browsers and libraries by default, so we don’t have to include any file to use it.
  3. In most of the cases document ready event trigger before window onload event but sometimes when there is no heavy content to load and no browser delay, the window onload even get fire at the same time as document ready event.
  4. As the definition says window onload event will wait for the content (image or videos to load) but if the image or videos are heavy and takes time to load, the window onload will wait for loading. The longer wait will result in a bad user experience.

I hope you understand the difference between document.ready and window.onload events/functions. I strongly recommend using the Jquery ready handler for all practical purposes. Unless you are dealing with DOM content, such as the size of the image (which may not be available) when the ready event is triggered. Jquery ready can also handle browser compatibility instead of window loading, although it is a standard browser quirk and adjustment. By the way, if you know any other difference between the Jquery document ready and window onload event (not included in this article), please feel free to write us in the comments section below.

Sunday, 5 August 2012

Difference Between val(),html() And text() | Jquery Functions

Today we will be learning about jquery functions, their difference, and how they work so you can use them when they are required.

val():-

Val() function returns the value of controls or also you can set the value of the selected element.

Example # 1:-

<input type="text" id="firstName" name="firstTxt" value="" />
<input type="button" id="firstButton" name="submitButton" value="Submit"/>
 
<script type="text/javascript">
 
        $(document).ready(function(){
        $("#firstButton").click(function(){
             var name =$("#firstName").val();
                alert(name);
        });
});
 
</script>

So you see in the above example when you enter some value in the text box and click the “Submit” button you will get the value of that text box.

Example # 2:-

<select id="country">
<option >England</option>
<option >Pakistan</option>
<option >India</option>
</select>
<input type="button" id="firstButton" name="submitButton" value="Submit"/>
 
<script type="text/javascript">
 
    $(document).ready(function(){
        $("#firstButton").click(function(){
             var countryName=$("#country").val();
                alert(countryName);
    });
});
 
</script>
val-function-example

And in this example also, with the help of the jquery val() function, you will get the selected value from the dropdown list.

html():-

It will give you the entire content inside a specific HTML element. It is only used in HTML documents.

Example # 1:-

<div id="testDiv">
<p>Cricket</p>
<p>Hockey</p>
<p>Football</p>
</div>
<input type="button" id="firstButton" name="submitButton" value="Submit"/>
 
<script type="text/javascript">
     
$(document).ready(function(){    
     $("#firstButton").click(function(){
        var content=$("#testDiv").html();
        alert(content);
    });
});
 
</script>
html-function-example

In the above example, html() returns the inner content of the DIV element having an id=”testDiv”.

text():-

It will give you the text inside an HTML element. It can be used in XML as well as in HTML documents. Let’s have an example to explain this.

Example # 1:-

<div id="testDiv">
<p>Cricket</p>
<p>Hockey</p>
<p>Football</p>
</div>
<input type="button" id="firstButton" name="submitButton" value="Submit"/>
 
<script type="text/javascript">
 
    $(document).ready(function(){
         $("#firstButton").click(function(){
                var content=$("#testDiv").text();
                 alert(content);
        });
});
 
</script>

In this example text() will give the text content that is written inside the html elements.

Hope you guys understand the difference between val(), html(), and text() functions. Best of Luck.