Tuesday 30 June 2015

Exceptions in DotNet

control gridview of type 'gridview' must be placed inside a form tag with runat=server

You are calling GridView.RenderControl(htmlTextWriter), hence the page raises an exception that a Server-Control was rendered outside of a Form.
You could avoid this execption by overriding VerifyRenderingInServerForm
public override void VerifyRenderingInServerForm(Control control)
{
  /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
     server control at run time. */
}


IFSC Code Validation using JavaScript in Asp.net

function AllowIFSC() {
            var ifsc = document.getElementById('<%=txtifsccode.ClientID%>').value;
            var reg = /[A-Z|a-z]{4}[0][a-zA-Z0-9]{6}$/;

            if (ifsc.match(reg)) {
                return true;
            }
            else {
                alert("You Entered Wrong IFSC Code \n\n ------ or------ \n\n IFSC code should be count 11 \n\n-> Starting 4 should be only alphabets[A-Z] \n\n-> Remaining 7 should be accepting only alphanumeric");
                document.getElementById("<%=txtifsccode.ClientID%>").focus();
                return false;
            }

        }

<asp:TextBox ID="txtifsccode" runat="server" onblur="return AllowIFSC();"  MaxLength="11" Width="200" Style='text-transform: uppercase'></asp:TextBox>
                                    

Saturday 27 June 2015

ADO dotNet Interview Questions

how to update database using DataSet in c#
 Read: More

Difference Between DataReader, DataSet, DataAdapter and DataTable in C#


