C# and .NET step by step with interview questions
Showing posts with label FAQ. Show all posts
Showing posts with label FAQ. Show all posts
Monday, April 29, 2013
Thursday, October 21, 2010
CAS (Code access security) & .NET 4.0 Security model FAQ (With Full Video demonstration)
Introduction
What is CAS?
What is evidence in CAS?
What is a permission and permission set?
What is code group?
So how does CAS work on runtime?
Can we see a quick demo of CAS?
What is CASPOL.exe?
When I open a .NET 4.0 DLL/Assembly using CASPOL it throws an error?
Can you throw some more light on the security transparent model?
A demo of security transparent model can really make things clear?
What is the concept of sandboxing?
Security transparent is good when we control the code what about external DLL?
But why this change, what was the problem with CAS?
So how can we give code access after .NET 4.0 and later?
What if I still want to use CAS in .NET 4.0?
References
This article first starts with the basic concepts of CAS like evidence, permission, code groups and caspol.exe. It then moves ahead to demonstrate how CAS can be implemented in real world. This article further talks about ground up changes made in .NET 4.0 for CAS. In those regards it discusses about security transparent model and sandboxing.
Bet me this article is your last chance to see CAS in actual action....enjoy.
This is a small Ebook for all my .NET friends which covers topics like WCF, WPF, WWF, Ajax, Core .NET, SQL etc you can download the same from here
or else you can catch me on my daily free training @ here
In order to know the same we need to probe the assembly / exe / dll and get evidences like who is the publisher of the code , from which site has this code from , from which zone has it come from ( internet , intranet etc) etc.
These permissions are collect permission sets and those permission sets are allocated to the code.
For instance there are various default code groups like My computer zone , internet zone , intranet zone etc.
My computer zone code group is allocated to code who evidence says that they are assemblies which are installed on the computer and they have permission set ‘internet’ which has various permissions like file dialog , execute , user interface , printing etc.

• Evidences are gathered about the assembly. In other words from where did this assembly come?
• Depending on evidences the assembly is assigned to a code group. In other words what rights does the assembly depending on the evidence gathered.
• Depending on code group the assembly is allocated security rights.
• Using the security rights the assembly is run with in those rights.

Can we see a quick demo of CAS?
If you want to allocate rights to an assembly we need to install the .NET configuration tool and click on trust assembly menu as shown in the below figure.

Once you trust the assembly you can adjust the trust to full trust or none.

Please do see the below complete video which explains how we can assign
permission, permission set,code group and evidence to an exe or an assembly.

What is CASPOL.exe?
It’s the core exe which is responsible to assign permission to the assembly. The .NET configuration tool is just a cover which sits on the top of caspol.exe to ease our work. CASPOL.exe commands are cryptic so the .NET configuration too is more user friendly. In case you are interested in using caspol.exe you can go to visual studio command prompt and type caspol.exe with necessary parameters.

CAS is completely deprecated in .NET 4.0, there are two big changes:-
• Granting of permission is no more dependent on the .NET CAS, it’s now the job of the host. So the host who runs the .NET DLL will define what kind of rights will the assembly have. NET Framework 4.0 comes with CAS a disabled which means all applications started via Windows Explorer or the command prompt run with full trust. Hosted .NET applications, those running inside Internet Explorer or ASP.NET, will run at the trust level granted by their host, being partially trusted.
• Security transparent model is introduced which divides a .NET code in to 3 categories Security critical, Security transparent and security safe critical.
By putting the above compartments you have ensured that the unsecured code (Security transparent) cannot call the secured code (Security critical). When you mark a code as security transparent, these types of code cannot call security critical code.
If for some reason the transparent code wants to call security critical code it can go via the bridge security safe critical code.


So if you have third party DLL you can create your own appdomain and assign permission sets so that your 3rd party DLL runs under a control environment. Below is a simple code snippet which shows how we can do things. The below code snippet, creates an application domain, allocates permissions for execution and user interface display only.
We then try to do something funny like popping up a file brows dialog box and we end up with error as shown in the below figure.
Step1:- Create appdomain with two permission execution and UI display
using permission set class.
Step 2:- Apply the above defined permission set to the newly created application domain as shown in the below code snippet.
Step 3:- Create the instance and try calling the ‘ShowDialog’ function.

• If you have to move the assembly to a different computer you need to do the whole rework again.
• The worst part CAS does not work on unmanaged code. I am dead sure it’s always possible you will download exe which is not written in .NET.
• Log on with an Administrator account.
• Type gpedit.msc into the Run or Search box on your Start menu, click OK, and
Group Policy will open.
• Go down to Computer Configuration > Windows Settings > Security Settings.
• Right-click on "Software Restriction Policies" and create new policies.

