Wednesday, 9 December 2015

What is difference between Temp Table and Hash Table in SQL?

        The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very quick searches can be made for values by searching through their keys.

        Temporary tables are a useful tool in SQL Server provided to allow for short term use of data. There are two types of temporary table in SQL Server,

  • Local temporary table
  • Global temporary table

        Local temporary tables are only available to the current connection to the database for the current user and are dropped when the connection is closed. Global temporary tables are available to any connection once created, and are dropped when the last connection using it is closed.

        Both types of temporary tables are created in the system database tempdb.

What are Cursors?

What are Cursors?

          A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor contains information on a select statement and the rows of data accessed by it.
          This temporary work area is used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process only one row at a time. The set of rows the cursor holds is called the active set.

There are two types of cursors in PL/SQL:

  •      Implicit cursors:

          These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements are executed. They are also created when a SELECT statement that returns just one row is executed. 

  •     Explicit cursors:

          They must be created when you are executing a SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row the current row position moves to next row.

            Both implicit and explicit cursors have the same functionality, but they differ in the way they are accessed.

What is the difference between convert.ToInt32 and int32.Parse ?

string convertToInt = "78";
string nullString = null;
string maxValue = "93333332222222224444442222222222";
string formatException = "99.99";

int ParseResult;

Int32.Parsh(String Str)
Convert.ToInt32(String Str)
Int32.Parse(str) method converts the string representation of a number to integer 32 bit.
Exe.
// It will perfectly convert interger
parseResult= int.Parse(convertToInt);

Convert.ToInt32(str) method converts the string representation of a number to integer 32 bit.
Exe.
//It will perfectly convert integer
parseResult= Convert.ToInt32(convertToInt);

when str is a null reference it will throw ArgumentNullException.
Exe.
// It will raise Argument Null Exception
parseResult= int.Parse(nullString);

when str is a null reference it will return 0 rather than throw ArgumentNullException.
Exe.
//It will ouput as 0 if Null string is there
parseResult= Convert.ToInt32(nullString);

if str is other than integer value it will throw FormatException.
Exe.
//It will raise Format Exception
parseResult= int.Parse(formatException);

if str is other than integer value it will throw FormatException.
Exe.
//It will raise Format Exception
parseResult= Convert.ToInt32(formatException);

when str represents a number less than MinValue or greater than MaxValue it will throw OverflowException.
Exe.
//It willl raise Over Flow Exception
parseResult= int.Parse(maxValue);

when str represents a number less than MinValue or greater than MaxValue it will throw OverflowException.
Exe.
//It will raise Over Flow Exception
parseResult= Convert.ToInt32(maxValue);


What is the DOM in Javascript/jquery ?

          The DOM is basically an API you use to interface the document with, and is available in many languages as a library ( JS is one of those languages ). The browser converts all the HTML in your web page to a tree based on the nesting. Pop open Firebug and look at the HTML structure. That is the tree I'm talking about.

If you want to change any HTML you can interact with the DOM API in order to do so.

<html>
 <head><script src="Tempfile.js"></script></head>
 <body>blah</body>
</html>
In Tempfile.js I can reference the body using:

onload = function() {
    document.getElementsByTagName('body')[0].style.display='none';
}
The getElementsByTagName is a method of the document object. I am manipulating the body element, which is a DOM element. If I wanted to traverse and find say, a span I can do this:

onload = function() {
 var els = document.getElementsByTagName('*');
 for ( var i = els.length; i--; ) {
    if ( els[i].nodeType == 1 && els[i].nodeName.toLowerCase() == 'span' ) {
       alert( els[i] )
    }
 }
}
I am traversing the nodeList given back by getElementsByTagName in the snippet above, and looking for a span based on the nodeName property.

what is lambda expression in linq c#?

          The term of ‘Lambda expression’ has derived its name from ‘lambda’ calculus which in turn is a mathematical notation applied for defining functions.
          Lambda expressions as a LINQ equation’s executable part translate logic in a way at run time so it can pass on to the data source conveniently.
         However, lambda expressions are not just limited to find application in LINQ only.

These expressions are expressed by the following syntax:

         (input parameters) => expression or statement block

         Below is an example of lambda expression

          y => y * y

         The above expression specifies a parameter named y and that value of y is squared. However, it is not possible to execute a lambda expression in this form. Example of a lambda expression in C# is shown below.

Example:

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

namespace LambdaExa
{
  class Program
  {
     delegate int del(int i);
     static void Main(string[] args)
     {
        del myDelegate = y => y * y;
        int j = myDelegate(5);
        Console.WriteLine(j);
        Console.ReadLine();
     }
  }
}

Wednesday, 28 October 2015

Difference between Delete and Truncate in SQL?