DataReader
DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database. DataReader will fetch the data very fast when compared with dataset. Generally we will use ExecuteReader object to bind data to datareader.
To bind DataReader data to GridView we need to write the code like as shown below:
Protected void BindGridview()
{
using (SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
gvUserInfo.DataSource = sdr;
gvUserInfo.DataBind();
conn.Close();
}
}
  • Holds the connection open until you are finished (don't forget to close it!).
  • Can typically only be iterated over once
  • Is not as useful for updating back to the database
DataSet
DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.
protected void BindGridview()
{
    SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
DataAdapter
DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. Check below sample code to see how to use DataAdapter in code:
protected void BindGridview()
{
    SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
    conn.Open();
    SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    gvUserInfo.DataSource = ds;
    gvUserInfo.DataBind();
}
  • Lets you close the connection as soon it's done loading data, and may even close it for you automatically
  • All of the results are available in memory
  • You can iterate over it as many times as you need, or even look up a specific record by index
  • Has some built-in faculties for updating back to the database.
DataTable 
DataTable represents a single table in the database. It has rows and columns. There is no much difference between dataset and datatable, dataset is simply the collection of datatables.
protected void BindGridview()
{
     SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");
     conn.Open();
     SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
     SqlDataAdapter sda = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
     da.Fill(dt);
     gridview1.DataSource = dt;
     gvidview1.DataBind();
}
References: More

WCF Interview Quetions

In single wcf service, can we use multiple interfaces are possible ? How.
With WCF, you can:
  • have one service implementation class that implements multiple service interfaces
  • have one service implementation class exposed through multiple endpoints, e.g. one service endpoint using BasicHttpBinding for maximum interoperability and another endpoint using NetTcpBinding for maximum performance (with WCF clients).
EX: More

Wednesday 24 June 2015

Self Join with an example in sql server

There are 3 different types of joins available in sql server, and they are
1. Cross Join 
2. Inner Join or Join 
3. Outer Join

Outer Join is again divided into 3 types as shown below.
1. Left Outer Join or Left Join 
2. Right Outer Join or Right Join 
3. Full Outer Join or Full Join 

Self join means joining a table with itself. We can have an inner self join or outer self join


We use Self Join, if we have a table that references itself. For example, In the Employee Table below MANAGERID column references EMPLOYEEID column. So the table is said to referencing itself. This is the right scenario where we can use Self Join. Now I want to write a query that will give me the list of all Employee Names and their respective Manager Names. In order to achieve this I can use Self Join. In the Table below,Raj is the manager for Pete,Prasad and Ben. Ravi is the manager for Raj and Mary. Ravi does not have a manager as he is the president of the Company.The query below is an example of Self Join. Both E1 and E2 refer to the same Employee Table. In this query we are joining the Employee Table with itself. 

SELECT E1.[NAME],E2.[NAME] AS [MANAGER NAME]
FROM EMPLOYEE E1 
INNER JOIN EMPLOYEE E2 
ON E2.EMPLOYEEID =E1.MANAGERID

If we run the above query we only get 5 rows out of the 6 rows as shown below.

Inner Self Join


If we want to get all the rows then we can use LEFT OUTER JOIN as shown below.
SELECT E1.[NAME],E2.[NAME] AS [MANAGER NAME]
FROM EMPLOYEE E1 
LEFT OUTER JOIN EMPLOYEE E2 
ON E2.EMPLOYEEID =E1.MANAGERID
Left Outer Self Join

Let us now slightly modify the above query using COALESCESELECT E1.[NAME],COALESCE(E2.[NAME],'No Manager'AS [MANAGER NAME]
FROM EMPLOYEE E1 
LEFT JOIN EMPLOYEE E2 
ON E2.EMPLOYEEID =E1.MANAGERID

If we execute the above query the output will be as shown in the image below. This is how COALESCE can be used.

Left Outer Self Join with COALESCE

Tuesday 23 June 2015

Ajax Interview Questions

Is Ajax considered client or server-side scripting?

Ajax ( short for asynchronous JavaScript and XML) is a group of interrelated Web development techniques used on the client-side to create asynchronous Web applications

With Ajax, web applications can send data to and retrieve from a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object

If you are talking about ASP.NET AJAX , its both client side and server side. There is client side asp.net ajax framework that gets loaded in the browser with the help of .axd files and there is server side framework that receives the request, process it and sends the response back to the client/browser. 

If you are talking about just jQuery or JavaScript ajax , it's pure client side technology that let us send the request to the server without sending the entire page on the server.  

Friday 19 June 2015

SQL Server Interview Questions

How to RESET identity columns in SQL Server

One way is...
truncate table [table_name]
-- for example
truncate table product
But the truncate command fails to delete the data if there is a relationship given to the table and the identity column is not reset.

The other way is...
In this case, first you need to delete data from the child and the master table.
After deleting data, fire this command and it will reset your identity column to 0.

DBCC CHECKIDENT('[table_name]', RESEED, [new_reseed_value])
-- for example


DBCC CHECKIDENT('product', RESEED, 0)


insert values to identity column in SQL Server

CREATE TABLE Customer(ID int IDENTITY, Name varchar(100), Address varchar(200))
INSERT INTO Customer(ID,Name,Address) VALUES(1,'Shakham','Delhi')
While will get error
SET IDENTITY_INSERT Customer ON  (Allow)
SET IDENTITY_INSERT Customer OFF (DisAllow)
Usually, we use this trick when we have deleted some rows from the table and we want the data in a sequence.

What is transactions, how will be used in stored procedure

Read :Here , Here

How will handle exceptions in stored procedure

Read: Here

Explain what is CTE in SQL Server

Read:Here ,Here

Difference between CTE and Temp Table and Table Variable

Refer: Here

Delete from tables involved in a SQL Join

Deletes all the HR department employees.

Delete E From (Employees E Inner Join Departments D On E.DeptId = D.Id and D.Name = 'HR')
OR
Delete Employees From (Employees join Departments on Employees.DeptId = Departments.Idwhere Departments.Name = 'HR'

Difference between inner join and left join

INNER JOIN returns only the matching rows between the tables involved in the JOIN. Notice that, Pam employee record which does not have a matching DepartmentId in departments table is eliminated from the result-set.
SELECT EmployeeName, DepartmentName
FROM Employees
INNER JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID

LEFT JOIN returns all rows from left table including non-matching rows. Notice that, Pam employee record which does not have a matching DepartmentId in departments table is also included in the result-set. 
SELECT EmployeeName, DepartmentName
FROM Employees
LEFT JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID

SQL Query to get the name of the Department that has got the maximum number of Employees.

SQL query that retrieves the department name with maximum number of employees
SELECT TOP 1 DepartmentName
FROM Employees
JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID
GROUP BY DepartmentName
ORDER BY COUNT(*) DESC

SQL query to find rows that contain only numerical data

Select Value from TestTable Where ISNUMERIC(Value) = 1

ISNUMERIC function returns 1 when the input expression evaluates to a valid numeric data type, otherwise it returns 0. For the list of all valid numeric data types in SQL Server 

SQL query to find employees hired in last n months

Select FROM Employees Where DATEDIFF(MONTH, HireDate, GETDATE()) Between 1 and N
-- Replace N with number of months

Delete duplicate rows in sql

WITH EmployeesCTE AS
(
   SELECT *, ROW_NUMBER()OVER(PARTITION BY ID ORDER BY ID) ASRowNumber
   FROM Employees
)
DELETE FROM EmployeesCTE WHERE RowNumber > 1

How to get second-highest salary employee in a table?

select max(Salary) from Employee where Salary not in (Select Max(Salary) from Employee)
or select max(Salary) from Employee where Salary < (Select Max(Salary) from Employee) 
If want to get nth-highest salary where n=1,2,3......n

SELECT TOP 1 salary FROM (
   SELECT distinct TOP n salary FROM employee ORDER BY salary DESC  ) AS emp ORDER BY salary ASC

To find nth highest salary using CTE
WITH RESULT AS
(
    SELECT SALARY,
           DENSE_RANK() OVER (ORDER BY SALARY DESC) AS DENSERANK
    FROM EMPLOYEES
)
SELECT TOP 1 SALARY FROM RESULT WHERE DENSERANK = N
To find 2nd highest salary we can use any of the above queries. Simple replace N with 2. 

Note:The below query will only work if there are no duplicates.

WITH RESULT AS
(
    SELECT SALARY,
           ROW_NUMBER() OVER (ORDER BY SALARY DESC) AS ROWNUMBER
    FROM EMPLOYEES
)
SELECT SALARY FROM RESULT WHERE ROWNUMBER = 3

Refer:More 

What is SQL Injection?

SQL Injection is one of the many web attack mechanisms used by hackers to steal data from organizations.
It is the type of attack that takes advantage of improper coding of  web applications that allows hacker to inject SQL commands into say a login form to allow them to gain access to the data held within your database.

An In-depth Explanation

SQL Injection is the hacking technique which attempts to pass SQL commands (statements) through a web application for execution by the backend database. If not sanitized properly, web applications may result in SQL Injection attacks that allow hackers to view information from the database and/or even wipe it out.
Ex:- login pages, support and product request forms, feedback forms, search pages, shopping carts and the general delivery of dynamic content, shape modern websites and provide businesses with the means necessary to communicate with prospects and customers. 
These website features are all susceptible to SQL Injection attacks which arise because the fields available for user input allow SQL statements to pass through and query the database directly.

Example of an SQL Injection Attack

SELECT id FROM logins WHERE username = 'username' AND password = 'password’

If the variables username and password are requested directly from the user’s input, this can easily be compromised. 
Suppose that we gave Joe as a username and that the following string was provided as a password: anything' OR 'x'='x

SELECT id FROM logins WHERE username = 'Joe' AND password = 'anything' OR 'x'='x'

As the inputs of the web application are not properly sanitized, the use of the single quotes has turned the WHERE SQL command into a two-component clause.

The 'x'='x' part guarantees to be true regardless of what the first part contains.

This will allow the attacker to bypass the login form without actually knowing a valid username/password combination.

How do I prevent SQL Injection attacks?

Firewalls and similar intrusion detection mechanisms provide little defense against full-scale web attacks.
By passing data through parameters, stored procedures and Table adapters
EX:- 
SELECT id FROM logins WHERE username = @username AND password =@password