http://blogs.rev-net.com/ddewinter/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/
http://msdn.microsoft.com/en-us/library/930b76w0%28VS.90%29.aspx
What’s new in .NET 4.0 security
http://www.simple-talk.com/dotnet/.net-framework/whats-new-in-code-access-security-in-.net-framework-4.0---part-i/
CAS in .NET nice simple article
http://www.devx.com/vb2themax/article/19886/1954
Nice Q and A article explaining CAS
http://justindeveloper.wordpress.com/2010/02/09/application-security-for-developers/
5 reasons why you would use sandboxing
http://blogs.msdn.com/b/shawnfa/archive/2006/04/19/579066.aspx
Legacy CAS policy in .NET 4.0 backward compatibility
http://blogs.rev-net.com/ddewinter/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/
What is CAS?
What is evidence in CAS?
What is a permission and permission set?
What is code group?
So how does CAS work on runtime?
Can we see a quick demo of CAS?
What is CASPOL.exe?
When I open a .NET 4.0 DLL/Assembly using CASPOL it throws an error?
Can you throw some more light on the security transparent model?
A demo of security transparent model can really make things clear?
What is the concept of sandboxing?
Security transparent is good when we control the code what about external DLL?
But why this change, what was the problem with CAS?
So how can we give code access after .NET 4.0 and later?
What if I still want to use CAS in .NET 4.0?
References
Introduction
Many developers understand the concept of CAS (Code access security) but very few know how to implement the same. This article will discuss and demonstrate practically all those aspects of CAS which you have ready only in theory till today.This article first starts with the basic concepts of CAS like evidence, permission, code groups and caspol.exe. It then moves ahead to demonstrate how CAS can be implemented in real world. This article further talks about ground up changes made in .NET 4.0 for CAS. In those regards it discusses about security transparent model and sandboxing.
Bet me this article is your last chance to see CAS in actual action....enjoy.
This is a small Ebook for all my .NET friends which covers topics like WCF, WPF, WWF, Ajax, Core .NET, SQL etc you can download the same from here
or else you can catch me on my daily free training @ here
What is CAS?
Code Access security is a security model which grants or denies permission to your assembly depending on evidences like from where the code has emerged, who the publisher is? , strong names etc.What is evidence in CAS?
When you want to execute any code in your environment you would first like to know from where the code came from. Depending from where it came from, you would then would like to give him access rights. For instance a code compiled from your own computer would have greater rights than code downloaded from the internet.In order to know the same we need to probe the assembly / exe / dll and get evidences like who is the publisher of the code , from which site has this code from , from which zone has it come from ( internet , intranet etc) etc.
What is a permission and permission set?
Once you have gathered the evidences about the code you would like to assign permission to the code. There are various permissions which you can assign to the code like Can the code create a file, can we write to registry, can the code execute reflection, can the code open file dialog box etc.These permissions are collect permission sets and those permission sets are allocated to the code.
What is code group?
Code groups are nothing but categories of code. These categories are defined by permissions and evidence values. When .NET code runs it’s assigned to a code group by the evidences which are collected during runtime.For instance there are various default code groups like My computer zone , internet zone , intranet zone etc.
My computer zone code group is allocated to code who evidence says that they are assemblies which are installed on the computer and they have permission set ‘internet’ which has various permissions like file dialog , execute , user interface , printing etc.
So how does CAS work on runtime?
When the assembly runs following steps takes place:-• Evidences are gathered about the assembly. In other words from where did this assembly come?
• Depending on evidences the assembly is assigned to a code group. In other words what rights does the assembly depending on the evidence gathered.
• Depending on code group the assembly is allocated security rights.
• Using the security rights the assembly is run with in those rights.
Can we see a quick demo of CAS?
If you want to allocate rights to an assembly we need to install the .NET configuration tool and click on trust assembly menu as shown in the below figure.Once you trust the assembly you can adjust the trust to full trust or none.
Please do see the below complete video which explains how we can assign
permission, permission set,code group and evidence to an exe or an assembly.
What is CASPOL.exe?
It’s the core exe which is responsible to assign permission to the assembly. The .NET configuration tool is just a cover which sits on the top of caspol.exe to ease our work. CASPOL.exe commands are cryptic so the .NET configuration too is more user friendly. In case you are interested in using caspol.exe you can go to visual studio command prompt and type caspol.exe with necessary parameters.When I open a .NET 4.0 DLL/Assembly using CASPOL it throws an error?
If you try to open a .NET 4.0 DLL in configuration wizard you will get an error as shown below.CAS is completely deprecated in .NET 4.0, there are two big changes:-
• Granting of permission is no more dependent on the .NET CAS, it’s now the job of the host. So the host who runs the .NET DLL will define what kind of rights will the assembly have. NET Framework 4.0 comes with CAS a disabled which means all applications started via Windows Explorer or the command prompt run with full trust. Hosted .NET applications, those running inside Internet Explorer or ASP.NET, will run at the trust level granted by their host, being partially trusted.
• Security transparent model is introduced which divides a .NET code in to 3 categories Security critical, Security transparent and security safe critical.
Can you throw some more light on the security transparent model?
The security transparent model puts code in to separate boxes as per the risk associated. If you know that code can do something wrong you can box that code as ‘Security transparent’ and if you have a code which you trust you can box them in to ‘Security critical’.By putting the above compartments you have ensured that the unsecured code (Security transparent) cannot call the secured code (Security critical). When you mark a code as security transparent, these types of code cannot call security critical code.
If for some reason the transparent code wants to call security critical code it can go via the bridge security safe critical code.
A demo of security transparent model can really make things clear?
Below is a simple video where we have created a simple code marked it as security critical and then we tried calling the same from security transparent code and we get an error.What is the concept of sandboxing?
The next question answers the same.Security transparent is good when we control the code what about external DLL?
The security transparent code is good when we control the code but what if get assembly which is a third party. In those situations you can use the concept of sandboxing. One of the important points to note is that CAS is deprecated and not removed completely.So if you have third party DLL you can create your own appdomain and assign permission sets so that your 3rd party DLL runs under a control environment. Below is a simple code snippet which shows how we can do things. The below code snippet, creates an application domain, allocates permissions for execution and user interface display only.
We then try to do something funny like popping up a file brows dialog box and we end up with error as shown in the below figure.
Step1:- Create appdomain with two permission execution and UI display
using permission set class.
PermissionSet permset = new PermissionSet(PermissionState.None); permset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); permset.AddPermission(new UIPermission(UIPermissionWindow.AllWindows));
Step 2:- Apply the above defined permission set to the newly created application domain as shown in the below code snippet.
AppDomainSetup objSetup = new AppDomainSetup();
objSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
AppDomain domain = AppDomain.CreateDomain("New domain name",
AppDomain.CurrentDomain.Evidence, objSetup, permset);
Step 3:- Create the instance and try calling the ‘ShowDialog’ function.
Interface1 i1 = (ClassLibrary1.Class1)domain.CreateInstanceAndUnwrap("ClassLibrary1",
"ClassLibrary1.Class1");
i1.ShowDialog();
If you try to execute the open dialog it will pop up an error as shown in the below code.But why this change, what was the problem with CAS?
• First thing CAS was not easy, all those cryptic steps of creating code groups, and permission sets etc eats your energy completely.• If you have to move the assembly to a different computer you need to do the whole rework again.
• The worst part CAS does not work on unmanaged code. I am dead sure it’s always possible you will download exe which is not written in .NET.
So how can we give code access after .NET 4.0 and later?
The best way to restrict code access is by putting restriction at the operating system level. Windows SRP (Software restriction policy) helps to achieve the same.• Log on with an Administrator account.
• Type gpedit.msc into the Run or Search box on your Start menu, click OK, and
Group Policy will open.
• Go down to Computer Configuration > Windows Settings > Security Settings.
• Right-click on "Software Restriction Policies" and create new policies.
What if I still want to use CAS in .NET 4.0?
“<NetFx40_LegacySecurityPolicy>” configuration element lets you specify that a process or library uses CAS policy. When you activate this element, the policy and evidence overloads will work as they did in older versions of the .NET framework.<configuration> <runtime> <NetFx40_LegacySecurityPolicy enabled="true"/> </runtime> </configuration>
http://blogs.rev-net.com/ddewinter/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/
References
MSDN link to CAShttp://msdn.microsoft.com/en-us/library/930b76w0%28VS.90%29.aspx
What’s new in .NET 4.0 security
http://www.simple-talk.com/dotnet/.net-framework/whats-new-in-code-access-security-in-.net-framework-4.0---part-i/
CAS in .NET nice simple article
http://www.devx.com/vb2themax/article/19886/1954
Nice Q and A article explaining CAS
http://justindeveloper.wordpress.com/2010/02/09/application-security-for-developers/
5 reasons why you would use sandboxing
http://blogs.msdn.com/b/shawnfa/archive/2006/04/19/579066.aspx
Legacy CAS policy in .NET 4.0 backward compatibility
http://blogs.rev-net.com/ddewinter/2010/03/02/tip-20-opting-out-of-security-changes-in-net-4-in-asp-net-and-custom-appdomains/
Tuesday, August 31, 2010
.NET 4.0 MEF FAQ (Socket, Plug and extension)
Introduction and GoalWhat is MEF (Manage extensibility framework)?
How can we implement MEF in .NET 4.0?
Can we see a simple example of MEF with the above 3 steps?
Should data types of import and export match?
Can we connect import and export via some defined contract rather than .NET data types?
This looks very much similar like DI and IOC, why the re-invention?
Can they work hand on hand?
We would like to see a sample in Silverlight?
Can we also see a simple Sample in WPF?
How about some Sample in ASP.NET?
Reference
Introduction and Goal
This FAQ deep dives in to .Net 4.0 MEF fundamentals (Import and Export) and also explains when to use MEF over DI / IOC. This article also explains step by step on how to use MEF in various technologies like Silverlight, WPF and ASP.NET.
Please feel free to download by free .NET Ebook which has 400 questions and answers in WCF,WPF,WWF,Silverlight and lot more http://www.questpond.com/SampleDotNetInterviewQuestionBook.zip
What is MEF (Manage extensibility framework)?
MEF is a framework by which you can make your application extensible. For example you have an accounting application and you would like to provide a hook (socket) where external vendors can connect (plug) and add invoicing capabilities to the accounting application.For instance you have application which you would want different vendors to connect with their features and extend your application.
So the vendors just put the components in the application, the application discovers them and does the connection and extension.

