Dot Net Question and Answers – Part 2

advertisement
What are the best practices to follow to secure connection strings in an ASP.NET web application?
1. Always store connection strings in the site's Web.config file. Web.config is very secure. Users will not be able to access web.config from the
browser.
2. Do not store connection strings as plain text. To help keep the connection to your database server secure, it is recommended that you encrypt
connection string information in the configuration file.
3. Never store connection strings in an aspx page.
4. Never set connection strings as declarative properties of the SqlDataSource control or other data source controls. Why is "Connecting to SQL
Server using Integrated Security" considered a best practice? Connecting to SQL Server using integrated security instead of using an explicit user
name and password, helps avoid the possibility of the connection string being compromised and your user ID and password being exposed.
What is Script injection?
A script injection attack attempts to send executable script to your application with the intent of having other users run it. A typical script
injection attack sends script to a page that stores the script in a database, so that another user who views the data inadvertently runs the code.
What is SQL injection? A SQL injection attack attempts to compromise your database by creating SQL commands that are executed instead of,
or in addition to, the commands that you have built into your application. What are the best practices to keep in mind when accepting user input
on a web application?
1. Always use validation controls whenever possible to limit user input to acceptable values.
2. Always check the IsValid property of the aspx page. Run the server side code only if the IsValid property value is true. A value of false means
that one or more validation controls have failed a validation check.
3. Always perform server side validation irrespective of client side validation being performed or not. This will protect your web application even
if the client has by passed the client side validation by disabling javascript in the web browser.
4. Also make sure to re validate user input in the business logic layer of your application. What are the steps to follow to avoid Script Injection
attacks?
1. Encode user input with the HtmlEncode method. This method turns HTML into its text representation.
2. If you are using the GridView control with bound fields, set the BoundField object's HtmlEncode property to true. This causes the GridView
control to encode user input when the row is in edit mode. What are the steps to follow to avoid SQL Injection attacks? Always use parameterized
queries or stored procedures instead of creating SQL commands by concatenating strings together.
Can you encrypt view state data of an aspx page?
Yes, you encrypt view state data of an aspx page by setting the page's ViewStateEncryptionMode property to true.
The following are the advantages of a layered architecture:
Layered architecture increases flexibility, maintainability, and scalability. In Layered architecture we separate the user interface from the business
logic, and the business logic from the data access logic. Separation of concerns among these logical layers and components is easily achieved
with the help of layered architecture.
Multiple applications can reuse the components. For example if we want a windows user interface rather than a web browser interface, this can be
done in an easy and fast way by just replacing the UI component. All the other components like business logic, data access and the database
remains the same. Layered architecture allows swapping and reusing components at will.
Layered architecture enables teams to work on different parts of the application parallel with minimal dependencies on other teams.
Layered architecture enables develop loosely coupled systems.
Different components of the application can be independently deployed, maintained, and updated, on different time schedules.
Layered architecture also makes it possible to configure different levels of security to different components deployed on different boxes. So
Layered architecture, enables you to secure portions of the application behind the firewall and make other components accessible from the
Internet.
Layered architecture also helps you to test the components independently of each other.
The following are the disadvantages of a layered architecture:
There might be a negative impact on the performance as we have the extra overhead of passing through layers instead of calling a component
directly.
Development of user-intensive applications can sometime take longer if the layering prevents the use of user interface components that directly
interact with the database.
The use of layers helps to control and encapsulate the complexity of large applications, but adds complexity to simple applications.
Changes to lower level interfaces tend to percolate to higher levels, especially if the relaxed layered approach is used.
Layers refer to logical separation of code. Logical layers help you organize your code better. For example an application can have the
following layers.
1) Presentation Layer or UI Layer
2) Business Layer or Business Logic Layer
3) Data Access Layer or Data Layer
The above three layers reside in their own projects, may be 3 projects or even more. When we compile the projects we get the respective
layer DLL. So we have 3 DLL's now.
Depending upon how we deploy our application, we may have 1 to 3 tiers. As we now have 3 DLL's, if we deploy all the DLL's on the same
machine, then we have only 1 physical tier but 3 logical layers.
If we choose to deploy each DLL on a separate machine, then we have 3 tiers and 3 layers.
So, Layers are a logical separation and Tiers are a physical separation. We can also say that, tiers are the physical deployment of layers.
Tiers:
1) Presentation Tier or UI Tier (Hosts the Presentation Layer or UI Layer). This can be considered as web server in case of an ASP.NET web
application.
2) Application Tier or Business Tier (Hosts Business Layer or Business Logic Layer).
3) Data Access Tier or Data Tier (Hosts Data Access Layer or Data Layer).
4) Database Tier - SQL Server or Oracle (or any other database) which has tables, stored procedures and other database objects.
In general the following are the responsibilities of each layer or tier:
1) Presentation Layer or Tier is usually responsible for interacting with the user.
2) Business Layer or Tier is responsible for implementing the business logic of the application.
3) Data Access Layer or Tier is responsible for encapsulating the code that accesses the persistent data stores such as a relational database.
What are Master Pages in ASP.NET? Or what is a Master Page?
ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel
and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages
that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that
combines the layout of the master page with the content from the content page.
What are the 2 important parts of a master page?
The following are the 2 important parts of a master page
1. The Master Page itself
2. One or more Content Pages
Can Master Pages be nested?
Yes, Master Pages be nested.
What is the file extension for a Master Page?
.master
How do you identify a Master Page?
The master page is identified by a special @ Master directive that replaces the @ Page directive that is used for ordinary .aspx pages.
Can a Master Page have more than one ContentPlaceHolder?
Yes, a Master Page can have more than one ContentPlaceHolder
What is a ContentPlaceHolder?
ContentPlaceHolder is a region where replaceable content will appear.
How do you bind a Content Page to a Master Page?
MasterPageFile attribute of a content page's @ Page directive is used to bind a Content Page to a Master Page.
Can the content page contain any other markup outside of the Content control?
No.
What are the advantages of using Master Pages?
1. They allow you to centralize the common functionality of your pages so that you can make updates in just one place.
2. They make it easy to create one set of controls and code and apply the results to a set of pages. For example, you can use controls on the master
page to create a menu that applies to all pages.
3. They give you fine-grained control over the layout of the final page by allowing you to control how the placeholder controls are rendered.
4. They provide an object model that allows you to customize the master page from individual content pages.
What are the 3 levels at which content pages can be attached to Master Page?
At the page level - You can use a page directive in each content page to bind it to a master page
At the application level - By making a setting in the pages element of the application's configuration file (Web.config), you can specify that all
ASP.NET pages (.aspx files) in the application automatically bind to a master page.
At the folder level - This strategy is like binding at the application level, except that you make the setting in a Web.config file in one folder only.
The master-page bindings then apply to the ASP.NET pages in that folder.
What is @MasterType directive used for?
@MasterType directive is used to create a strongly typed reference to the master page.
Are controls on the master page accessible to content page code?
Yes, controls on the master page are accessible to content page code.
At what stage of page processing master page and content page are merged?
During the initialization stage of page processing, master page and content page are merged.
Can you dynamically assign a Master Page?
Yes, you can assign a master page dynamically during the PreInit stage using the Page class MasterPageFile property as shown in the code
sample below.
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/MasterPage.master";
}
Can you access non public properties and non public methods of a master page inside a content page?
No, the properties and methods of a master page must be public in order to access them on the content page.
From the content page code how can you reference a control on the master page?
Use the FindControl() method as shown in the code sample below.
void Page_Load()
{
// Gets a reference to a TextBox control inside
// a ContentPlaceHolder
ContentPlaceHolder ContPlaceHldr = (ContentPlaceHolder)Master.FindControl ("ContentPlaceHolder1");
if(ContPlaceHldr != null)
{
TextBox TxtBox = (TextBox)ContPlaceHldr.FindControl("TextBox1");
if(TxtBox != null)
{
TxtBox.Text = "TextBox Present!";
}
}
// Gets a reference to a Label control that not in
// a ContentPlaceHolder
Label Lbl = (Label)Master.FindControl("Label1");
if(Lbl != null)
{
Lbl.Text = "Lable Present";
}
}
Can you access controls on the Master Page without using FindControl() method?
Yes, by casting the Master to your MasterPage as shown in the below code sample.
protected void Page_Load(object sender, EventArgs e)
{
MyMasterPage MMP = this.Master;
MMP.MyTextBox.Text = "Text Box Found";
}
What is a Session?
A Session is a unique instance of the browser. A single user can have multiple instances of the browser running on his or her machine. If each
instance visits your Web application, each instance has a unique session. A session starts when a user accesses a page on a Web site for the first
time, at which time they are assigned a unique session ID. The server stores the user's session ID in the Session.SessionID property.
What is the default session timeout period?
20 minutes.
Where do you generally specify the Session Timeout?
You specify the Session Timeout setting in the web.config file.
Can you specify Session Timeout in a code behind file?
Yes, can specify the Session.Timeout property as shown below in a code behind file.
Session.Timeout = 10;
How do you end a user session?
You can call the Session.Abandon() method to end a user session. If a user then tries to access a page the server will assign them a new session
ID and it will clear all the previous session variables. You'll typically use Session.Abandon() on log-out pages.
What type of data can you store in Application State and Session State variables?
Application State and Session State variables are used to store data that you want to keep for the lifetime of an application or for the lifetime of a
session. You can store any type of data in the Application or Session state, including objects.
Is Application State or Session State variables type safe?
No, Application and Session state variables are created on the fly, without variable name or type checking.
Does maintaining Session state affect performance?
Yes
Can you turn of Session state?
Yes, Session state can be turned off at the application and page levels.
Are Application state variables available throughout the current process?
Yes, Application state variables are available throughout the current process, but not across processes. If an application is scaled to run on
multiple servers or on multiple processors within a server, each process has its own Application state.
How do you disable Session state for a Web form?
To turn Session state off for a Web form set EnableSessionState property of the Page to False.
<%@ Page Title="Session state" Language="C#" MasterPageFile="~/Layout.master" AutoEventWireup="true"
CodeFile="Library1.aspx.cs" Inherits="Library" EnableSessionState="False" %>
How do you turn Session state off for an entire web application?
In the Web.config file, set the sessionstate tag to False.
<sessionState cookieless="false" timeout="2000" mode="Off"></sessionState>
What are Application State variables?
Application State variables are global variables that are available from anywhere in the application. All Sessions can access Application State
variables.
How to add and remove data to Application State Variables?
//Code to add data to Application State
Application.Add("AppName", "Sample");
//Code to remove data from Application State
Application.Remove("AppName");
How do you remove all Application State Variables data?
//Code to remove all Application State Variables data
Application.RemoveAll();
What are Exceptions?
Exceptions are unusual occurrences that happen within the logic of an application.
Globalization & Localization
Globalization is the process of designing and developing applications that function for multiple cultures. Localization is the process of
customizing your application for a given culture and locale
What are the 3 approaches to handle exceptions in a Web application?
1. Use exception-handling structures to deal with exceptions within the scope of a procedure. This technique is called structured exception
handling (SEH) in the Visual Studio .NET documentation.
try
catch
finally
2. Use error events to deal with exceptions within the scope of an object.
Page_Error
Global_Error
Application_Error
3. Use custom error pages to display informational messages for unhandled exceptions within the scope of a Web application.
Where will the control flow if an exception occurs inside a try block?
If a statement in a try block causes an exception, control flow passes immediately to the next catch statement. When control flow passes to a
catch block, the statements contained in the catch block are processed to correct the error or otherwise handle the exception.
Will the finally block gets executed, if an exception occurs?
Yes, a finally block will always be executed irrespective of whether an exception has occurred or not.
What is the main use of a finally block in exception handling?
Finally block is mainly used to free resources used within the try block.
How do you raise an exception?
Use the throw keyword to raise an exception. Use this keyword within your exception-handling structure to immediately pass control flow to the
catch statement.
Will the following code block compile?
try
{
throw new System.IO.FileNotFoundException();
}
catch (Exception E)
{
Response.Write(E.Message);
}
catch (System.IO.FileNotFoundException FNFE)
{
Response.Write(FNFE.Message);
}
No, the following compile time error is reported.
A previous catch clause already catches all exceptions of this or of a super type ('System.Exception').
Catch blocks are evaluated in the order in which they appear in code. The exception declaration of each catch block determines which type of
exception the catch block handles. Always order catch blocks from most specific to most general. So, in the preceding sample,
FileNotFoundException should be placed before the general Exception catch block.
What is ApplicationException class used for?
If you are creating a large application or creating components that are used by other applications, you might want to define your own exception
classes based on the ApplicationException class.
For example, the following code defines a class for the UserLoggedOnException:
public class UserLoggedOnException : System.ApplicationException
{
// Exception constructor (overloaded).
public UserLoggedOnException()
: this("The user is already logged on to the server", null)
{
}
public UserLoggedOnException(string message)
: this(message, null)
{
}
public UserLoggedOnException(string message, Exception inner)
: base(message, inner)
{
}
}
The preceding UserLoggedOnException class inherits its properties and methods from the ApplicationException base class. The new exception
class provides only its own constructor to set the default message to display. This is a standard practice.
What are Error Events?
Another way to handle exceptions is through the Web objects’ built-in error events. When an unhandled exception occurs in a Web application,
ASP.NET fires the error events shown below.
Page_Error : Occurs when an unhandled exception occurs on the page. This event procedure resides in the Web form.
Global_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.
Application_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.
Error events let you handle exceptions for an entire object in a single, centralized location—the error event procedure. This is different from using
exception-handling structures, in which exceptions are handled within the procedure where they occurred. You can use error events in the
following ways:
As a substitute for exception-handling structures :
Because error events occur outside the scope of the procedure in which the error occurred, you have less information about the steps leading up to
the exception and therefore less ability to correct the exception condition for the user. However, using exception-handling events is fine for tasks
where you might not be able to correct the exception in code.
As an adjunct to exception-handling structures :
Error events can provide a centralized “backstop” against exceptions that were not foreseen or handled elsewhere. Using the two exceptionhandling techniques together lets you catch all exceptions before the user sees them, display a reasonable message, and even record the exception
in a log as part of an ongoing effort to improve your application.
Give an example to show how error events can be used to handle exceptions?
To handle an exception using error events, follow these steps:
1. In the Page_Error event procedure, get the exception that occurred using the GetLastError method.
2. Do something with the exception, such as display a message to the user, take steps to correct the problem, or write to an error log.
3. Clear the exception using the Clear Error method.
4. Redisplay the page. Web form processing stops immediately when an exception occurs, so server controls and other items on the page might
not be displayed after the exception is cleared.
5. Add the following code to Page_Error event procedure on the web page.
private void Page_Error(object sender, System.EventArgs e)
{
// Get the error.
Exception ex = Server.GetLastError();
// Store the message in a session object.
Session["Error"] = ex.Message;
// Clear the error message.
Server.ClearError();
// Redisplay this page.
Server.Transfer("ErrorEvents.aspx");
}
The preceding code stores the exception message as a Session state variable before clearing the exception so that the message can be displayed
when the page is reloaded by the Transfer method. The following code displays the saved exception message when the page is redisplayed:
Add the following code to Page_Load event procedure on the web page.
private void Page_Load(object sender, System.EventArgs e)
{
// Display error. if any.
if (Session["Error"] != null)
{
litError.Text = "The following error occurred:
"+
Session["Error"].ToString();
// Clear the Session state variable.
Session["Error"] = null;
}
}
Can you have a try block without a catch or a finally block?
No, you cannot have a try block without a catch or a finally block. A try block cannot exist in isolation. A try block should be followed by either
a catch block or a finally block or both.
Is the following code legal?
try
{
Response.Write("Try block executed");
}
finally
{
Response.Write("Finally block executed");
}
Yes, it's legal. A try statement does not have to have a catch statement if it has a finally statement.
What is wrong with using the following type of exception handler?
catch(Exception E)
{
//Some Code
}
This handler catches exceptions of type Exception, therefore, it catches any exception. This can be a poor implementation because you are losing
valuable information about the type of exception being thrown and making your code less efficient. As a result, your program may be forced to
determine the type of exception before it can decide on the best recovery strategy.
Will the second catch block handle the exception thrown by the first catch block?
try
{
throw new System.IO.FileNotFoundException();
}
catch (System.IO.FileNotFoundException FNFE)
{
Response.Write(FNFE.Message);
throw new Exception();
}
catch(Exception E)
{
Response.Write(E.Message);
}
No. For a catch block to handle the exception, the statement that raised the exception must be inside a try block.
What will happen to the exception raised by the code in the following Button1_Click event procedure?
protected void Button1_Click(object sender, EventArgs e)
{
throw new Exception();
try
{
Response.Write("Hello");
}
catch (Exception E)
{
Response.Write(E.Message);
}
}
The exception will not be handled by the catch block because the statement that raised the exception must be inside a try block.
What is the difference between Session Cookies and Persistent Cookies?
Persistent Cookies are same as Session Cookies except that, persistent cookies have an expiration date. The expiration date indicates to the
browser that it should write the cookie to the client's hard drive. Keep in mind that because a user can delete cookies from their machine that there
is no guarantee that a cookie you "drop" on a user machine will be there the next time they visit your site.
What are Persistent Cookies used for?
Persistent cookies are generally used to store information that identifies a returning user to a Web site. Typical information found in Persistent
Cookies includes user names or user IDs.
How do you create a Persistent Cookie?
You create a persistent cookie the same way as session cookies except that you set the Expires property to a Date in the future which will store
the Cookie to the client computer hard drive.
//Code to create a UserName Persistent Cookie that lives for 10 days
HttpCookie CookieObject = new HttpCookie("UserName", "David");
CookieObject.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(CookieObject);
//Code to read the Cookie created above
Request.Cookies["UserName"].Value;
What is Cookie Dictionary?
A cookie dictionary is a single cookie object that stores multiple pieces of information. You use the Values property to access and assign new
values to the cookie dictionary.
Give an example using Cookie Dictionary?
//Code to create a Cookie Dictionary
HttpCookie CookieObject = new HttpCookie("UserPreference");
//Use the Values property to assign new values to the cookie dictionary
CookieObject.Values.Add("UserName", "David");
CookieObject.Values.Add("Country", "USA");
CookieObject.Values.Add("PreviousVisit", DateTime.Now.ToString());
CookieObject.Expires = DateTime.MaxValue;
//Add the Cookie to the client machine using the Response object
Response.Cookies.Add(CookieObject);
//Code to read the Cookie created above
HttpCookie ObjectCookie = Request.Cookies["UserPreference"];
string UserName = ObjectCookie.Values["UserName"];
string Country = ObjectCookie.Values["Country"];
string PreviousVisit = ObjectCookie.Values["PreviousVisit"];
What are the advantages of Using Cookies?
1. Cookies do not require any server resources since they are stored on the client.
2. Cookies are easy to implement.
3. You can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the
client computer (persistent cookies).
What are the disadvantages of Using Cookies?
1. Users can delete cookies.
2. Users browser can refuse cookies, so your code has to anticipate that possibility.
3. Cookies exist as plain text on the client machine and they may pose a possible security risk as anyone can open and tamper with cookies.
How do you create a Cookie that never expires?
To create a Cookie that never expires set the Expires property of the Cookie object to DateTime.MaxValue.
Are Cookies secure?
No, Cookies are not secure. You must pay attention to the type of data you store in cookies.
1. Cookies are not designed to store critical information so storing passwords in a cookie is a bad idea.
2. Keep the lifetime of a cookie as short as practically possible.
3. Encrypt cookie data to help protect the values stored in the cookie.
ADO.NET architecture
Namespaces
using System. Data
using System.Data.SqlClient;
Connection
SqlConnection objConnect = new SqlConnection (Your Connection String);
objConnect.Open();
Listed below are the common connection object methods we could work with:
Open - Opens the connection to our database
Close - Closes the database connection
Dispose - Releases the resources on the connection object. Used to force garbage collecting, ensuring no resources are being held after our
connection is used. Incidentally, by using the Dispose method you automatically call the Close method as well.
State - Tells you what type of connection state your object is in, often used to check whether your connection is still using any resources.
Ex. if (ConnectionObject.State == ConnectionState.Open)
Command Object Methods
1) ExecuteReader - Simply executes the SQL query against the database, using the Read() method to traverse through data, as illustrated below
2) ExecuteNonQuery -Executes commands that have no return values such as INSERT, UPDATE or DELETE
3) ExecuteScalar - Returns a lightning fast single value as an object from your database Ex. object val = Command.ExecuteScalar(); Then check if
!= null.
4) ExecuteXmlReader - Executes the SQL query against SQL Server only, while returning an XmlReader object. See .NET documentation for more
information
5) Prepare – Equivalent to ADO’s Command.Prepared = True property. Useful in caching the SQL command so it runs faster when called more
than once. Ex. Command.Prepare();
6) Dispose – Releases the resources on the Command object. Used to force garbage collecting, ensuring no resources are being held after our
connection is used. Incidentally, by using the Dispose method you automatically call the Connection object’s Close method as well.
DataReader
The DataReader object provides a forward-only, read-only, connected stream recordset from a database. Unlike other components of the Data
Provider, DataReader objects cannot be directly instantiated. Rather, the DataReader is returned as the result of the Command object's
ExecuteReader method. The SqlCommand.ExecuteReader method returns a SqlDataReader object, and the OleDbCommand.ExecuteReader
method returns an OleDbDataReader object. The DataReader can provide rows of data directly to application logic when you do not need to keep
the data cached in memory. Because only one row is in memory at a time, the DataReader provides the lowest overhead in terms of system
performance but requires the exclusive use of an open Connection object for the lifetime of the DataReader.
DataReader Methods
1) Read – Moves the record pointer to the first row, which allows the data to be read by column name or index position. Can check for data
existence with conditional, if (DataReader.Read() = true)
2) HasRows - New only with .NET v1.1. HasRows checks if any data exists, and is used instead of the Read method. Ex. if
(DataReader.HasRows).
3) IsClosed - A method that can determine if the DataReader is closed. Ex. if (DataReader.IsClosed == false)
4) NextResult - Equivalent to ADO’s NextRecordset Method, where a batch of SQL statements are executed with this method before advancing
to the next set of data results. As with the loop just listed, you can add DataReader.NextResult() after the first loop within multiple SQL
statements, and then begin a new loop for the next set.
5) Close – Closes the DataReader
OOPS
Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.
In which Scenario you will go for Interface or Abstract Class?
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are
implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit
implementation from a base class, it also forces you to make most of your design decisions when the class is first published.
Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but
leave the implementation of other methods until a specific Implementation of that class is needed. They also version well, because if additional
functionality is needed in derived classes, it can be added to the base class without breaking code.
What is WCF?
WCF stands for Windows Communication Foundation (WCF) and is considered as the Microsoft Service-Oriented Architecture (SOA) platform
for building connected services and oriented architecture. WCF unifies ASMX, Remoting, and Enterprise Services stacks and provides a single
programming model. WCF services are interoperable and supports all the core Web services standards. WCF services also provide extension
points to quickly adapt to new protocols and updates and integrate very easily with the earlier Microsoft technologies like Enterprise Services,
COM and MSMQ.
Why WCF Services are considered as loosely coupled?
WCF Services are considered as loosely coupled because WCF services are not tightly bound to a particular protocol, encoding format, or
hosting environment. All of these are configurable. At the time of designing WCF services, we do not have to worry about what protocol,
encoding format, or hosting environment to use to expose the service. We can worry about all these at the time of deployment
What is the version of the .NET framework in which WCF is released?
WCF - Windows Communication Foundation is released as part of .NET Framework 3.0. WPF (Windows Presentation Foundation), WF
(Workflow Foundation) and Card Space are also part of .NET Framework 3.0.
What are the 3 things that a WCF Services end point must have? OR What is the ABC of a WCF service?
Address - The address where the WCF Service is hosted.
Binding - The binding that decides the protocol, message encoding and security to use. Binding also decides whether to use reliable messaging
and transaction support.
Contract - The service contract defines what service operations are available to the client for consumption.
So the Address (A), Binding (B) and Contract(C) are called as the ABC of the service end point.
What is the role of WSDL in WCF? OR What is WSDL?
WSDL stands for Web Service Description Language. The WCF service exposes the WSDL document for the clients, to generate proxies and the
configuration file. The WSDL file provides the following information for the consumers of the WCF service.
1. Provides the information about the service contract and operations available.
2. Provides the information about all the end points exposed by the WCF service.
3. Provides the information about the messages and types that can be exchanged between the client and the WCF service.
4. WSDL also provides any information about the policies used.
What is the tool that a client application can use to generate the proxy for a WCF service?
Service Utility (svcutil.exe) can be used by the clients to generate the proxy and configuration file. For the client to be able to generate proxies,
the service should enable metadata exchange
Define Service Contracts and Operation Contracts in WCF?
1. Service Contract - An interface that exposes the service operations is usually decorated with the service contract attribute. Always provide
meaningful Namespace and Name to a service contract as shown in the example below.
2. Operation Contract - All methods in a service contract should have OperationContract attribute. You can also provide explicit Name, Action
and Reply Action as shown in the example below.
Can you apply, ServiceContract attribute to a class rather than an interface in WCF?
Yes, a ServiceContract attribute can be applied either to a class or an interface, but defining service contracts using interfaces rather classes has
the following benefits.
1. Defining service contracts using interfaces, removes coupling to service implementation. Later the implementation can be changed at will
without affecting the clients.
2. Defining service contracts using interfaces, also allows a service to implement more than 1 contract.
What is the purpose of MessageParameter attribute in WCF?
MessageParameter attribute is used to control the parameter and returned object names from a service operation. Consider the example
below. On the service side, the method parameter name in SaveCustomer([MessageParameter(Name = "Customer")] Customer cust) is cust. If
we do not use MessageParameter attribute, then "cust" is what is exposed as parameter name to the client, which is not very professional. So
we are using MessageParameter attribute to expose the method parameter name as Customer.
What are the different options available to serialize complex types that are sent and received between clients and services in WCF?
The following are the different options available to serialize complex types that are exchanged between clients and services in WCF. These
options have their own advantages and disadvantages. Data contracts is the preferred way to serialize complex types in WCF.
1. Serializable types - Use the Serializable attribute on the type that you want to serialize
2. Data contracts - Use DataContract attribute on the type and DataMember attribute on every member of the type that you want to serialize.
You can apply DataMember attribute either on a field or a property.
3. Known types - Use Known types to enable polymorphic behavior in service contracts.
4. IXmlSerializable - IXmlSerializable types provide XSD schema to Web Services Description Language (WSDL) and metadata exchange (MEX).
What is the disadvantage of using Serializable attribute to serialize a complex type that is sent and received between clients and services in
WCF?
When we decorate a class with Serializable attribute, all the fields of the class are serialized regardless of the accessibility. We do not have
control on what to serialize and what not to serialize. We also will not have any control over naming conventions or data types.
What is the preferred way for serializing complex types in WCF?
The preferred way for serializing complex types in WCF is to use data contracts. Using Data Contracts provides us with the following
advantages.
1. Using DataMember attribute, you can control which members of the class to serialize.
2. You can also control the order in which members are serialized using Order parameter of the DataMember attribute..
3. You can also provide explicit Name to the serialized members using Name parameter of the DataMember attribute.
4. You can also specify if a member is required or optional using IsRequired parameter of the DataMember attribute.
Consider the example below which uses Name, IsRequired and Order parameters of the DataMember attribute to serialize CustomerId
property. By the way DataMember attribute can be used with either fields or properties. If you do not specify the order in which members are
serialized, then by default alphabetical ordering is done by the DataContractSerializer.
What is the best way to serialize Polymorphic Types in WCF?
The best way to serialize Polymorphic Types in WCF is to use Known Type attribute on the parent type as shown in the example below.
Corporate Customer and Premium Customer classes inherit from Customer class, and hence we can associate Corporate Customer and
Premium Customer types as known types in 3 different ways depending on the project requirement.
1. Associate known types to the base types themselves.
2. Associate known types to particular operations.
3. Associate known types to the service contract as a whole.
In Example 1, we are associating known types, Corporate Customer and Premium Customer to the base type, Customer.
In Example 2, we are associating known type, CorporateCustomer on SaveCorporateCustomer(Customer customer) and
GetCorporateCustomer(int CustomerId) operations using ServiceKnownType attribute
In Example 3, we are associating known types, CorporateCustomer and PremiumCustomer to the service contract ICustomerService as a whole.
It is also possible to specify known types in a configuration file rather than in code. Example 4 shows how to specify known types in
configuration.file.
SQL
Explain DML, DDL, DCL and TCL statements with examples?
DML: DML stands for Data Manipulation Language. DML is used to retrieve, store, modify, delete, insert and update data in database.
Examples of DML statements: SELECT, UPDATE, INSERT, and DELETE statements.
DDL: DDL stands for Data Definition Language. DDL is used to create and modify the structure of database objects.
Examples: CREATE, ALTER, and DROP statements.
DCL: DCL stands for Data Control Language. DCL is used to create roles, grant and revoke permissions, establish referential integrity etc.
Examples: GRANT, REVOKE statements
TCL: TCL stands for Transactional Control Language. TCL is used to manage transactions within a database.
Examples: COMMIT, ROLLBACK statements
What is the difference between Drop, Delete and Truncate statements in SQL Server?
Drop, Delete and Truncate - All operations can be rolled back.
Delete is a logged operation, which means deleted rows are written to the transaction log. Truncate is not a logged operation, which means
deleted rows are not written to the transaction log.
Hence, truncate is a little faster than Delete. You can have a where clause in Delete statement where as Truncate statement cannot have a where
clause. Truncate will delete all the rows in a Table, but the structure of the table remains. Drop would delete all the rows including the structure
of the Table.
TRUNCATE is a DDL command
DELETE is a DML command
WHERE clause can be used with DELETE and not with TRUNCATE.
Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?
Data Definition Language (DDL)
What's the maximum size of a row?
8060 bytes. Don't be surprised with questions like 'what is the maximum number of columns per table'. Check out SQL Server books online for
the page titled: "Maximum Capacity Specifications".
What operator performs pattern matching? LIKE operator
What operator tests column for the absence of data? IS NULL operator
Which command displays the SQL command in the SQL buffer, and then executes it? RUN
What are the wildcards used for pattern matching?
_ For single character substitution and % for multi-character substitution
Why does the following command give a compilation error? DROP TABLE &TABLE_NAME;
Variable names should start with an alphabet. Here the table name starts with an '&' symbol
What is the use of DESC in SQL?
DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order.
Explanation: The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order.
Which function is used to find the largest integer less than or equal to a specific value? FLOOR
What is GROUP BY?
The GROUP BY keywords has been added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time
they are called. Without the GROUP BY functionality, finding the sum for each individual group of column values was not possible
Difference between a "where" clause and a "having" clause.
Having clause is used only with group functions whereas Where is not used with.
Define candidate key, alternate key, and composite key.
A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table
has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.
A key formed by combining at least two or more columns is called composite key.
What's the difference between a primary key and a unique key?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index
on the column, where are unique creates a no clustered index by default. Another major difference is that, primary key doesn't allow NULLs, but
unique key allows one NULL only.
Define candidate key, alternate key, and composite key.
A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table
has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.
A key formed by combining at least two or more columns is called composite key.
What is bit datatype and what's the information that can be stored inside a bit column?
Bit datatype is used to store boolean information like 1 or 0 (true or false). Until SQL Server 6.5 bit datatype could hold either a 1 or 0 and there
was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.
What is UNION, UNION ALL in SQL?
UNION: eliminates duplicates
UNION ALL: retains duplicates
Both these are used to combine the results of different SELECT statements.
Is BETWEEN inclusive of the range values specified?
Yes.
Date Functions
1) GETDATE() is very common used method which returns exact date time from the system. It does not accept any parameter. Just call it like
simple function.
2) DATEADD() is used to add or subtract date time. Its return a new date time based on the added or subtracted interval.
General Syntax
DATEADD(datepart, number, date)
Date part is the parameter that specifies on which part of the date to return a new value. Number parameter is used to increment date part.
Declare @Date datetime
set @Date = (SELECT GETDATE());
print @Date -- Print Current Date
-- Adding 5 days with Current Date
Select @Date
SELECT DATEADD(day, -5,@Date ) AS NewTime
SELECT DATEADD(day, 5,@Date ) AS NewTime
3) DATEPART()
DATEPART() is used when we need a part of date or time from a datetime variable. We can use DATEPART() method only with select
command.
SELECT DATEPART(year, GETDATE()) AS 'Year'
SELECT DATEPART(month, GETDATE()) AS 'Month'
SELECT DATEPART(hour, GETDATE()) AS 'Hour'
SELECT DATEPART(Day, GETDATE()) AS 'Day'
4) DATEDIFF()
DATEDIFF() is very common function to find out the difference between two DateTime elements.
DATEDIFF(datepart, startdate, enddate)
5) DATENAME()
DATENAME() is very common and most useful function to find out the date name from the datetime value.
SELECT DATENAME(dw, getdate()) AS 'Today Is'
SELECT DATENAME(MONTH, getdate()) AS 'Current Month'
What is Elapsed Time?
Ans - Elapsed time is the clock time it takes to run a piece of code. Basically, the elapsed time is the number of hours, minutes, second, and/or
milliseconds it takes to run a chuck of code.
What is a join and explain different types of joins?
INNER JOIN
OUTER JOIN
LEFT OUTER JOIN
RIGHT OUTER JOIN
FULL OUTER JOIN
What is a self join?
Self join is just like any other join, except that two instances of the same table will be joined in the query Sample SQL: SELECT A.EMPNAME,
B.EMPNAME FROM EMP A, EMP B WHERE A.MGRID = B.EMPID
What is a transaction and ACID?
Transaction - A transaction is a logical unit of work. All steps must be committed or rolled back.
ACID - Atomicity, Consistency, Isolation and Durability, these are properties of a transaction.
Atomicity requires that database modifications must follow an "all or nothing" rule. Each transaction is said to be atomic. If one part of the
transaction fails, the entire transaction fails and the database state is left unchanged
The consistency property ensures that any transaction the database performs will take it from one consistent state to another.
Consistency states that only valid data will be written to the database
Isolation requires that multiple transactions occurring at the same time not impact each other’s execution.
Durability ensures that any transaction committed to the database will not be lost. Durability is ensured through the use of database backups and
transaction logs that facilitate the restoration of committed transactions in spite of any subsequent software or hardware failures
Difference between stored procedure and functions in SQL Server
Functions can run an executable file from SQL SELECT or an action query. Operating system use Execute or Exec to run
Procedure can return zero or n values whereas function can return one value which is mandatory.
Procedures can have input, output parameters for it whereas functions can have only input parameters.
Procedure allows select as well as DML statement in it whereas function allows only select statement in it.
Functions can be called from procedure whereas procedures cannot be called from function
Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function
Functions are basically used to compute values. Stored procedures are basically used to process the task.
Explain different isolation levels
An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read
Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, and
Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION
LEVEL, which lets you customize the isolation level at the connection level.
What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?
Cursors allow row-by-row processing of the result sets.
Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information.
Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip; where as a normal SELECT query makes
only one roundtrip, however large the result set is. Cursors are also costly because they require more resources and temporary storage (results in
more IO operations). Further, there are restrictions on the SELECT statements that can be used with some types of cursors.
Most of the times, set based operations can be used instead of cursors. Here is an example:
If you have to give a flat hike to your employees using the following criteria:
Salary between 30000 and 40000 -- 5000 hike
Salary between 40000 and 55000 -- 7000 hike
Salary between 55000 and 65000 -- 9000 hike
In this situation many developers tend to use a cursor, determine each employee's salary and update his salary according to the above formula.
But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below:
UPDATE tbl_emp SET salary =
CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000
WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000
WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000
END
Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain
condition. You don't have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row.
For examples of using WHILE loop for row by row processing, check out the 'My code library' section of my site or search for WHILE.
Write down the general syntax for a SELECT statements covering all the options.
Here's the basic syntax: (Also checkout SELECT in books online for advanced syntax).
SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by__expression]
[HAVING search_condition]
[ORDER BY order__expression [ASC | DESC] ]
What are triggers? How to invoke a trigger on demand? How many triggers you can have on a table?
Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on
a table.
Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on
which they are defined.
Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but
wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.
In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0
onwards, this restriction is gone, and you could create multiple triggers per each action. But in 7.0 there's no way to control the order in which the
triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder
What is the system function to get the current user's user id?
USER_ID (). Also check out other system functions like USER_NAME (), SYSTEM_USER, SESSION_USER, CURRENT_USER, USER,
SUSER_SID (), HOST_NAME ().
Error severity 13 indicates what?
Transactional deadlock errors.
This level of error severity indicates a transaction deadlock error.
Can you have a nested transaction?
Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT
BEGIN TRY
BEGIN TRANSACTION
INSERT INTO Emp (EmpName,Salary,City,Contact) values (‘PQR1’,12121,’PUNE’,’232’)
DELETE Emp where EmpNo='asd'
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
Select * from emp
@@TRANCOUNT Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection.
The BEGIN TRANSACTION statement increments @@TRANCOUNT by 1. ROLLBACK TRANSACTION decrements @@TRANCOUNT to
0 and each COMMIT TRANSACTION decreases @@trancount by 1.
What is a deadlock and what is a live lock? How will you go about resolving deadlocks?
Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the other's piece. Each process
would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and
terminates one user's process.
A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL
Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table
or page, forcing a write transaction to wait indefinitely.
Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks” in SQL Server books online. Also check out the article Q169960 from
Microsoft knowledge base
What are the different ways of moving data/databases between servers and databases in SQL Server?
There are lots of options available; you have to choose your option depending upon your requirements. Some of the options you have are:
BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP, log shipping, INSERT...SELECT, SELECT...INTO, creating
INSERT scripts to generate data.
Examples
1)Get The temporary table Column names
Select name from tempdb.sys.coulmns where object_id=object_id(‘tempdb..#temp1’)
2)Get The Original table Column names
Select Column_name information_schema.coulmns where table_schema=’tbl_emp’
3) Consider the employee table with column PROJECT nullable. How can you get a list?
Of employees who are not assigned to any project?
SQL: SELECT EMPNO FROM EMP WHERE PROJECT IS null;
Table 1: STUDIES PNAME (VARCHAR), SPLACE (VARCHAR), COURSE (VARCHAR), CCOST (NUMBER)
Table 2: SOFTWARE PNAME (VARCHAR), TITLE (VARCHAR), DEVIN (VARCHAR), DCOST (NUMBER), SCOST (NUMBER)
Table 3: PROGRAMMER PNAME (VARCHAR), DOB (DATE), DOJ (DATE), SEX (CHAR), PROF1 (VARCHAR), PROF2 (VARCHAR),
SAL (NUMBER)
LEGEND: PNAME – Programmer Name,
SPLACE – Study Place,
CCOST – Course Cost,
DEVIN – Developed in,
SCOST – Software Cost, DCOST – Development Cost,
PROF1 – Proficiency
Find out the selling cost average for packages developed in Oracle.
SELECT AVG (SCOST) FROM SOFTWARE WHERE DEVIN = 'ORACLE';
Display the names, ages and experience of all programmers.
SELECT PNAME,dob ,datediff(YEAR,DOB,GETDATE()) ‘AGE’,datediff(YEAR,DOJ,GETDATE())
'Experience' FROM tbl_programmer
Display the names of those who have done the PGDCA course
4) Table 1: DEPT DEPTNO (NOT NULL, NUMBER (2)), DNAME (VARCHAR (14)), LOC (VARCHAR (13)
Table 2 : EMP EMPNO (NOT NULL , NUMBER(4)), ENAME (VARCHAR(10)), JOB (VARCHAR(9)), MGR (NUMBER(4)), HIREDATE
(DATE), SAL (NUMBER(7,2)), COMM (NUMBER(7,2)), DEPTNO (NUMBER(2))
MGR is the empno of the employee whom the employee reports to. DEPTNO is a foreign key
List all the employees who have at least one person reporting to them.
select distinct b.EmpName from Emp a, Emp b where a.EmpNo=b.Mgr
select distinct EmpName from Emp where Emp.mgr in(select EmpNo from Emp)
List the employee details if and only if more than 10 employees are present in department no 10.
SELECT * FROM EMP WHERE DEPTNO IN (SELECT DEPTNO FROM EMP GROUP BY DEPTNO HAVING COUNT(EMPNO)>10 AND
DEPTNO=10)
Find total no of employees from each cities
select City,COUNT(empNo) as 'Total Emp' from Emp group by city
Query to find 2nd or 3rd maximum salary from emp table
select * from emp e where 2 =(select count(distinct Salary) from emp where e.Salary<=Salary)
or 3 =(select count(distinct Salary) from emp where e.Salary<=Salary)
Find Nth Highest Salary of Employee – Query to Retrieve the Nth Maximum value
SELECT TOP 1 salary FROM (SELECT DISTINCT TOP 2 salary FROM emp ORDER BY salary DESC) a ORDER BY salary
Comma Separated Values (CSV) from Table Column
SELECT SUBSTRING((SELECT ',' + s.EmpName FROM emp s ORDER BY s.EmpName FOR XML PATH('')),2,200000) AS CSV
outPut CSV
jack,juli,meena,Rahul,teena
How to remove duplicate records from a table?
select distinct *into emp2 from emp;
truncate table emp;
insert into emp select *from emp2
What does this return?
declare @i int
select @i = -5
select +@i
ans: -5
What does the following query do?
SELECT case when Salary IS null then 0 else Salary end from Emp
This replace null value with 0
What is the output of the following query?
SELECT Round(1234.5678,1) :1230.6000
SELECT Round(1234.5678,0) :1235
SELECT Round(1234.5678,-1) :1230
SELECT Round(1234.5678,-2) :1200
SELECT Round(1234.5678,-3) :1000
SELECT Round(1234.5678,-4) :0.0000
State true or false. EXISTS, SOME, ANY are operators in SQL. True
State true or false. !=, <>, ^= all denote the same operation. True
What are the privileges that can be granted on a table by a user to others? Insert, update, delete, select, references, index, execute, alter, all
What command is used to get back the privileges offered by the GRANT command? REVOKE
What command is used to create a table by copying the structure of another table?
1) CREATE TABLE
2) select * into temp123 from Emp :This copied all data with structure of emp into temp123
Which date function is used to find the difference between two 1 and 1000?
SELECT * from Emp where Salary between 1 AND 1000
Download