Search This Blog

Monday, November 21, 2011

Best Sql Server Interview Questions 2000/2005/2008 : Part 4

Difference between INDEX SEEK AND INDEX SCAN :

The index scan will scan all the data in the data page. Index scan is useful if the table has small amount of datasets. The index scan can be considered as a table scan.
The index seek is good at performance optimization point of view. Index seek will only seek for the satisfying query conditions.

Wednesday, November 16, 2011

Difference between const, static and readonly in c#

Within a class, const, static and readonly members are special in comparison to the other modifiers.

const vs. readonly

const and readonly perform a similar function on data members, but they have a few important differences.


A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the const keyword and must be initialized as they are declared. For example;

public class MyClass
  public const double PI = 3.14159;
PI cannot be changed in the application anywhere else in the code as this will cause a compiler error.
Constants must be a value type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool), an enumeration, a string literal, or a reference to null.

Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure.

Constants can be marked as public, private, protected, internal, or protected internal.
Constants are accessed as if they were static fields, although they cannot use the static keyword.
To use a constant outside of the class that it is declared in, you must fully qualify it using the class name.


A read only member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. For example:

public class MyClass
  public readonly double PI = 3.14159;
public class MyClass
  public readonly double PI;
  public MyClass()
    PI = 3.14159;
Because a readonly field can be initialized either at the declaration or in a constructor, readonly fields can have different values depending on the constructor used. A readonly field can also be used for runtime constants as in the following example:

public static readonly uint l1 = (uint)DateTime.Now.Ticks;
  • readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required.
  • A readonly member can hold a complex object by using the new keyword at initialization.


Use of the static modifier to declare a static member, means that the member is no longer tied to a specific object. This means that the member can be accessed without creating an instance of the class. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. For example:

public class Car
  public static int NumberOfWheels = 4;
The static modifier can be used with classes, fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types other than classes.
static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a static class member, use the name of the class instead of a variable name to specify the location of the member. For example:

int i = Car.NumberOfWheels;

Exposing 2 endpoints for same WCF service using different Bindings

I just created a simple which exposes a service through 2 different endpoints which uses different bindings.One is basicHttpBinding and another using wsHttpBinding.

Specifying 2 EndPoints 

If you have a basic idea about WCF you can easily understand the below configuration in web.config which exposes  Uploader service through 2 different end points.

<service behaviorConfiguration="DemoMTOM.Web.UploaderBehavior"  name="DemoMTOM.Web.Uploader">
<endpoint address="bh" binding="basicHttpBinding" contract="DemoMTOM.Web.IUploader">
<dns value="localhost"/>
<endpoint address="wh" binding="wsHttpBinding" contract="DemoMTOM.Web.IUploader">
<dns value="localhost"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

In the sample the url to the basicHttpBinding endpoint is http://localhost:64738/Uploader.svc/bh and the url to the wsHttpBinding endpoint is http://localhost:64738/Uploader.svc/wh. You can check this by adding a service reference in to a WPF application. 

Creating ServiceClient to call the service in WPF
When we create service reference in the WPF application, the app.config in the WPF application will get 2 entries.One for basicHttpBinding and another for wsHttpBinding.See the sample app.config below.

<endpoint address="http://localhost:64738/Uploader.svc/bh" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IUploader" contract="UploadServiceReference.IUploader"
name="BasicHttpBinding_IUploader" />
<endpoint address="http://localhost:64738/Uploader.svc/wh" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IUploader" contract="UploadServiceReference.IUploader"
<dns value="localhost" />

So at the calling side there will be confusion of course in selecting the end point.So to resolve that confusion we have to specify the endPointConfigurationName at the time of creating client. See code below which uses the basicHttpBinding.

UploadServiceReference.UploaderClient cli = new UploadServiceReference.UploaderClient("BasicHttpBinding_IUploader");
string res = cli.DoWork("Joy");

UploadServiceReference.UploaderClient cli = new UploadServiceReference.UploaderClient("WSHttpBinding_IUploader");
string res = cli.DoWork("Joy");

The second code snippet uses wsHttpBinding to call the service.

Hosting service using 2 endpoints in a Console Application

static void Main(string[] args)
        ServiceHost serviceHost =
new ServiceHost(typeof(Uploader),
new Uri("http://localhost:64738/Uploader.svc"));