How can we implement MEF in .NET 4.0?
Implementing MEF is a three step process:-
• Import (Create the socket):- Use the “Import” attribute to define a hook or socket in your application.
• Export (Attach the Plug):- Use the “Export” attribute to create the plug which can attach to the plug or hook.
• Compose (Extend it):- Use the composition container and compose it.

Can we see a simple example of MEF with the above 3 steps?
We will create a simple class which will have a hook to import string message. In other words any class who has functionality of string message implementation can attach themself to the hook and extend that class.Step 1:- Create the socket (Import)
The first step is to create a place holder / hook / socket where other components can plug in.
Import the below namespaces needed by MEF.
using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Reflection;
To define a hook we have created an empty property called as “ImportMessage”
and we have attributed the same with “Import” attribute.
class Program
{
[Import()]
public string ImportMessage
{
set;
get;
}
}
The above “import” attribute says that anyone who has string functionality implementation type
can connect to me and attach the functionality.
Step 2:- Create and attach the plug (Export)
In order to create the plug or extension we need to use the “Export” attribute as shown below. This attribute in the current scenario does nothing but displays a simple string.
class clsMySimpleMessage
{
[Export()]
string ExportMessage
{
set
{
}
get
{
return "Message inserted via MEF";
}
}
}
Step 3: Connect and Extend it (Compose it)
Ok so we have created the socket, the plug and it’s time to connect these both. Below goes the code for the same.
private void Compose()
{
// Get a reference to the current assemblies in the project.
AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
// Once you have got the reference of catalog add it to the composition container.
CompositionContainer compositionContainer = new CompositionContainer(catalog);
// Finally call composeparts to connect the Import with Export.
compositionContainer.ComposeParts(this);
// use the property
Console.WriteLine(ImportMessage);
Console.ReadLine();
}
In other words export, import and compose, Below figure summarizes the same.