Delete
Truncate
Delete is DML (Data Manipulation Language) command.
Truncate is DDL (data Definition Language) command.
Delete statement is executed using a row lock.
Truncate table always lock the table and page but not each row.
We can specify in where clause.
We cannot specify in where clause.
It delete specified data if where condition exists.
It deletes all the data of table.
Delete activates a trigger because the operation is logged individually.
Truncate cannot activate a trigger because operation does not log individually row delete.
Rollback is possible in Delete.
Rollback is not possible in Truncate.
Slower then Truncate because it keep log.
Faster in performance, Don’t keep logs.

Difference between Primary Key and Unique key in SQL?

Primary key
Unique key
Primary key cannot have NULL value.
Unique key may have a NULL value.
Each table can have only one primary key.
Each table can have more than one unique key.
By default primary key is clustered index.
By default unique key is Non- clustered index.
Primary key can be related with another table’s as a Foreign Key.
Unique key cannot be related with another table’s as a Foreign Key.
We can generate ID automatically with the help of auto increment field.
Unique key is not support auto increment field.

Difference between Union and Union ALL in SQL?

Union
Union ALL
Union only selects distinct values.
Union all select all values in the table.
Union removes duplicate rows.
Union all doesn’t removes duplicate rows.
Output is in sorted order so that it is faster.
Output is not sorted order.

Difference between Where and Having clause?

WHERE
HAVING
Where can be used other then select statement also.
Having is used only with the select statement.
Where applies to each and every single row.
Having applies to summarized rows (with using Group By).
In where clause the data that fetched from memory according to condition.
In having, The completed data firstly fetched and then separated according to condition.
Where is use before group by.
Having is used to impose condition on group by function and use.

How to Find the last inserted record without using MAX / Top clause in SQL( Query).

1 : -
        Select *  From TABLENAME  Where  ID = IDENT_CURRENT('TABLENAME')

2 : -
        Set Rowcount 1
        Select * from TABLENAME   order by ID desc


Monday, 26 October 2015

How to find second highest salary using Ranking Function (DENSE_RANK()) in SQL?


Table Name : SalaryDetails

IDSalary
11000
2500
3750
4500
5350
6750

SELECT a.Name,a.salary
FROM  (   SELECT Name,salary,DENSE_RANK() over (ORDER BY salary desc) AS Rank FROM salaryDetails  )  as a where Rank = 2 

How to find second highest salary in SQL using MAX?


Table Name : SalaryDetails

IDSalary
11000
2500
3750
4500
5350
6750

                Select max(salary) as salary from salaryDetails where salary not in (select top (1) salary from salaryDetails order by salary desc)

Monday, 24 August 2015

Write a query to diplay product name whose assign many employee in product table.

Table Name: Emp

EmpIdName
1Sagar
2Raj
3Mohan
4Anand
5Tiku

Table Name:  Product

ProductIdEmpIdProductName
11Product1
21Product2
32Product3
43Product4
55Product5
63Product6

select pp.proname,pp.proid,pp.empid from
(
select t.aaa,empid from
(
select count(proid)as aaa,empid  from product as p group by p.empid
) as t where t.aaa >= 2
) as t2 left join product as pp on t2.empid = pp.empid

Write a query to display employee name whose not assign any product table.

Table Name: Emp

EmpIdName
1Sagar
2Raj
3Mohan
4Anand
5Tiku

Table Name:  Product

ProductIdEmpIdProductName
11Product1
21Product2
32Product3
43Product4
55Product5



SELECT Empid, name FROM Emp e
WHERE NOT EXISTS
(
         SELECT * FROM Product AS p WHERE p.empid = e.empid
)

How to find second highest salary in SQL using TOP?


Table Name : SalaryDetails

IDSalary
11000
2500
3750
4500
5350
6750

SELECT TOP 1 salary FROM
(
             SELECT DISTINCT TOP 2 salary FROM SalaryDetails ORDER BY salary DESC
) a
ORDER BY salary asc

Wednesday, 19 August 2015

Difference between get and post method.


GET (HTTP)

POST (HTTP)

HistoryParameters remain in browser history because they are part of the URLParameters are not saved in browser history.
BookmarkedCan be bookmarked.Can not be bookmarked.
BACK button/re-submit behaviourGET requests are re-executed but may not be re-submitted to server if the HTML is stored in the browser cache.The browser usually alerts the user that data will need to be re-submitted.
Encoding type (enctype attribute)application/x-www-form-urlencodedmultipart/form-data or application/x-www-form-urlencoded Use multipart encoding for binary data.
Parameterscan send but the parameter data is limited to what we can stuff into the request line (URL). Safest to use less than 2K of parameters, some servers handle up to 64KCan send parameters, including uploading files, to the server.
HackedEasier to hack for script kiddiesMore difficult to hack
Restrictions on form data typeYes, only ASCII characters allowed.No restrictions. Binary data is also allowed.
SecurityGET is less secure compared to POST because data sent is part of the URL. So it's saved in browser history and server logs in plaintext.POST is a little safer than GET because the parameters are not stored in browser history or inweb server logs.
Restrictions on form data lengthYes, since form data is in the URL and URL length is restricted. A safe URL length limit is often 2048 characters but varies by browser and web server.No restrictions
UsabilityGET method should not be used when sending passwords or other sensitive information.POST method used when sending passwords or other sensitive information.
VisibilityGET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send.POST method variables are not displayed in the URL.
CachedCan be cachedNot cached