typeof(IUploader), new BasicHttpBinding(), "bh");
typeof(IUploader), new WSHttpBinding(), "wh");

        ServiceMetadataBehavior smb =
new ServiceMetadataBehavior();
        smb.HttpGetEnabled =

        ServiceDebugBehavior sdb =  serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
        sdb.IncludeExceptionDetailInFaults =


"Service running below are the Endpoints :");
foreach (ServiceEndpoint se in serviceHost.Description.Endpoints)
"Press any key to quit...");

catch (Exception ex)
string.Format("Error :{0}", ex.Message));

In the sample when you try to run the console application it will throw an error because the application also runs and uses the same port. So run the console application from command line or explorer.

There is no need to change the reference in the WPF application since both these console application and service host is using same url.

Tuesday, November 15, 2011

How to test WCF services

The typical way of testing WCF services is to create a test project, add a service reference to the project, and then write a test against the client object that is automatically created for you:
  • Create a test project
  • Right-click References and select Add Service Reference
  • In the Address box, type in the URL to the SVC file that is hosted on a web server. You can use the Discover button to find WCF services in the same solution.
  • Select a namespace to use for the service client that will be created, and press OK
This will create a class called <Namespace>.<ServiceName>Client for you, which will act as a client proxy to the WCF service. You can then write unit tests against that class just as you would write unit tests against a regular class. You could have a helper method that would convert some input parameters to the Byte array the WCF service takes, and returns the result. Then, each unit test would just call the helper method with the appropriate input parameters, and do validation on the output. The amount of code needed in each unit test can be minimized, but depends on how much validation needs to be done.

It looks like what you have is a web page that acts as a client to the WCF service. It is possible to have the web page take input parameters as query-string parameters in the URL, and have it write the result to the response, as it is already doing. With this, it would be possible to create web tests to test the WCF service through the web page. However, this requires that the web page be hosted on a web server, and separates related parts of test code.