“Export” is like things you give off and “import” is like things which you take in.
Should data types of import and export match?
The types of import and export should match or else while composing you will get an error as shown below. Can incompatible socket and plug connect?.

Can we connect import and export via some defined contract rather than .NET data types?
In real world your hooks would be some real world contract types like customer, supplier etc rather than simple .NET data types like string, int, Boolean etc. In order to create a real word kind of hook in MEF, we need to first create a contract using interfaces as shown below.
interface ImyInterface
{
string getString();
}
We need to ensure that the hooks defined in both import and export attribute are of the same interface type as shown below. The binding logic using
composition container does not change; it’s the same as described in the previous section.
[Export(typeof(ImyInterface))]
class clsMyImplementation : ImyInterface
{
public string getString()
{
return "This is my string";
}
}
class Program
{
[Import()]
public ImyInterface myInterface
{
set;
get;
}
}
This looks very much similar like DI and IOC, why the re-invention?
In case you are new to DI/IOC read here .http://www.codeproject.com/KB/aspnet/IOCDI.aspxBoth of them overlap each other to a very great extent but the GOALS are different. DI and IOC is meant for decoupling while MEF is for extensibility. The below requirement will throw more light on how to decide which solution to go for:-

Below table summarizes the same in a detail manner.

If you have still questions post it to Glenn Block over here
http://codebetter.com/blogs/glenn.block/archive/2009/08/16/should-i-use-mef-for-my-general-ioc-needs.aspx
Can they work hand on hand?
Let say you have an application and following is your requirement.

The way to approach the first requirement is by using your favorite IOC container and the second requirement is where MEF fits.
Below diagram shows how they fit in to the whole game.
The end GOAL is more important when making a choice between them.

Below is a nice article by Mr. Nicholas Blumhardt which shows how MEF and IOC fit in.
http://blogs.msdn.com/b/nblumhardt/archive/2009/03/16/hosting-mef-extensions-in-an-ioc-container.aspx
We would like to see a sample in Silverlight?
The main important steps do not change.
Step 1:- Create the socket (Import)
Define the Silverlight items you want to import. In the below code snippet we have defined a collection of user control type.
public partial class MainPage : UserControl
{
[ImportMany]
public ObservableCollection<UserControl> ImportedItems
{ get; set; }
}
Step 2:- Create and attach the plug (Export)
Use “Export” to define the plug. For the current scenario we have defined two Silverlight user control with export attribute exposing “UserControl” as the type.
[Export(typeof(UserControl))]
public partial class SilverlightControl1 : UserControl
{
public SilverlightControl1()
{
InitializeComponent();
}
}
[Export(typeof(UserControl))]
public partial class SilverlightControl2 : UserControl
{
public SilverlightControl2()
{
InitializeComponent();
}
}
Step 3: Connect and Extend it (Compose it)
Use the “SatisfyImport” to compose the exports and import.
CompositionInitializer.SatisfyImports(this);
If you run the same you should see the composed user controls in the main Silverlight UI container as shown below.

The whole Silverlight picture looks something as shown below.