Monday, 27 July 2015

What is Helper class in MVC?

                HTML Helper is just a method that returns a HTML string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input>, <button> and <img> tags etc. You can also create your own HTML Helpers to render more complex content such as a menu strip or an HTML table for displaying database data.

Differentiation SingleOrDefault() vs FirstOrDefault() in MVC

Single() SingleOrDefault() First() FirstOrDefault()
Description Returns a single, specific element of a sequence Returns a single, specific element of a sequence, or a default value if that element is not found Returns the first element of a sequence Returns the first element of a sequence, or a default value if no element is found
Exception thrown when There are 0 or more than 1 elements in the result There is more than one element in the result There are no elements in the result Only if the source is null (they all do this)
When to use If exactly 1 element is expected; not 0 or more than 1 When 0 or 1 elements are expected When more than 1 element is expected and you want only the first When more than 1 element is expected and you want only the first. Also it is ok for the result to be empty

List of Global.asax events in mvc.

protected void Application_Start(object sender, EventArgs e)
       {

       }

protected void Session_Start(object sender, EventArgs e)
        {

        }

protected void Application_BeginRequest(object sender, EventArgs e)
        {
        }

protected void Application_AuthenticateRequest(object sender,EventArgs e)
        {

        }

protected void Application_Error(object sender, EventArgs e)
        {

        }

protected void Session_End(object sender, EventArgs e)
        {

        }

protected void Application_End(object sender, EventArgs e)
        {

        }

protected void Application_Start()
        {
            
        }

How many web.config files can have in a web application(Project)..??

You may have multiple Web.Config files in one Asp.Net Application, but only One Per Folder.

Wednesday, 1 July 2015

What are the different types of Results in MVC (.Net)?

There are 11 different response types which can be sent to the end user :-

  1. ViewResult - Renders a specified view to the response stream
  2. PartialViewResult - Renders a specified partial view to the response stream
  3. EmptyResult - An empty response is returned
  4. RedirectResult - Performs an HTTP redirection to a specified URL
  5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  6. JsonResult - Serializes a given object to JSON format
  7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  8. ContentResult - Writes content to the response stream without requiring a view
  9. FileContentResult - Returns a file to the client
  10. FileStreamResult - Returns a file to the client, which is provided by a Stream
  11. FilePathResult - Returns a file to the client


Example:-

1. View Result: - 
              public ActionResult Home()
             {
                   return View();
              }
2. Partial View Result :-
            Public ActionResult AboutUs()
            {
                 return PartialView("Hi");
             }
3. Json Result :-
            Public ActionResult Home()
            {
                 return Json("hello from JSON");
            }

Tuesday, 30 June 2015

How can we restrict MVC (.Net) actions using GET or POST?

                    We can decorate the MVC action with the HttpGet or HttpPost attribute to restrict the type of HTTP calls.

                    For example you can see in the below code snippet the Home action can only be invoked by HttpGet. If we try to make HTTP POST on Home, it will throw an error.

//GET

      [HttpGet]
      public ActionResult Home()
     {
    
           return View();
      }

//POST

      [HttpPost]
      public ActionResult Home(Int Id)
     {
    
          return View(Id);
      }

What is routing in MVC (.Net)?

Routing helps you to define a URL structure and map the URL with the controller.

         For instance lets take one example. My Controller name is Static and Method name is Whoweare. So we want to display in URL like "http://localhost/Static/who-we-are/", Below is the code that you show of how to map that URL with controller and action.

routes.MapRoute(
               name: "Whoweare",
               url: "who-we-are",
               defaults: new { controller = "Static", action = "Whoweare", id = UrlParameter.Optional }
           );

What are HTML helpers in MVC (.Net)?

           
               HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view , below is the HTML helper code.

                                            "   <%= Html.TextBox("UserName") %>   "

                                            "   <%= Html.CheckBox("UserName") %> "

What are the benefits of using MVC (.Net)?

Benefits of using Model View Controller:

                  1. Separation of concerns is achieved as we are moving the code-behind to a separate class file. By moving the binding code to a separate class file we can reuse the code to a great extent.

                  2. Automated UI testing is possible because now the behind code has moved to a simple .NET class. This gives us opportunity to write unit tests and automate manual testing.

What is MVC in .Net?

             
                    MVC is an architectural pattern which separates the representation and user interaction. It is divided into three sections, Model, View, and Controller. 


  1. The View is responsible for the look and feel.
  2. Model represents the real world object and provides data to the View.
  3. The Controller is responsible for taking the end user request and loading the appropriate Model and View.