To answer your questions specifically:
  1. The first approach I mentioned above is probably the best way to test a WCF service. It allows you to test methods/properties exposed in the service contract in the same way as any other client application would use the service.
  2. The amount of code that is necessary really depends on how much validation needs to be done on what is being tested. You can use a web page client as an alternative, in which case the amount of code that is needed may be slightly reduced, but you still need the same inputs to the service and the same validation on the outputs, so if it is not through code, it will be through searching the response from the web page. Using a web page client may even unnecessarily complicate your test code, in things such as parsing the query strings to convert the input parameters to the right types, and then parsing the response text to do validation.
  3. Using WcfTestClient.exe (for more info:
  4. VSTS 2008 Test Edition is definitely the right tool for testing WCF services. With the service client that is automatically created for you, testing a WCF service becomes a task as simple as testing a regular class. 

What is the maximum number of Index per table?

For SQL Server 2005:
1 Clustered Index + 249 Nonclustered Index = 250 Index

For SQL Server 2008:
1 Clustered Index + 999 Nonclustered Index = 1000 Index

Find Nth Highest Salary of Employee in Sql server

How to get 2nd, 3rd, 4th, nth topmost salary from an Employee table.
we can get top salary in 2 ways


select top 1 salary from
( select distinct top n salary from Employee order by salary desc ) a
order by Salary

select * from Employee e where n-1 =
(select count(Salary) from Employee f where e.EmpId <= f.EmpId)                                           -- this query won't work for 1st highest salary

In the above query  n = 2nd, 3rd ..... nth salary as per your requirement

Friday, November 11, 2011

Show number of online users / visitors for ASP.NET website?

There are many ways to count number of active visitors on your ASP.NET website.
They differ in technique and accuracy.

here is the simplest approach that delivers acceptable accuracy when configured optimally:

Step 1:

    - first we need to add these lines to our global.asax file
      (if your website do not have it, create it by right-clicking on website in solution explorer,
       and choosing Add New Item > Global Application Class option)

    void Application_Start(object sender, EventArgs e)
        // Code that runs on application startup
        Application["OnlineUsers"] = 0;
    void Session_Start(object sender, EventArgs e)
        // Code that runs when a new session is started
        Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;
    void Session_End(object sender, EventArgs e)
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.
        Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;

This will allow us that whenever some distant web visitor opens our website in his browser,
and new session is created for him, our  "OnlineUsers" variable in the global HttpApplicationState class instance
is increased.

Also when user closes his browser or does not click on any links in our website, session expires,
and our "OnlineUsers" global variable is decreased.

To know more about ApplicationState and HttpApplicationState class visit this MSDN link:

we are using Application.Lock and Application.Unlock methods to prevent multiple threads
from changing this variable at the same time.

By calling Application.Lock we are receiving exclusive right to change the values in Application state.
But we must not forget to call Application.Unlock() afterwards.

Step 2:
    In order for this to work correctly we need to enable sessionstate and configure its mode to InProc value (in our web.config file):

        <sessionState mode="InProc" cookieless="false" timeout="20" />

In-process mode stores session state values and variables in memory on the local Web server.
It is the only mode that supports the Session_OnEnd event that we used previously.

Timeout value (in minutes, not in seconds) configures how long our sessions are kept 'alive' - in other words
here we set how long our users can be inactive before considered Offline.

In this example timeout is set to 20 minutes, so while our visitors click on some links in our website at least once
in a 20 minutes, they are considered online.
If they do not open any pages on our website longer than 20 minutes, they are considered Offline, and their session
is destroyed, so our online visitor counter is decreased by 1.
(You can experiment with lower or higher values of Timeout settings to see what is the best for your website).

Ok, so now we are done with configuration steps, let us see how to use this:

To show number of online visitors/users on your ASPX page you can use this code:
    Visitors online: <%= Application["OnlineUsers"].ToString() %>

Next you could put this code snippet in you UserControl, or inside Asp.Net AJAX UpdatePanel control, and use Timer to refresh it in regular intervals without refreshing the whole page

Wednesday, November 9, 2011

Ajax interview questions (.Net Ajax FAQ's)

What is Ajax?
The term Ajax was coined by Jesse James Garrett and is a short form for "Asynchronous Javascript and XML". Ajax represents a set of commonly used techniques, like HTML/XHTML, CSS, Document Object Model(DOM), XML/XSLT, Javascript and the XMLHttpRequest object, to create RIA's (Rich Internet Applications).
Ajax gives the user, the ability to dynamically and asynchronously interact with a web server, without using a plug-in or without compromising on the user’s ability to interact with the page. This is possible due to an object found in browsers called the XMLHttpRequest object. 

‘ASP.NET AJAX’ is a terminology coined by Microsoft for ‘their’ implementation of AJAX, which is a set of extensions to ASP.NET. These components allow you to build rich AJAX enabled web applications, which consists of both server side and client side libraries. 

Which is the current version of ASP.NET AJAX Control Toolkit?
As of this writing, the toolkit version is Version 1.0.20229 (if you are targeting Framework 2.0, ASP.NET AJAX 1.0 and Visual Studio 2005) and Version 3.0.20229 (if targeting .NET Framework 3.5 and Visual Studio 2008).

What role does the ScriptManager play?
The ScriptManager manages all ASP.NET AJAX resources on a page and renders the links for the ASP.NET AJAX client libraries, which lets you use AJAX functionality like PageMethods, UpdatePanels etc. It creates the PageRequestManager and Application objects, which are prominent in raising events during the client life cycle of an ASP.NET AJAX Web page. It also helps you create proxies to call web services asynchronously.

Can we use multiple ScriptManager on a page?
No. You can use only one ScriptManager on a page.

What is the role of a ScriptManagerProxy?
A page can contain only one ScriptManager control. If you have a Master-Content page scenario in your application and the MasterPage contains a ScriptManager control, then you can use the ScriptManagerProxy control to add scripts to content pages.
Also, if you come across a scenario where only a few pages in your application need to register to a script or a web service, then its best to remove them from the ScriptManager control and add them to individual pages, by using the ScriptManagerProxy control. That is because if you added the scripts using the ScriptManager on the Master Page, then these items will be downloaded on each page that derives from the MasterPage, even if they are not needed, which would lead to a waste of resources.

What are the requirements to run ASP.NET AJAX applications on a server?
You would need to install ‘ASP.NET AJAX Extensions’ on your server. If you are using the ASP.NET AJAX Control toolkit, then you would also need to add the AjaxControlToolkit.dll in the /Bin folder.
Note: ASP.NET AJAX 1.0 was available as a separate downloadable add-on for ASP.NET 2.0. With ASP.NET 3.5, the AJAX components have been integrated into ASP.NET.

Explain the UpdatePanel?
The UpdatePanel enables you to add AJAX functionality to existing ASP.NET applications. It can be used to update content in a page by using Partial-page rendering. By using Partial-page rendering, you can refresh only a selected part of the page instead of refreshing the whole page with a postback.

Can I use ASP.NET AJAX with any other technology apart from ASP.NET?
To answer this question, check out this example of using ASP.NET AJAX with PHP, to demonstrate running ASP.NET AJAX outside of ASP.NET. Client-Side ASP.NET AJAX framework can be used with PHP and Coldfusion.

can you cancel an Asynchronous postback?
Yes you can.
Difference between Server-Side AJAX framework and Client-side AJAX framework?
ASP.NET AJAX contains both a server-side Ajax framework and a client-side Ajax framework. The server-side framework provides developers with an easy way to implement Ajax functionality, without having to possess much knowledge of JavaScript. The framework includes server controls and components and the drag and drop functionality. This framework is usually preferred when you need to quickly ajaxify an application. The disadvantage is that you still need a round trip to the server to perform a client-side action.
The Client-Side Framework allows you to build web applications with rich user-interactivity as that of a desktop application. It contains a set of JavaScript libraries, which is independent from ASP.NET. The library is getting rich in functionality with every new build released.

 How can you debug ASP.NET AJAX applications?
Explain about two tools useful for debugging: Fiddler for IE and Firebug for Mozilla.

Can we call Server-Side code (C# or VB.NET code) from javascript?
Yes. You can do so using PageMethods in ASP.NET AJAX or using webservices.

Can you nest UpdatePanel within each other?
Yes, you can do that. You would want to nest update panels to basically have more control over the Page Refresh.

How can you to add JavaScript to a page when performing an asynchronous postback?
Use the ScriptManager class. This class contains several methods like the RegisterStartupScript(), RegisterClientScriptBlock(), RegisterClientScriptInclude(), RegisterArrayDeclaration(),RegisterClientScriptResource(), RegisterExpandoAttribute(), RegisterOnSubmitStatement() which helps to add javascript while performing an asynchronous postback.

Explain differences between the page execution lifecycle of an ASP.NET page and an ASP.NET AJAX page?
In an asynchronous model, all the server side events occur, as they do in a synchronous model. The Microsoft AJAX Library also raises client side events. However when the page is rendered, asynchronous postback renders only the contents of the update panel, where as in a synchronous postback, the entire page is recreated and sent back to the browser.

Explain the AJAX Client life-cycle events
Here’s a good article about the same.

Is the ASP.NET AJAX Control Toolkit(AjaxControlToolkit.dll) installed in the Global Assembly Cache?
No. You must copy the AjaxControlToolkit.dll assembly to the /Bin folder in your application.
 Those were some frequently asked questions you should have knowledge about. In one of the coming articles, we will cover some more ASP.NET AJAX FAQ’s which were not covered in this article. I hope this article was useful and I thank you for viewing it.

C# var Vs Javascript var

Difference between C# var and Javascript var


var i = 10; // implicitly typed
int i = 10; //explicitly typed

//Initialization is mandatory
var a = 10;
a = 13;
//Not Allowed
a = "string";

By using above example we can say C# var is strongly typed, but inferred from whatever the value is being assigned.  


   <script type="text/javascript">
        var a = "stringValue";
              a = 567;
              a= "2ndString"; // allowed

Monday, November 7, 2011

How to Create DataTable Programmatically in C#, ASP.NET


Most of the times programmers fill the DataTable from database. This action fills the schema of the database table into the DataTable. We can bind data controls like GridView, DropdownList to such DataTable. But somtimes what happens is one needs to create a DataTable programmatically. Here I have put the simple method of creating DataTable programmatically in C#.

Create a DataTable instance

DataTable table = new DataTable();

Create 7 columns for this DataTable
DataColumn col1 = new DataColumn("ID");
DataColumn col2 = new DataColumn("Name");

Define DataType of the Columns
col1.DataType = System.Type.GetType("System.Int");
col2.DataType = System.Type.GetType("System.String");

Add All These Columns into DataTable table

Create a Row in the DataTable table
DataRow row = table.NewRow();

Fill All Columns with Data
row[col1] = 1100;
row[col2] = "Computer Set";

Add the Row into DataTable

Want to bind this DataTable to a GridView?
GridView gvTest=new GridView();
gvTest.DataSource = table;

Popular Posts