Can we also see a simple Sample in WPF?
Phrrr..phusss….tired will update soon.How about some Sample in ASP.NET?
Phrrr..phusss….tired will update soon.Reference
Hansel and Glenn talks about difference between MEF and IOC on http://www.hanselminutes.com/default.aspx?showID=16610 reasons why to use MEF http://csharperimage.jeremylikness.com/2010/04/ten-reasons-to-use-managed.html
MEF for beginners http://blogs.microsoft.co.il/blogs/bnaya/archive/2009/11/28/mef-for-beginner-concept-part-1.aspx
As said by Sreeni Ramadurai its import, export and bin.
http://mstecharchitect.blogspot.com/2010/02/mef-managed-extensibility-framework.html
Simple article on MEF
http://www.sidarok.com/web/blog/content/2008/09/26/what-is-this-managed-extensibility-framework-thing-all-about.html
Thursday, January 28, 2010
SQL Query Optimization FAQ Part 1 (The SQL Plan)
SQL Query Optimization FAQ Part 1 (The SQL Plan)
Introduction and GoalWhat is a SQL execution Plan?
Can we understand step by step how SQL Query plan is created and executed?
Ok, so where do I start from?
What is a Table Scan (Operator number 1)?
Can performance increase by adding a unique key for table scans?
What are physical and logical reads?
Table scan doesn’t look to be efficient?
What is a seek scan (Operator number 2)?
Can we see a seek scan practically?
We have2 types of indexes so do we have different operators for it?
What are heap tables in SQL
Server? What is RID
Lookup heap in SQL query plan?
What is a bookmark lookup?
Lookups are costly operation, how can we eliminate the same?
What are covering indexes?
Do we have any other efficient way of creating covering indexes?How does size of the index affect performance?How
does unique column increase index performance?How
important is the order of indexes?What is the preferred data type for indexes?
What are indexed views and how does it improve
performance?
Can we see practically how indexed views
increase performance? How do we specify index hints?
Does index hints increase performance?
References
Detail links which discuss Physical and logical read
Introduction and Goal
In this article we will first try to understand what is a SQL plan, how is it created and then we will move towards understanding how to read the SQL plan. As we read the SQL plan we will try to understand different operators like table scan, index seek scan, clustered scan, RID lookup etc. We will also look in to the best practices associated with clustered and non-clustered indexes and howthey function internally. We will practically see how indexed views increase performance and in what scenarios we should use the same.
Here’s my small gift for all my .NET friends , a complete 400 pages FAQ Ebook which covers various .NET technologies like Azure , WCF , WWF , Silverlight , WPF , SharePoint and lot more Click
hereVideo explanation of this article
- In case you do not want to read the whole article you can view the below videos
This video runs through the basic concepts of SQL plan,Iterators and logical reads , click here to see the same. - This video explains how table scan performance is improved by unique keys, click here
to see the same.
What is a SQL execution Plan?
Every SQL query is broken down in to series of execution steps called as operators. Each operator performs basic operations like insertion, search, scan, updation, aggregation etc. There are 2 kinds of
operators Logical operators and physical operators.Logical operators describe how the execution will be executed at a conceptual level while physical operators are the actual logic / routine which perform the action.
On the query plan you always physical operators. One logical operator can map to multiple physical operator. It can also go vice versa but that’s a rare scenario. Some operators are both physical as well as logical. You can check out all the logical and physical operators for SQL Server at http://msdn.microsoft.com/en-us/library/ms191158.aspx . Below table shows some sample mapping between logical and physical operators.
Can we understand step by step how SQL Query plan is created and executed?
There are three phases through which a SQL is parsed and executed.

Parse: - The first phase is to parse the SQL query for syntaxes and create a query processor tree which defines logical steps to execute the SQL. This process is also called as ‘algebrizer’.Optimize: - The next step is to find a optimized way of executing the query processor tree defined by the ‘algebrizer’. This task is done by using ‘Optimizer’.’Optimizer’ takes data statistics like how many rows, how many unique data exist in the rows, do the table span over more than one page etc. In other words it takes information about data’s data. These all statistics are taken, the query
proces or tree is taken and a cost based plan is prepared using resources, CPU and I/O. The optimizer generates and evaluates many plan using the data statistics, query processor tree, CPU cost, I/O cost etc to choose the best plan.
The optimizer arrives to an estimated plan, for this estimated plan it tries to find an actual execution plan in the cache. Estimated plan is basically which comes out from the optimizer and actual plan is the one which is generated once the query is actually executed.
Execute: - The final step is to execute the plan which is sent by the optimizer.Ok, so where do I start from?
Till now we have understood operators and the way SQL plan is created and executed. So the first thing is to understand different operators and their logic. As discussed previously operator’s form the basic unit of you SQL plan, if we are able to understand them we can optimize our SQL to a great extent. So let’s understand the basic and important operators.
What is a Table Scan (Operator number 1)?
Before we try to understand table scan operator let’s try to see how can we see a SQL plan. Once you are in your SQL management studio, click on new query and write the SQL for which you want to see the SQL plan. Click on the icon which is displayed on the query window as shown below. Once you hit the icon you will see the query plan.
Now that we have understood how to see a query plan let try to understand the first basic operator i.e. table scan. In order to understand the same we have created a simple companies table with company code and description. Do not create any primary key or indexes. Now write a simple SQL with a select clause on one of the properties, we have selected company code currently as shown in the above figure.If you hit on the query plan icon you will see table scan in your query plan. Now let’s try to understand what it signifies.
If there is a primary key table scan operator scans row by row every record until it finds the exact record. For instance in our search criteria we have given ‘500019’ as the company code. In table scan it goes row by row until it finds the record. Once it gets the record it sends the same as output to the end client.In case the table does not have a primary key, it will continue searching ahead to find more matches if there are any.
Can performance increase by adding a unique key for table scans?
Yes, the performance increases if you add a unique key for table scan search criteria. Let’s see an actual demonstration of the same. So right click on the table field and create a unique key on customer code field as shown in the below figure.
Now let’s go to SQL Server analyzer and set the statistics to ‘ON’ using ‘set statistics io on’. With the statistics we also execute our query with the customer code criteria as shown in the below code snippet.set statistics io on
SELECT TOP 1000 [CustomerCode]
,[CustomerName]
FROM [CustomerNew].[dbo].[Customers]
where customercode=524412
If you click on messages you will see logical reads as ‘3’.
(1 row(s) affected)
Table 'Customers'. Scan count 0, logical reads 3, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Now let’s go and remove the unique key the logical reads are 17, which means performance has degraded as compared with unique key.
(1 row(s) affected)
Table 'Customers'. Scan count 1, logical reads 17, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
What are physical and logical reads?
The main work of database is to store and retrieve data. In other words lot of reads and writes to the disk. Read and writes consume lot of resources and take long time for completion. SQL server
allocates virtual memory for cache to speed up I/O operations. Every instance of SQL server has its own cache.When data is read it is stored in the SQL cache until it’s not referenced or the cache is needed for some purpose. So rather than reading from physical disk its read from SQL cache. In the same way for writing, data is written back to disk only if it’s modified.
So when data is fetched from SQL cache its terms as logical read and when its read from physical database its termed as physical read.
Table scan doesn’t look to be efficient?
Table scan operators are good if the numbers of records in the tables are less. If the numbers of records in the tables are more, then table scan is very inefficient as it needs to scan row by row to get to the record.So for big number of rows in a table rather than table scan operator, seek scan operator is preferred.
What is a seek scan (Operator number 2)?
Seek scan does not scan all the rows to go to a record, it uses indexes and b-tree logic to get to a record. Below is a sample diagram, which explains how B-Tree fundamental works. The below diagram shows how index will work for number from 1-50:-
• Let us say you want to search 39. SQL Server will first start from the first
node i.e. root node.
• It will see that the number is greater than 30, so it moves to the 50 node.
• Further in Non-Leaf nodes it compares is it more than 40 or less than 40. As
it’s less than 40 it loops through the leaf nodes which belong to 40 nodes.
In table scan it scans all rows while in seek scan it scans less number of rows comparatively. For instance to get to the record 39 it only scanned 9 records rather than travelling through all 50 records.
Can we see a seek scan practically?On the same above sample lets create a clustered index on the company code field and see the SQL plan again by hitting the SQL plan icon.
If you view the SQL plan for the select query with company code you will see a clustered index seek operator as shown in the below figure. In other words it says that it will use b-tree logic for searching rather than traversing row by row.
In case you have a non-clustered index on the company code it will show a non-clustered index operator as shown below. You may be wondering what the RID lookup and nested loop is in the query plan, we will come to that later on. The below figure indicates that its using the non-clustered index logical operator.
What are heap tables in SQL Server?
A table with no clustered indexes is termed as heap tables. The data rows of a heap table are not sorted, due to this there is a huge overhead of accessing heap tables.
What is RID Lookup heap in SQL query plan? (Operator Number 3)
RID lookup will be seen when you use non-clustered indexes with join queries. For instance below is a simple join with customer and address table on ‘custcode’.
SELECT Customers.CustomerName, Address.Address1
FROM Address INNER JOIN Customers ON Address.Custcode_fk = Customers.CustomerCode
If you do not put indexes on the primary table i.e. customer at this moment and you see the SQL plan, you should see the RID lookup heap as shown below. We will understand what it means, just try to get a glimpse of this operator first.

In order to understand the RID look up we need to first understand how non-clustered indexes work with clustered indexes and heap tables. Below is a simple figure which describes the working and their relationships.

Non-clustered indexes also use the B-tree structure fundamental to search data. In non-clustered indexes the leaf node is a ‘Rowid’ which points to different things depending on two scenarios:-
Scenario 1:- If the table which is having the primary key in the join has a clustered index on the join key (currently the join key is the custcode) then the leaf nodes i.e. ‘rowid’ will point to the index key of clustered index as shown below.

Scenario 2 :- if the table which is having the primary does not have a clustered index then the non-clustered index leaf node ‘rowid’ will point to actual row on the heap table. As the data is stored in a different heap table, it uses the lookup (i.e. RID lookup) to get to the actual row. Below is a query plan which has a join without clustered
indexes.

What is a bookmark lookup?
As discussed in the previous section, when query searches on a column which is not a part of non-clustered index a lookup is required. As mentioned earlier either you need to lookup on the clustered index or you need to lookup on the heap tables i.e. RID lookup.The old definition for these lookup was called as ‘Bookmark’ look up. If you are seeing SQL plan using SQL 2000 you should see a bookmark lookup in your query plan. In SQL 2000 bookmark loop up used a dedicated iterator to determine whether the table is heap table or index table and change the search logic accordingly. So cutting short index lookup and RID lookup are nothing but types of bookmark lookup.Lookups are costly operation, how can we eliminate the same?
Yes, lookups are costly operations and should be avoided as far as possible. To avoid RID lookup or clustered lookup we can use covering indexes.Below is a simple table which has two fields customer code and customer name. Clustered indexes are defined on Customer code and non-clustered index is defined on customer name as shown in the table figure below.

Lets fire the below and see the query plan for the same. Please note we are searching on the non-clustered index column.SELECT *
FROM [CustomerNew].[dbo].[Customers] where CustomerName='20 microns'As the non-clustered index needs to do a lookup on the clustered index it uses the RID lookup to get the clustered index. This lookup happens because the customer name non-clustered index does not have information about the clustered index data. If somehow we are able to make aware of clustered index data to non-clustered index the RID lookup can be avoided.

In order that the non-clustered index i.e. customer name is aware of the clustered index i.e. customer code we can create a combined non-clustered index on customer and customer doe as shown in the below figure.

Now if you generate the plan you can see that RID lookup is completely eliminated. The customer code key in this current scenario is called as the covering index.

What are covering indexes?
As explained above. It helps to remove the lookup operation.
Do we have any other efficient way of creating covering indexes?
The composite non-clustered index creation has certain draw backs:-• You cannot create composite indexes on data types like varchar(max) , XML.
• Size of the index increases the key size which further impacts performance.
• Can exceed the constraint of index key size of 900 bytes.
The best practice for creating covering index is by using the include keyword. So you create the non-clustered index as shown in the below code snippet.
You can see that we have included the customer code primary key as the part of our non-clustered index customer name and when you re-run the plan you can see how book mark lookup is removed and clustered indexes are used.
CREATE NONCLUSTERED INDEX [MyIndex] ON [dbo].[Customers]
(
CustomerName
) INCLUDE (CustomerCode) ON [PRIMARY]
-->![]()
How does size of the index affect performance?
Let us make a statement before we answer this question:- ‘The more the size of the index key, performance will also degrade accordingly’. Let’s do a small practical example to understand the impact of the same. Below is a simple customer table with customer code and customer name field and below are the data types as shown in table.* Please note that customer code has a clustered index and the data type is int.

Now fire the below SQL statement. In the below SQL script “Customer” is the database and “CustomerTable” is the table. This SQL statement gives details about number of pages which is used to store indexes.
Just to revise people who are new SQL Server pages. Pages are fundamental unit of storage. In other words the disk space allocated on the hard disk is divided in to pages. A page size is normally of 8 kb. Page has data rows of SQL Server. If you can fit your rows in one page you do not need to jump from on page to other page, which increases performance.
Now if you fire the below SQL statement it will give you number of pages consumed to store the clustered index. You can see from the results below clustered index with ‘int’ uses 12 pages.SELECT Indextable.Name
,Indextable.type_desc
,PhysicalStat.page_count
,PhysicalStat.record_count
,PhysicalStat.index_level
FROM sys.indexes Indextable
JOIN sys.dm_db_index_physical_stats(DB_ID(N'Customer'),
OBJECT_ID(N'dbo.CustomerTable'),NULL, NULL, 'DETAILED') AS PhysicalStat
ON Indextable.index_id = PhysicalStat.index_id
WHERE Indextable.OBJECT_ID = OBJECT_ID(N'dbo.CustomerTable')

Now let’s change the data type to numeric as shown in the below table.
Now if you fire the above query you can see the number of pages have increased which means SQL engine has to jump between pages to fetch the data row. In other words this decreases performance.

If you change the data type to ‘char’ or ‘varchar’ the ‘page_count’ will have the worst value. Below figure shows how the number of pages have increased because of the data type.
So concluding the more the size of the index, the more the number of pages and worse the performance. Avoid data types like ‘char’ , ‘varchar’ , ‘int’ is the preferred data type for indexes.If the clustered indexes are small we get the following advantages:-
- Reduces I/O as the number of 8 KB page decrease.
- As the size decreases caching size is increased.
- Less storage space required.
How does unique
column increase index performance?
Creating indexes on unique column values
increases performance of indexes. So unique columns always are best candidates
for clustered indexes. Let’s demonstrate how creating clustered indexes on
unique columns increases performances as compared to creating indexes on columns
with non-unique values.
Below is a simple query which is fired on the customer table which has two
fields ‘active’ and ‘customercode’. ‘customercode’ field has unique values while
‘active’ field has non-unique values , it has only two values ‘1’ and ‘0’. Below
is a SQL statement which is fired with statistics IO ON.
set statistics io on
SELECT *
FROM Customers where active=1 and CustomerCode=500008
If you fire the above statement with clustered
index on ‘customercode’ field the logical reads are ‘2’.
(1 row(s) affected)
Table 'Customers'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
If you fire the above SQL statement with
clustered index on ‘active’ field the logical reads are 16. In other words the
performance is hampered.
(1 row(s) affected)
Table 'Customers'. Scan count 1, logical reads 16, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
How important is the order of indexes?
When you create composite indexes the order of columns in composite index is also of prime importance. For instance for the below customer table we have created an index with ‘customercode’ as the first column and ‘customerid’ as the second column.

If most of the SQL statements in your project are as shown below, i.e. with ‘customerid’ as the first column in the where clause then ‘customerid’ should be the first column in the composite index.
Select * from Customer where Customerid=1 and CustomerCode=9898998
If ‘customercode’ is the first column in the where clause as shown below then the composite key should have ‘customercode’ as
the first column in your joint index key.
Select * from Customer where CustomerCode=9898998 and Customerid=1 What is the preferred data type for indexes?‘integer’ data type is the preferred data type for indexes as compared to string data types like ‘char’ , ‘varchar’. If needed
you can also choose ‘bigint’ , ‘smallint’ etc. Arithmetic searches are faster as compared to string searches.
What are indexed views and how does it improve performance?
Indexed view is a virtual table which represents an output of a select statement. In general when we create a view the view does not store any data. So when we query a view it queries the underlying base table.But when we create indexed views, result set is persisted on the hard disk which can save lot of overheads. So let’s understand advantages and disadvantages of indexed views.
Advantages
By creating indexed views you can store pre-computed values , expensive computations and join in the indexed views so that we do not need to recalculate them again and again.

Disadvantages
Indexed views are not suitable for tables which are highly transactional because SQL engine needs to also update indexed views if base table changes.
Can we see practically how indexed views increase performance?
Below is a simple query which calculates count as per ‘registerdate’ from the customers table.
SELECT dbo.Customers.RegisterDate as RDate,
count(*) as CountCust
FROM dbo.Customers
group by dbo.Customers.RegisterDate
In order to understand the same we will do the following:-
• We will run the above aggregate select query on the table without indexes and measure logical reads for the same. We will also measure logical reads for inserts on the same.
• In the next step we will create a clustered index and again record logical scan for select and insert.
• Finally we will create an indexed view and again measure logical scans for select and insert.

Benchmarking without indexes
So let’s fire the above aggregated statement without any indexes with statistics io on as shown in the below snippet.
Set statistics io on
go
SELECT dbo.Customers.RegisterDate as RDate, count(*) as CountCust
FROM dbo.Customers
group by dbo.Customers.RegisterDate
If you see the SQL plan it uses hash match.

The total logical reads for select query for the above operation is 16.
Table 'Worktable'. Scan count 0, logical
reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical
reads 0, lob read-ahead reads 0.
Table 'Customers'. Scan count 1, logical reads 16, physical reads 0, read-ahead
reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
For insert the total logical read operation is 1.
set statistics io on
insert into Customers values(429,'Shiv','1/1/2001')
Table 'Customers'. Scan count 0, logical reads 1, physical reads 0, read-ahead
reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
(1 row(s) affected)Benchmarking with clustered indexes
Now let’s go and create a clustered index on the ‘customers’ table , set the statistics io on and see the plan. You can see that it uses the index scan and uses the stem aggregate logical operator to give the results.

The select query takes 10 logical reads to execute the above SQL query.
(6 row(s) affected)
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead
reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Customers'. Scan count 1, logical reads 10, physical reads 0, read-ahead
reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
With clustered index insert takes 2 logical reads.
Table 'Customers'. Scan count 0, logical
reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical
reads 0, lob read-ahead reads 0.
(1 row(s) affected)
Benchmarking with indexed view
Now let’s create an indexed view and try to benchmark again for select and insert queries. Below is the SQL snippet to create index views. Please note ‘count’ will not work with indexed views, we need to use ‘count_big’. Some function like ‘avg’ etc are also not allowed with indexed views. CREATE VIEW IndexedView WITH SCHEMABINDING as SELECT dbo.Customers.RegisterDate as RDate, COUNT_BIG(*) as CountCust FROM dbo.Customers group by dbo.Customers.RegisterDate GO CREATE UNIQUE CLUSTERED INDEX NonInx ON IndexedView(RDate); GO
If you see the plan you will see that there are no aggregate logical operators because it’s pre-calculated in the indexed views.

The select statistics show the logical reads as 1.
Table 'Customers'. Scan count 0, logical
reads 1, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical
reads 0, lob read-ahead reads 0.
Insert logical scan is 18 for indexed views as shown below.
Table 'IndexedView'. Scan count 0, logical
reads 6, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical
reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 3, logical reads 12, physical reads 0, read-ahead
reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Customers'. Scan count 0, logical reads 1, physical reads 0, read-ahead
reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
(1 row(s) affected)
So concluding indexed views are good for select aggregate queries they increase performance. On the other hand if your table is highly transactional then indexed views can decrease your performance. Below is a simple performance impact graph which plotted using the above benchmark data. You can see how logical scan is decreased with select plus indexed views and how insert logical is increased with indexed views.

Performance is impacted in insert’s on indexed views because any updates to the base table needs to be also reflected back to indexed views which decreases performance.

Note: - If your base table is highly
transaction indexed views will decrease performance of your insert, update and
delete queries.
How do we specify index hints?
Does index hints increase performance?
References
• http://en.wikipedia.org/wiki/Query_plan• Execution plan basics by Grant FritChey http://www.simple-talk.com/sql/performance/execution-plan-basics/
• The best guide on logical and physical operators http://msdn.microsoft.com/en-us/library/ms191158.aspx
• Inside Microsoft SQL Server 2005: Query Tuning and Optimization by Kalen Delaney
Detail links which discuss Physical and logical read
• http://netindonesia.net/blogs/kasim.wirama/archive/2008/04/20/logical-and-physical-read-in-sql-server-performance.aspx
• http://msdn.microsoft.com/en-us/library/aa224763(SQL.80).aspx
• http://msdn.microsoft.com/en-us/library/ms184361.aspx
Subscribe to:
Posts (Atom)
