Saturday, November 14, 2009

Error connecting to TFS Server from client Server

PRoblem

when connect to TFS server from Visual studio 2008 to Team foundation server, we get the below error



---------------------------Microsoft Visual Studio---------------------------

Error
Team Foundation Server USNBKU183P does not exist or is not accessible at this time.
Technical information (for administrator):


HTTP code 407: Proxy Authentication Required ( The ISA Server requires authorization to fulfill the request. Access to the Web Proxy filter is denied. )

---------------------------OK ---------------------------



Solution

This problem is due to the proxy settings in IE. Please check the settings in the IE in the client machine.

Open IE (tools -> options -> connections -> lan settings) and change the proxy settings. Restart Visual studio and this worked for me.





Problem #2

Team Project creation failed With Error




Error TF30004: The New Team Project Wizard encountered an unexpected error while initializing the Microsoft.ProjectCreationWizard.Reporting plug-in.


Explanation TF30171: The Microsoft.ProjectCreationWizard.Reporting plug-in used to create the new team project could not be initialized and returned the following error: TF30224: Failed to retrieve projects from the report server. Please check that the SQL Server Reporting Services Web and Windows services are running and you have sufficient privileges for creating a project..
User Action Contact your Team Foundation Server administrator.



Also Unable to connect to Reports node from Visual studio team system as shown in the image





Solution #2
Install Visual studio 2008 Service pack 1 in the client machine to solve this issue. Required Team Explorer version to connect at client side or higher vesions
Microsoft Visual Studio 2008 Team ExplorerVersion 9.0.30729.1

Tuesday, May 12, 2009

Windows Authentication(Active Directory/LDAP) in ASP.Net

Sometimes, there may be requirement to get user name from end user information and authenticate against active directory group/LDAP in ASP.Net.

Following are the ways to achieve that
  • can be accomplished by enabling windows Integrated authentication in IIS server and disabling Anonymous access for this application. By doing the above config changes in IIS server, the user will be shown a Login window in the browser and prompting for windows user credentials.

  • Alternate way is to get the logon crdentials using C# code and validate again user information. Below is the code snippet which is used to capture the login info using windows integrated authentication and validate against AD group.


Write the following code sample in the Session start event and based on user validation, session will be started

using System.Security.Principal;
using System.Security.Permissions;

protected void Session_Start(Object sender, EventArgs e)
{
// Get the current loged in User information
WindowsPrincipal user = (WindowsPrincipal)Thread.CurrentPrincipal;

//Storing the user name in the session. If you remove the domain name, u can get user name alone
Session["userName"] =user.Identity.Name.Replace("DOMAINName\\",string.Empty);

// This session variable is used further to verify the user
Session["SecurityIsApproved"] = "false";

// Check for valid user in the AD group
if(user.IsInRole("Active Directory group name"))
{
Session["SecurityIsApproved"] = "true";
}
else
{
throw new Exception("Invalid user");
}
}

Monday, May 11, 2009

Authentication in ASP.Net

The article explains different types of Authentication available in ASP.Net framework and it's functionalities. This explains the various authentication options supported by .net and their features. Each has their own advantages as well as dis-advantages and decision of the Authentication depends on the application.


  • Forms authentication A system by which unauthenticated requests are redirected to an HTML form using HTTP client-side redirection. The user provides credentials and submits the form. If the application authenticates the request, the system issues a cookie that contains the credentials or a key for reacquiring the identity. Subsequent requests are issued with the cookie in the request headers; they are authenticated and authorized by an ASP.NET event handler using whatever validation method the application developer specifies.

  • Passport authentication Centralized authentication service provided by Microsoft that offers a single logon and core profile services for member sites.

  • Windows authentication ASP.NET uses Windows authentication in conjunction with Microsoft Internet Information Services (IIS) authentication. Authentication is performed by IIS in one of three ways: basic, digest, or Integrated Windows Authentication. When IIS authentication is complete, ASP.NET uses the authenticated identity to authorize access.

To enable an authentication provider for an ASP.NET application, you only need to create an entry for the application configuration file as follows.

authentication mode= "[WindowsFormsPassportNone]"/>

The different authentication Methods are

  • Anonymous Authentication: Used for public areas of Internet sites.Used for public areas of Internet sites. This is supported by all browsers and uses IUSR_computername account.

  • Basic Authentication: This requires a user name and password and Transmits password unencrypted.Assumption here is that the connection between the client and server computers is secure and can be trusted. Specifically, the credentials are passed as plaintext and could be intercepted easily.One advantage of the basic access authentication is that it is supported by all popular web browsers.

  • Digest authentication addresses many of the weaknesses of basic authentication.Usable across proxy servers and other firewalls.Digest Authentication offers single sign-on only to a single Web URL protection space. If users navigate to a different Web site, or even to a different server in the same site, they will usually be prompted to enter credentials again.

  • Integrated Windows Authentication: Used for private areas of intranets.Secure form of authentication because the user name and password are not sent across the network.

  • Certificates: Widely used for secure transactions over Internet.Obtain server certificates. Configure certificate trust lists (CTLs) (for first use only).

  • Forms authentication: used for personalization, where content is customized for a known user.This is achieved using SQL Server membership provider and active directory membership provider.Controls like ASP.Net login controls are used to implement forms authentication.


Differences between NTLM and Kerberos in Windows authentication

NTLM Authentication is the well-known and loved challenge-response authentication mechanism. That is the default authentication protocol of Windows NT 4.0 and earlier Windows versions. For backward compatibility reasons, Microsoft still supports NTLM in Windows Vista, Windows Server 2003.


Kerberos, on the other hand, is a more complex ticket-based authentication mechanism that authenticates the client to the server and authenticates the server to the client. While Kerberos is more secure, it can be a bit challenging to set up properly.


Kerberos has the following key advantages that make it worth consideration.

  • Performance - Kerberos caches information about the client after authentication. This means that it can perform better than NTLM particularly in large farm environments.
  • Delegation - Kerberos can delegate the client credentials from the SharePoint (For Example) front-end web server to other back-end servers like SQL Server. As an example, consider a web part that access a SQL Server database and uses a connection string that relies on the end-user credentials (i. e., “Integrated Security=SSPI”). If the targeted SQL Server is not on the same physical server as SharePoint, the database log in will fail under NTLM authentication. This is the dreaded “double-hop” scenario that affects not only SharePoint, but ASP.NET applications as well. Under Kerberos, however, the log in will succeed.
  • Kerberos supports for smart card logon where as NTLM is not.

Friday, May 8, 2009

Frequently asked interview questions in SQL Server 2005

This article explains the frequently asked (FAQs) interview questions in SQL Server 2005 with answers. This covers basic and advanced concept of SQL Server

1. What are the differences between User Defined function (UDF) and Stored Procedure?

  • Stored Procedure is pre compiled execution plan where as functions are not.
  • Stored Procedure returns more than one value at a time while function returns only one value at a time.
  • We can call the UDFs in sql statements (select max (sal) from emp) whereas SP is not so
  • Function parameters are always IN, no OUT is possibleFunctions MUST return a value, procedures need not be
2. How to Create and Run a CLR SQL Server User-Defined Function?

  • Create a SQL Server Project in Visual Studio
  • From the Project menu, select Add New Item.
  • Select User-Defined Function in the Add New Item Dialog Box.
  • Type a Name for the new user-defined function.

using System.Data.SqlTypes;

using Microsoft.SqlServer.Server;
public partial class UserDefinedFunctions{
[SqlFunction()]
public static SqlDouble addTax(SqlDouble originalAmount) {
SqlDouble taxAmount = originalAmount * .3;
return originalAmount + taxAmount;
}}

Select Deploy project from the Build menu
Note : The common language runtime (CLR) integration feature is turned off by default in Microsoft SQL Server and must be enabled in order to use SQL Server project items.
To enable CLR integration, use the clr enabled option of the sp_configure stored procedure.

EXEC sp_configure 'clr enabled' , '1'

To learn more, click here

3. What is SQL Cache Dependency in ASP.NET 2.0?

SQL cache dependencies are new technique in ASP.NET 2.0 which can automatically invalidate a cached data object just like a Dataset. when the related data is modified in the database. So for instance if you have a dataset which is tied up to a database tables any changes in the database table will invalidate the cached data object which can be a dataset or a data source.
To enable this we need a syntax that is as follows:- aspnet_regsql -ed -E -d Northwind


4.What are the different types of temporary tables in SQL Server?
  • Local temporary tables are created using a single pound (#) sign and are visible to a single connection and automatically dropped when that connection ends.
  • Global temporary tables are created using a double pound (##) sign and are visible across multiple connections and users and are automatically dropped when all SQL sessions stop referencing the global temporary table.

5.What is the difference between UNION ALL and UNION Statement?

The main difference between UNION ALL statement and UNION is UNION All statement is much faster than UNION. The reason behind this is that because UNION ALL statement does not look for duplicate rows, but on the other hand UNION statement does look for duplicate rows, whether or not they exist.

6. What is the use of Cascade and Restrict when we use DROP table in SQL SERVER?

When we are using Drop table in SQL the syntax is simple. SQL92 specifies some additional capabilities for DROP TABLE:
Drop table table_name(CASCADE / RESTRICT)

If we use cascade to drop table although it have some dependencies just like triggers, views, stored procedure, primary key, foreign key it will delete first.But if we use restrict a error message is shown on using of DROP if the table have relation Trigger or stored procedure

7. What is the use of SCHEMABINDING Option in creation of view in SQL Server?

Imagine that you have created a view without SCHEMABINDING option and you have altered the schema of underlying table (deleted one column). Next time when you run your view, it will fail. Here is when SCHEMABINDING comes into picture. Creating a view with SCHEMABINDING option locks the underlying tables and prevents any changes that may change the table schema.

E.g CREATE VIEW testview
WITH SCHEMABINDING
AS
SELECT
SalesTerritoryID, CustomerID,
FROM testtable a INNER JOIN testtable2 b
ON (a.column1 = b.column1)

8. What are the differences between DELETE TABLE and TRUNCATE TABLE commands?

  • DELETE TABLE syntax logs the deletes thus make the delete operation slow. TRUNCATE table does not log any information but it logs information about deallocation of data page of the table so TRUNCATE table is faster as compared to delete table.
  • DELETE table can have criteria while TRUNCATE cannot.
  • TRUNCATE table cannot trigger

9. What is Normalization and what are the advantages?

It is set of rules that have been established to aid in the design of tables that are meant to be connected through relationships. This set of rules is known as Normalization.

Benefits of normalizing your database will include:

  • Avoiding repetitive entries
  • Reducing required storage space
  • Preventing the need to restructure existing tables to accommodate new data.
  • Increased speed and flexibility of queries, sorts, and summaries.

10. What are the different types of Keys?

Different types of Keys

  • Primary key:- The attribute or combination of attributes that uniquely identifies a row or record.
  • Foreign Key:- an attribute or combination of attribute in a table whose value match a primary key in another table.
  • Composite key:- A primary key that consists of two or more attributes is known as composite key
  • Candidate key:- is a column in a table which has the ability to become a primary key. Candidate Key (Primary Key) is a Key which Maintains the Row Unique .
    A table may have more than one combination of columns that could uniquely identify the rows in a table; each combination is a candidate key.
  • Alternate Key:- Any of the candidate keys that is not part of the primary key is called an alternate key. Alternate Key or Unique Key is similar to PK , except it accepts null Values .

11. What is DBCC and explain it's use?

DBCC (Database Consistency Checker Commands) is used to check logical and physical consistency of database structure. DBCC statements can fix and detect problems.
They are grouped in to four categories:-

  • Maintenance commands like DBCC DBREINDEX , DBCC DBREPAR etc ,they are mainly used for maintenance tasks in SQL SERVER.
  • Miscellaneous commands like DBCC ROWLOCK , DBCC TRACEO etc ,they are mainly used for enabling row-level locking or removing DLL from memory.
  • Status Commands like DBCC OPENTRAN , DBCC SHOWCONTIG etc ,they are mainly used for checking status of the database.
  • Validation Commands like DBCC CHECKALLOC, DBCCCHECKCATALOG etc, they perform validation operations on database.


12. What are the types of replication supported by SQL SERVER 2005?

  • Snapshot Replication takes snapshot of one database and moves it to the other database. After initial load data can be refreshed periodically. The only disadvantage of this type of replication is that all data has to be copied each time the table is refreshed.
  • In transactional replication data is copied first time as in snapshot replication, but later only the transactions are synchronized rather than replicating the whole database. You can either specify to run continuously or on periodic basis.
  • Merge replication combines data from multiple sources into a single central database. Again as usual the initial load is like snapshot but later it allows change of data both on subscriber and publisher, later when they come on-line it detects and combines them and updates accordingly.

Configuring SQL server Replication using SQL Server Publication and Subscription, click here

13.What is BCP in SQL Server?

BCP (Bulk Copy Program) is a command line utility by which you can import and export large amounts of data in and out of SQL SERVER database.

14. What is the use of SQL Server Agent?

It is a Microsoft Windows service that executes scheduled administrative tasks, which are called jobs. SQL Server Agent uses SQL Server to store job information. Jobs contain one or more job steps. Each step contains its own task, for example, backing up a database. SQL Server Agent can run a job on a schedule, in response to a specific event, or on demand.

15. What are the types of Triggers?

1. DML Triggers

These triggers are fired when a Data Manipulation Language (DML) event takes place. These are attached to a Table or View and are fired only when an INSERT, UPDATE and/or DELETE event occurs. The trigger and the statement that fires it are treated as a single transaction. Using this we can cascade changes in related tables, can do check operations for satisfying some rules and can get noticed through firing Mails. We can even execute multiple triggering actions by creating multiple Triggers of same action type on a table.

  • AFTER Triggers: As the name specifies, AFTER triggers are executed after the action of the INSERT, UPDATE, or DELETE statement is performed. AFTER triggers can be specified on tables only. Here is a sample trigger creation statement on the Users table.

E.g To Create a DML trigger in T-SQL

SET NOCOUNT ON

CREATE TABLE UserTable (User_ID int IDENTITY, User_Name varchar(30), Type varchar(10))

GO

CREATE TRIGGER tr_User_INSERTON UserTable FOR INSERT AS PRINT GETDATE()

Go

INSERT UserTable (User_Name, Type) VALUES ('James', 'ADMIN')

  • INSTEAD OF Triggers INSTEAD OF triggers are executed in place of the usual triggering action. INSTEAD OF triggers can also be defined on views with one or more base tables, where they can extend the types of updates a view can support.

2. DDL Triggers

DDL triggers are new to SQL Server 2005. This type of triggers, like regular triggers, fire stored procedures in response to an event. They fire in response to a variety of Data Definition Language (DDL) events. These events are specified by the T-SQL statements that are start with the keywords CREATE, ALTER, and DROP. Certain stored procedures that perform DDL-like operations can also fire this. These are used for administrative tasks like auditing and regulating database operations.

3. CLR Triggers

A CLR triggers can be any of the above, e.g. can be a DDL or DML one or can also be an AFTER or INSTEAD OF trigger. Here we need to execute one or more methods written in managed codes that are members of an assembly created in the .Net framework. Again, that assembly must be deployed in SQL Server 2005 using CREATE assembly statement.

Creating CLR Trigger is available here

Wednesday, May 6, 2009

Frequently asked interview questions in ASP.Net web services

This article explains the frequently asked interview questions in ASP.Net web services with answers. This covers basic and advanced concept of Web service

1. What is Service Orientated Architecture(SOA)?

A service-oriented architecture (SOA) is a group of services that communicate with each other. The process of communication involves either simple data-passing between a service provider and service consumers, or a more complicated system of two or more service providers. Intercommunication implies the need for some means of connecting two or more services to each other.

Simply, SOA describes an information technology architecture that enables distributed computing environments with many different types of computing platforms and applications.

2. What are the approaches for implementing SOA?

Web services can implement a service-oriented architecture. Implementers commonly build SOAs using Web services standards (for example, using SOAP) that have gained broad industry acceptance.

Building blocks of SOA are

  • The service provider creates a Web service and possibly publishes its interface and access information to the service registry. Each provider must decide which services to expose, how to make trade-offs between security and easy availability, how to price the services, or (if no charges apply) how to exploit them for other value.
  • The service requester or Web service client

3. When do you require doing an Update a Project Web Reference?


The application contains a Web reference to an XML Web service that has been recently modified on the server; you might need to update the reference in your project. While updating web service, it generates a new proxy for the Web service so you can access the new method.

4. What are the Components of Web service?

The componets of ASP.Net web services are

  • SOAP (Simple Object Access Protocol) is a communication protocol it is for communication between applications. Its platform and language independent. It is based on XML and also help to get from Firewall.
  • WSDL(WebService description language) is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information. It explains Service, method, input and output parameters.
  • UDDI stands for Universal Description, Discovery, and Integration. It is like a "Yellow Pages" for Web Services and is designed to provide detailed information regarding registered Web Services for all vendors. It is maintained by companies like Microsoft, IBM etc


5. What are the different Web Services Protocols?

  • Http-Get protocol This is standard protocol that helps client to communicate with server with HTTP. When client send a request to server via HTTP request and reuired parameter are attached with the querystring.

    E.g http://dotnet/interview.aspx?param1=value1&param=value2 and we get the value from query string.
    Request.querystring("param1")
    Request.querystring("param2").

  • Http-Post is same as Http-Get but the difference is that in place of sending parameters onto the URL information is send with HTTP request message with some extra information which contains Parameters and their values. These Protocols is limited to sending name/value pairs.

  • SOAP: The only difference is that its relies on the XML as compares to Http-Get, Http-Post. SOAP can send not only the name/value pairs but also some complex object also as for example data types, class, objects. SOAP can also uses request/response model as Http-Get, Http-post but it is not limited to Request/Response it can also send types of message. Because its uses XML that is pure text and hence pass firewalls easily.

6. What is Web Service Enhancement 3.0 (WSE)?


Web Services Enhancements for .NET (WSE) is a product that enables you to build secure Web services quickly and easily.This gives wizard based approach for developing and securing web services.

  • The Web Services Enhancements for Microsoft .NET (WSE) has many features to augment applications built on Web services using the .NET Framework 2.0.
  • Securing Applications That Use Web Services
  • Integration with .NET Framework 2.0 and Visual Studio 2005
  • Sending Large Amounts of Data in a SOAP Message Using WSE


7. What are the different types of Security supported in ASP.Net Web services?

The type of Security supported in ASP.Net Web services

  • Anonymous
  • Username
  • Windows(Kerberos)
  • Certificate

8.What are the differences between ASP.net Web Service and .Net Remoting?

  • Web services support interoperability across platforms and are good for heterogeneous environments. .NET Remoting requires the clients be built using .NET or another framework that supports .NET Remoting which means a homogeneous environment.

  • Web services work in a stateless environment where each request results in a new object created to service the request. To maintain state between requests, you can either use the same techniques used by ASP.NET pages, i.e., the Session and Application objects. .NET Remoting supports state management options using Singleton and can correlate multiple calls from the same client and support callbacks.

  • Web services serialize objects through XML contained in the SOAP messages and can thus only handle items that can be fully expressed in XML. .NET Remoting relies on the existence of the common language runtime assemblies that contain information about data types. This limits the information that must be passed about an object and allows objects to be passed by value or by reference.

  • In terms of performance, the .NET Remoting plumbing provides the fastest communication when you use the TCP channel and the binary formatter. In the case of Web services, the primary issue is performance.

  • Web service Can be accessed only over HTTP where as .net Remoting Can be accessed over any protocol (including TCP, HTTP, SMTP and so on)

  • Web services are Easy-to-create and deploy where as Remoting is Complex to program

9. How to avoid timeout in .net web service?

For long running process, the ASP.Net web service may timeout. To avoid this time out error, increase the timeout in Server and client side

At Server Side
<configuration> <system.web>

<httpRuntime executionTimeout="300"/>

</system.web> </configuration>

The above configuration increases request timeout to 5 minutes

At Client side, increase the timeout of the web service proxy
Service1 proxy = new Service1 ();

proxy.Timeout = 300;

10. How to pass the client credentials to a web service using proxy?

To Pass the client credential at the client side using service proxy, write the following code using proxy credentials

// Create a new instance of the proxy class to an XML Web service method.

Service1 proxy = new Service1();

// Add the CredentialCache to the proxy class credentials.

proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Call the method on the proxy class.

int result = proxy.myWebMethod(5,5);

Monday, May 4, 2009

Create Hierarchical Grid using WPF. A sample Application Using WPF


This article explains the creation of the hierarchical grid using .net Windows presentation foundation concept. This also explains a sample application using WPF.

To do this, we need

  • Listview to display the items

  • Groupstyle Property to group items.

  • To get the number of items, define ContainerStyle for the GroupStyle and ItemCount will give the number of items in that category.

  • GridView to show the grid

The xaml code for the above sample looks like


<Window x:Class="WpfSampleApp.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Heirarchial Grid Sample" Height="300" Width="300">


<Grid>


<StackPanel xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='clr-namespace:System.Windows.Data;assembly=PresentationFramework'>
<StackPanel.Resources>
<XmlDataProvider x:Key="MyData" XPath="/Info">
<x:XData>
<Info xmlns="">
<Item ID="ISBN 45-F1" Name="Winner" Price="$32.05" Author="Aka" Catalog="Business"/>
<Item ID="ISBN 54-32" Name="C++ Inside" Price="$10.00" Author="John" Catalog="Language"/>
<Item ID="ISBN 14-A0" Name="Java Inside" Price="$9.00" Author="Tom" Catalog="Language"/>
<Item ID="ISBN 56-78" Name="Stock Market" Price="$8.50" Author="Bob" Catalog="Business"/>
<Item ID="ISBN AA-02" Name="Guideline for Health" Price="$19.00" Author="Lee" Catalog="Health"/>
<Item ID="ISBN A4-07" Name="C# Inside" Price="$8.50" Author="Bob" Catalog="Language"/>
</Info>
</x:XData>
</XmlDataProvider>
<CollectionViewSource x:Key='src' Source="{Binding Source={StaticResource MyData}, XPath=Item}">
<CollectionViewSource.GroupDescriptions>
<d:PropertyGroupDescription PropertyName="@Catalog" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</StackPanel.Resources>

<ListView ItemsSource='{Binding Source={StaticResource src}}' BorderThickness="0">
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0,0,0,5"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True" BorderBrush="#FFA4B97F" BorderThickness="0,0,0,1">
<Expander.Header>
<DockPanel>
<TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" Width="100"/>
<TextBlock FontWeight="Bold" Text="{Binding Path=ItemCount}"/>
</DockPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter />
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListView.GroupStyle>
<ListView.View>
<GridView>
<GridViewColumn Header="ID" DisplayMemberBinding="{Binding XPath=@ID}" Width="100" />
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding XPath=@Name}" Width="140" />
<GridViewColumn Header="Price" DisplayMemberBinding="{Binding XPath=@Price}" Width="80" />
<GridViewColumn Header="Author" DisplayMemberBinding="{Binding XPath=@Author}" Width="80" />
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</Grid></Window>



The Output of the above code looks like below



[WPFSample.JPG]

Saturday, May 2, 2009

Frequently asked interview questions in ASP.Net

This article explains the frequently asked interview questions in ASP.Net with answers


1. How to bring COM Component Compatibility in ASP.NET?

When using single-threaded apartment (STA) COM components, such as components developed using Visual Basic, from an ASP.NET page, you must include the compatibility attribute AspCompat=true in an Page tag on the ASP.NET page, as shown in the following code example.
<%@ Page AspCompat="true" Language = "C#" %>

2. What is the difference between login controls in ASP.Net and Forms authentication?

Login controls are an easy way to implement Forms authentication without having to write any code. For example, the Login control performs the same functions you would normally perform when using the FormsAuthentication class

  • prompt for user credentials
  • validate them, and
  • issue the authentication ticket


But with all the functionality wrapped in a control that you can just drag from the Toolbox in Visual Studio. Under the covers, the login control uses the FormsAuthentication class (for example, to issue the authentication ticket) and ASP.NET membership (to validate the user credentials). Naturally, you can still use Forms authentication yourself, and applications you have that currently use it will continue to run.


3.Since there can be multiple ASP.NET configuration files on one computer, how does ASP.NET configuration handle inheritance?

ASP.NET integrates the settings in configuration files (the Machine.config and Web.config files) into a single inheritance hierarchy. With a few exceptions, you can place a Web.config file wherever you need to override the configuration settings that are inherited from a configuration file located at a higher level in the hierarchy.


We can have web config file at each folder or sub folder of the web application which overrides the higher level config. To learn more about web config hierarchy, click here


4. What is the difference between Web server control and HTML control?

Server Control

  • Runs at the serverY
  • ou prefer a Visual Basic-like programming model.
  • You are writing a Web Forms page that might be used by both HTML 3.2 and HTML 4.0 browsers.

HTML control

  • Runs in the Browser
  • You prefer an HTML-like object model.
  • You are working with existing HTML pages and want to quickly add Web Forms functionality. Because HTML server controls map exactly to HTML elements, they can be supported by any HTML design environment.
  • The control will also interact with client script.


HTML Server Controls, By default, HTML elements within an ASP.NET file are treated as literal text and you cannot reference them in server-side code. To make these elements programmatically accessible, you can indicate that an HTML element should be treated as a server control by adding the runat="server" attribute. You can also set the element's id attribute to give you way to programmatically reference the control. You then set attributes to declare property arguments and event bindings on server control instances. Sample controls are HtmlAnchor, HtmlButton, HtmlForm, HtmlLink etc.

5. Explain ASP.NET State Management?

States in ASP.Net is maintained at client and server sides.

Client-Based State Management Options

  • View state : The web is stateless. But in ASP.NET, the state of a page is maintained in the page itself automatically. The values are encrypted and saved in hidden controls. This is done automatically by the ASP.NET. This can be switched off / on for a single control
    This is done using EnableViewState property for each control.

  • Control state

  • Hidden fields ASP.NET allows you to store information in a HiddenField control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control.

<asp:hiddenfield id="ExampleHiddenField" value="Example Value" runat="server"/>

  • Cookies : A cookie is a small amount of data that is stored either in a text file on the client file system or in-memory in the client browser session. It contains site-specific information that the server sends to the client along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.

To store Cookies

// Use this line when you want to save a cookie

Response.Cookies["MyCookieName"].Value = "MyCookieValue";

// How long will cookie exist on client hard disk

Response.Cookies["MyCookieName"].Expires = DateTime.Now.AddDays(1);

To get cookies

if (Request.Cookies["MyCookieName"] != null)

MyCookieValue = Request.Cookies["MyCookieName"].Value;

Server-Based State Management Options

  • Application state : ASP.NET allows you to save values using application state — which is an instance of the HttpApplicationState class — for each active Web application. Application state is a global storage mechanism that is accessible from all pages in the Web application. Thus, application state is useful for storing information that needs to be maintained between server round trips and between requests for pages.


Application["WelcomeMessage"] = "Welcome to test site.";

  • Session state: ASP.NET allows you to save values by using session state — which is an instance of the HttpSessionState class — for each active Web-application session.Session state is similar to application state, except that it is scoped to the current browser session.

Session["FirstName"] = FirstNameTxtBox.Text;

  • Profile Properties: ASP.NET provides a feature called profile properties, which allows you to store user-specific data. This feature is similar to session state, except that the profile data is not lost when a user's session expires. To learn more, click here

6. What is smart navigation in .net?

The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.

7. How do I create pages in ASP.Net for mobile devices?

ASP.NET will automatically detect the type of browser making the request. This information is used by the page and by individual controls to render appropriate markup for that browser. You therefore do not need to use a special set of pages or controls for mobile devices. Whether you can design a single page to work with all types of browsers will depend on the page, on the browsers you want to target, and on your own goals.

8.What is ASP.NET Application Life Cycle Overview?. Or What happens when a user request a page from the browser?

  • User requests an application resource from the Web server. The life cycle of an ASP.NET application starts with a request sent by a browser to the Web server (for ASP.NET applications, typically IIS). ASP.NET is an ISAPI extension under the Web server. When a Web server receives a request, it examines the file-name extension of the requested file, determines which ISAPI extension should handle the request, and then passes the request to the appropriate ISAPI extension. ASP.NET handles file name extensions that have been mapped to it, such as .aspx, .ascx, .ashx, and .asmx.

  • ASP.NET receives the first request for the application. When ASP.NET receives the first request for any resource in an application, a class named ApplicationManager creates an application domain. Application domains provide isolation between applications for global variables and allow each application to be unloaded separately. Within an application domain, an instance of the class named HostingEnvironment is created, which provides access to information about the application such as the name of the folder where the application is stored.There will be only one application domain created for an application and all the clients use the same.

  • ASP.NET core objects are created for each request. After the application domain has been created and the HostingEnvironment object instantiated, ASP.NET creates and initializes core objects such as HttpContext, HttpRequest, and HttpResponse. The HttpContext class contains objects that are specific to the current application request, such as the HttpRequest and HttpResponse objects.

  • An HttpApplication object is assigned to the request. After all core application objects have been initialized, the application is started by creating an instance of the HttpApplication class. If the application has a Global.asax file, ASP.NET instead creates an instance of the Global.asax class that is derived from the HttpApplication class and uses the derived class to represent the application.

9. Explain ASP.NET Page Life Cycle Overview?

  • Page request: The page request occurs before the page life cycle begins. When the page is requested by a user, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

  • Start: In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.

  • Page initialization: During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

  • Load: During load, if the current request is a postback (First load is not a post back or response to any client action is a postback) control properties are loaded with information recovered from view state and control state.

  • Validation: During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.
    Postback event handling If the request is a postback, any event handlers are called.

  • Rendering: Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.

  • Unload: Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

10. what is the difference between Themes and Cascading Style Sheets?

Themes are similar to cascading style sheets in that both themes and style sheets define a set of common attributes that can be applied to any page. Themes can define many properties of a control or page, not just style properties. For example, using themes, you can specify the graphics for a TreeView control, the template layout of a GridView control, and so on.

  • Themes can include graphics.
  • Themes do not cascade the way style sheets do. By default, any property values defined in a theme referenced by a page's Theme property override the property values declaratively set on a control, unless you explicitly apply the theme using the StyleSheetTheme property. For more information, see the Theme Settings Precedence section above.
  • Only one theme can be applied to each page. You cannot apply multiple themes to a page, unlike style sheets where multiple style sheets can be applied.

To apply a theme to a Web site.

In the application's Web.config file, set the Pages element to the name of the theme, either a global theme or a page theme, as shown in the following example:

<pages theme="ThemeName" />

To apply a theme to an individual pageSet the Theme or StyleSheetTheme attribute of the @ Page directive to the name of the theme to use, as shown in the following example:Theme="ThemeName"

11. What are the different types of Caching in ASP.Net?

The main difference between the Cache and Application objects is that the Cache object provides cache-specific features, such as dependencies and expiration policies.


Different types of caching using cache object of ASP.NET

  • Page Output Caching: Page output caching adds the response of page to cache object. Later when page is requested page is displayed from cache rather than creating the page object and displaying it. Page output caching is good if the site is fairly static.
    Page Output caching is easy to implement. By simply using the @OuputCache page directive, ASP.NET Web pages can take advantage of this powerful technique. The syntax looks like this:
    <%@OutputCache Duration="60" VaryByParam="none" %>

  • Page Fragment Caching: If parts of the page are changing, you can wrap the static sections as user controls and cache the user controls using page fragment caching.


12.What are the various modes of storing ASP.NET session?

  • InProc: In this mode Session state is stored in the memory space of the Aspnet_wp.exe process. This is the default setting. If the IIS reboots or web application restarts then session state is lost.

  • StateServer: In this mode Session state is serialized and stored in a separate process (Aspnet_state.exe); therefore, the state can be stored on a separate computer (a state server).

  • SQL SERVER: In this mode Session state is serialized and stored in a SQL Server database.

Session state can be specified in sessionState element of application configuration file. Using State Server and SQL SERVER session state can be shared across web farms but note this comes at speed cost as ASP.NET needs to serialize and deserialize data over network again and again.
Session_End event occurs only in “Inproc mode”. ”State Server” and “SQL SERVER” do not have Session_End event.

13. What is the difference between Absolute and Sliding expiration in Cache?

Absolute Expiration allows you to specify the duration of the cache, starting from the time the cache is activated. The following example shows that the cache has a cache dependency specified, as well as an expiration time of one minute.

Cache.Insert("key","value",dependencies,DateTime.Now.AddMinutes(1),null)

Sliding expiration: The following code specifies that the cache will have a sliding duration of one minute. If a request is made 59 seconds after the cache is accessed, the validity of the cache would be reset to another minute:

Cache.Insert("key","value",dependencies,DateTime.Now.AddMinutes(1), TimeSpan.FromMinutes(1))

14. Compare Datagrid, Datalist and repeater?

A Datagrid, Datalist and Repeater are all ASP.NET data Web controls. They have many things in common like DataSource Property, DataBind Method ItemDataBound and ItemCreated
Itemtemplate can be used for design. Datagrid has a in-built support for Sort, Filter and paging the Data, which is not possible when using a DataList and for a Repeater Control we would require to write an explicit code to do paging.Repeater is fastest followed by Datalist and finally datagrid.

15. What are WebFarm and WebGarden Differences?

Web farms are used to have some redundancy to minimize failures. It consists of two or more web server of the same configuration and they stream the same kind of contents. When any request comes there is switching / routing logic(Load Balancer) which decides which web server from the farm handles the request. For instance we have two servers “Server1” and “Server2” which have the same configuration and content. So there is a special switch which stands in between these two servers and the users and routes the request accordingly.

The routing logic can be a number of different options:-

  • Round-robin: Each node gets a request sent to it “in turn”. So, server1 gets a request, then server2 again, then server1, then server2 again.
  • Least Active: Whichever node show to have the lowest number of current connects gets new connects sent to it. This is good to help keep the load balanced between the server nodes
  • Fastest Reply: Whichever node replies faster is the one that gets new requests. This is also a good option - especially if there are nodes that might not be “equal” in performance.

Web Garden: All requests to IIS are routed to “aspnet_wp.exe” for IIS 5.0 and “w3wp.exe” for IIS 6.0. In normal case i.e. with out web garden we have one worker process instance (“aspnet_wp.exe” / “w3wp.exe”) across all requests. This one instance of worker process uses the CPU processor as directed by the operating system. But when we enable web garden for a web server it creates different instances of the worker process and each of these worker process runs on different CPU. In short we can define a model in which multiple processes run on multiple CPUs in a single server machine are known as a Web garden. To configure Web Garden for asp.net application in web config

<processModel enable ="true" webGarden="true" cpuMask="12" />

cpuMask Specifies which processors on a multiprocessor server are eligible to run ASP.NET processes. For example, if you want to use the first two processors for ASP.NET of a four-processor computer, type 1100. then convert to binary to decimal.

Thursday, April 30, 2009

Creating sample Windows communication Foundation application using .net

This article describes how to create and run a sample Windows Communication Foundation with .NET Framework 3.0 and above. This shows step-by-step in .net sample project to create a WCF Service and host the service in a console application.


To develop a WCF application, we need

  • WCF Service library which implements the Service using ServiceContract, OperationContract, DatatContract. This has the core logic of the service

  • Service Host using ServiceHost. The Service can be hosted in a Console application, Windows Service , IIS or Windows Process Activation Service (WAS)

  • Create a client and consume the service


Step by step to create sample WCF application and consume it

1. Open Visual studio and Create a WCF service Library project as shown.

[WCF1.JPG]

2. Once the project is created, visual studio by default creates ServiceContract with name IService1, OperationContract and DataContract.

[WCF2.JPG]

For sample purpose, we use the default contracts created by visual studio.

3. Implement the operation contract. This operation is used by the WCF clients to consume the service
public class Service1 : IService1 {

public string GetData(int value) {

// Todo Custom code here

return string.Format("Sample WCF application. you have Entered {0}", value);

}

}

4. Configure the endpoints,base address using app.config file as below

[WCF3.JPG]

5. create a new windows console application(WCFHostSample) to host the WCF Service (WcfServiceLibrarySample) as shown below.


[WCF4.JPG]

Add the reference to the WcfServiceLibrarySample library as shwon below.

[WCF5.JPG]

6. Include the following namesapce in WCF host sample and add the code in console application for hosting the service

using System.ServiceModel;

using System.ServiceModel.Description;

static void Main(string[] args)
{
// This is to host the WcfServiceLibrarySample
ServiceHost servicehost = new ServiceHost(typeof(WcfServiceLibrarySample.Service1));
servicehost.Open();
Console.WriteLine("Service started.....Press to terminate service.");
Console.ReadLine();
servicehost.Close();
}

Note : create an app.config for this host console application(WCFHostSample). Copy and paste the app.config (with end points and behavior nodes) created from service library to console application since the service library is loaded from this console application and uses the configuration of host console application.

Alternate way to host the WCF service without configuration file(app.config) and using ServiceMetadataBehavior as descibed below

static void Main(string[] args)
{
ServiceHost servicehost = new ServiceHost(typeof(WcfServiceLibrarySample.Service1));
//// A channel to describe the service.
ServiceMetadataBehavior metadataBehavior;
metadataBehavior = servicehost.Description.Behaviors.Find ServiceMetadataBehavior ();
if (metadataBehavior == null)
{
// This is how I create the proxy object add behavior to the service
metadataBehavior = new ServiceMetadataBehavior();

// configure url
metadataBehavior.HttpGetUrl = new Uri("
http://localhost:8731/WcfServiceLibrarySample/SampleApp");
metadataBehavior.HttpGetEnabled = true;

// add behviour to the host
servicehost.Description.Behaviors.Add(metadataBehavior);
}
servicehost.Open();
Console.WriteLine("Press to terminate service.");
Console.ReadLine();
servicehost.Close();
}

7. Start the WCF host console application as shown in the below. This should be running to consume the service from an client.

[WCF5a.JPG]

Note: Once the Service host is closed, then WCF service cannot be consumed from client


8. Create a windows console application (WCFClientSample) for consuming the WCF service hosted using the endpoint.


[WCF6.JPG]

9. Add Service reference using the url configured in the application configuration file and name the reference( as WCFSampleRef) as shown below.

[WCF7.JPG]

10. Then write the following code in WCF client project to consume the WCF service operations

static void Main(string[] args)
{
// create intstance of the WCF proxy
WCFSampleRef.Service1Client serviceproxy = new WCFClientSample.WCFSampleRef.Service1Client();
// CAll the Service GetData Method
Console.WriteLine(serviceproxy.GetData(100).ToString());
Console.ReadLine();
}

11. Then run the client and it get the following output

[WCF8.JPG]

Tuesday, April 28, 2009

Table Valued Parameters in SQL Server 2008

This summary is not available. Please click here to view the post.

SQL Server 2005 - Tips for Optimizing SQL Server Query Performance

The following are some tips to improve the performance of SQL Server queries.

1. Turn on the execution plan, and statistics. Then analyse the query performance
The first step is to use the tools that help you determine whether a query done one way is better than another. By comparing the original query to a new query that we come up with is the best way to evaluate the benefits of any changes.

To do this, go into SQL Server Management Studio and select the Query menu. Select the “Include Actual Execution Plan.”

[SqlServer1.JPG]

Next, turn on statistics. Type the following statement:

SET STATISTICS IO ON;

To counteract the above two you should also compare the actual execution times. To do this, execute the following statement:

SET STATISTICS TIME ON;

After running a simple query, analyze the query execution plan for optimizing the query as below.

[sqlserver2.JPG]

After getting the execution plan, do the following

  • Analyzing Execution Plans
  • Estimated Cost of Execution

2. Use Clustered Indexes in appropriate columns
Having the clustered index on the primary key is sometimes not the most efficient place for the clustered index to be. A clustered index is the most per formant type of index.
The scenario is

  • Generally, the whole table is sorted according to the clustered index which is created by default while creating Primary key.
  • If the table is involved in lots of joins based on the primary key, it is probably the right place for it to be.
  • But in some cases that you are continually filtering or grouping on other columns in a table, then you should possibly consider changing the primary key index to Non-Clustered, and putting the clustered index on those filtered or grouped columns.


In such cases, drop the clustered index from PK and create new clustered index for other column.

ALTER TABLE testtable
DROP CONSTRAINT PK_testtable
GO
ALTER TABLE testtable
ADD CONSTRAINT PK_testtable
PRIMARY KEY NONCLUSTERED (testcolumn);

Then the following statement adds a new clustered index to a table for the required column other than primary key where it involved lot of joins.

CREATE CLUSTERED INDEX MyClusteredIndex
ON testtable (testcolumnID)

3. Use Indexed views

Indexed Views have been around for a while for improving the performance using SCHEMABINDING option and create index on the views.
Imagine that you have created a view without SCHEMABINDING option and you have altered the schema of underlying table (deleted one column). Next time when you run your view, it will fail. Here is when SCHEMABINDING comes into picture. Creating a view with SCHEMABINDING option locks the underlying tables and prevents any changes that may change the table schema.

CREATE VIEW testview
WITH SCHEMABINDING
AS
SELECT testcolumn1, testcolumn2,
FROM testtable a INNER JOIN testtable2 b
ON (a.column1 = b.column1)

Note the use of the schema binding attribute. This prevents you from changing underlying tables while this view exists, and is necessary if you want to add an index.

CREATE UNIQUE CLUSTERED INDEX Idxtestview
ON testview (
testcolumn1, testcolumn2
)

4. Use Covering Indexes

Covering indexes are a feature that was newly added to SQL 2005. Basically, you can create an index optimized for the query itself based on joins, filters and grouping, and then add additional columns that can be retrieved directly from the index for use in select statements, as follows:

CREATE NONCLUSTERED INDEX TestIndex ON salestable (OrderId)INCLUDE (Quantity, UnitPrice)

If queries are executed on the OrderId column, the index will be used, and if the only other columns being retrieved are Quantity and UnitPrice, then the query optimizer doesn’t need to retrieve any extra columns from the underlying table. It can just use the index. Because the query optimizer doesn’t need to query the original table, performance is improved.

5. Keep your clustered index small in the table

One thing you need to consider when determining where to put your clustered index is how big the key for that index will be. So if you have a large clustered index on a table with a decent number of rows, the size could blow out significantly. In the case where there is no clustered index on a table, this could be just as bad, because it will use the row pointer, which is 8 bytes per row.

6. Avoid cursors

Cursors are less performant because every FETCH statement executed is equivalent to another SELECT statement execution that returns a single row. The optimizer can’t optimize a CURSOR statement, instead optimizing the queries within each execution of the cursor loop, which is undesirable. Given that most CURSOR statements can be re-written using set logic, they should generally be avoided.
Each time when the FECTH is executed, it causes a roundtrip to the server and hence performance is degraded.

7. Archive old data using Replication or Backup
If you want to improve query performance, give the optimizer less work to do. If you can cut down the number of rows the query has deal with, then performance will improve.

This can be done in the following ways

  • One can also create audit triggers to move historical data into other tables for this reason.
  • Don’t need your data after a certain period of time, back up your database and remove the data.
  • Also we can use SQL Server Replication technique to back up the data


8. Partition your data correctly
These days, you don’t actually have to move old data out of a table to improve query performance. You can partition your table into a number of data segments based on a partition function. The query optimizer can use the partition function to look at rows only on the most appropriate file group. To create partitions, you need a partition function and a partition scheme.

CREATE PARTITION FUNCTION TestPartitionFunction (int) AS RANGE RIGHT FOR VALUES (1, 100, 1000)

Once the partition function is created, you can then apply the function to a partition scheme for a table.
CREATE PARTITION SCHEME TestPartitionSchemeAS PARTITION TestPartitionFunctionTO (filegrp1, filegrp2, filegrp3, filegrp4)

Then it’s just a matter of creating the table to use the partition scheme on the column you decided to partition on:
CREATE TABLE myPartitionTable ( Col1 int, Col2 varchar (100))ON TestPartitionScheme (col1)

9. Remove user-defined inline scalar functions
Inline scalar functions are convenient if you want to return a single value, but at the expense of performance. They look somewhat like stored procedures, and they can be used in SQL statements. The problem is that they are not expanded and therefore not optimized into the query plan by the query optimizer. Queries like this may appear to be performant in the Execution plans and also in the IO statistics, but when you run the query, it can perform really badly.


CREATE FUNCTION dbo.fnGetPostalCode ( @Suburb varchar (100), @State varchar (10)) RETURNS int AS BEGIN

RETURN ISNULL (( SELECT Postal Code FROM dbo.PostalCode WHERE Suburb = @Suburb AND State = @State ), -1);

END

The following statement will only perform a clustered index scan, not a seek, and on a big table this could seriously affect performance.

SELECT s.SalesPersonID, s.SuburbName, s.State, dbo.fnGetPostalCode (s.SuburbName, s.State) AS PostalCode FROM dbo.SalesPerson

You can have a look at the details by clicking on SQL Server Management Studio’s Query menu, and selecting “Include Actual Execution Plan”
One way to get around this is to simply inline the underlying queries from the function, as follows:
SELECT s.SalesPersonID, s.SuburbName, s.State, ISNULL ((SELECT PostalCode FROM dbo.PostalCode WHERE Suburb = s.SuburbName AND State = s.State), -1) AS PostalCode FROM dbo.SalesPerson

Inline the SQL statement will perform significantly better than the inline function.

10. Use APPLY in SQL queries
The apply statement was created for the situation where you put multiple inline nested queries in the one statement. For example, take the following statement:

SELECT soh.SalesOrderID, Quantity= (SELECT TOP 1 (Quantity) FROM SalesOrderDetails WHERE SalesOrderID = a.SalesOrderID), UnitPrice= (SELECT TOP 1 (UnitPrice) FROM SalesOrderDetails WHERE SalesOrderID = a.SalesOrderID)FROM SalesOrderHeader a

This performs an extra query, retrieving data from another table using the same criterion. This can now be replaced with the following:

SELECT b.SalesOrderID, b.OrderDate, a.* FROM SalesOrderHeader b CROSS APPLY ( SELECT TOP (1) c.UnitPrice as UnitPrice, c.Quantity as Quantity FROM SalesOrderDetail c WHERE c.SalesOrderId = b.SalesOrderId ORDER BY c.Quantity DESC) as a

a.* mentioned in the above query returns Quantity and UnitPrice. We can also refer as a. UnitPrice and a.Quantity.

11. Use computed columns

Computed columns are derived from other columns in a table. By creating and indexing a computed column, you can turn what would otherwise be a scan into a seek.
For example, if you needed to calculate SalesPrice and you had a Quantity and UnitPrice column, multiplying them in the SQL inline would cause a table scan as it multiplied the two columns together for every single row. Create a computed column called SalesPrice, then index it and the query optimizer will no longer need to retrieve the UnitPrice and Quantity data and do a calculation.
Creating computed column syntax

CREATE TABLE sales (SALESORDERID int, UNITPRICE int, QUANTITY int, SALESPRICE as (UNITPRICE * QUANTITY))

where SALESPRICE is a computed column

Inserting the values into other columns automatically inserts value in SALESPRICE which is a computed column.
INSERT INTO sales (SALESORDERID, UNITPRICE, QUANTITY) VALUES (1, 100, 2)

12. Use the correct transaction isolation level

If there are a lot of rows in your table, multiple concurrent requests to that table could cause contention if the correct transaction isolation level is not set. If requests are repeatedly blocked, it could be time to consider whether to change.

For example, READ UNCOMMITED is equivalent to dirty reads, or NOLOCK. That is, if a transaction is in the middle of processing and you read a row, the data may not be valid, especially if multiple inserts/updates are occurring that require atomicity. This is the most per formant and it ignores locking altogether, but is generally not allowed by good design and is a special case.

With READ_COMMITTED_SNAPSHOT, it specifies that any data read by the transaction will be the transitionally consistent version of the data that existed at the start of the transaction. Internally, it makes a versioned copy of the data and this is placed in tempdb until the transaction has competed. Except when the database is being recovered, snapshot transactions do not request locks when reading data, and therefore do not block other transactions from writing data. Transactions writing data also do not block other transactions reading data.

There are various other types of transaction options, including REPEATABLE_READ and SERIALIZABLE amongst others that you can look at to determine whether they are appropriate for your needs.

Microsoft suggested some check list for SQL Server performance is available here

.Net framework Frequently asked interview questions

Frequently asked interview questions with answers are explained below. This helps to understand about .net framework basics

1. Difference between Mutable and immutable objects
An object qualifies as being called immutable if its value cannot be modified once it has been created. For example, methods that appear to modify a String actually return a new String containing the modification. Developers are modifying strings all the time in their code. This may appear to the developer as mutable - but it is not. What actually happens is your string variable/object has been changed to reference a new string value containing the results of your new string value. For this very reason .NET has the System.Text.StringBuilder class. If you find it necessary to modify the actual contents of a string-like object heavily, such as in a for or foreach loop, use the System.Text.StringBuilder class System.String is immutable.

System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

2. Difference between interface and abstract class
In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete.
In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.

3. Difference between Struct and a Class
Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.

4. Debug class and Trace class difference?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

5. assert() method in Debug and Trace class
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
For Release mode, need to use
Trace.Assert(false, "Message to be displayed");

6. How to call Win32 API from a .NET Framework program?
Yes. Using platform invoke, .NET Framework programs can access native code libraries by means of static DLL entry points.

Here is an example of C# calling the Win32 MessageBox function:

using System;
using System.Runtime.InteropServices;
class MainApp {
[DllImport("user32.dll", EntryPoint="MessageBox")]
public static extern int MessageBox(int hWnd, String strMessage, String strCaption, uint uiType);
public static void Main() {
MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 );
}
}

7. Difference between Early Binding and late binding
Early binding occurs at compile time where as late binding occurs at Run-time.
With early binding, Visual Basic .NET uses type information that is available about the Office application in question to bind directly to the methods or properties that it needs to use.

This occurs at compile time
objApp = New Excel.Application()

In contrast to early binding, late binding waits until run time to bind property and method calls to their objects.

This occurs at run time and .net reflection is used to invoke the objects and methods dynamically
objApp = CreateObject("Excel.Application")

8. supportedruntime Element in .net framework
Specifies which versions of the common language runtime the application supports. This element should be used by all applications built with version 1.1 or later of the .NET Framework. This should be specified in exe.config or web config file


[Config1.JPG]

9. Delay Signing in .Net

During development process you will need strong name keys to be exposed to developer which is not a good practice from security aspect point of view. In such situations you can assign the key later on and during development you can use delay signing

[assembly:AssemblyKeyFileAttribute("myKey.snk")]

[assembly:AssemblyDelaySignAttribute(true)]

The compiler inserts the public key into the assembly manifest and reserves space in the PE file for the full strong name signature. The real public key must be stored while the assembly is built so that other assemblies that reference this assembly can obtain the key to store in their own assembly reference.

Because the assembly does not have a valid strong name signature, the verification ofthat signature must be turned off. You can do this by using the –Vr option with theStrong Name tool. The following example turns off verification for an assembly calledmyAssembly.dll.
Sn –Vr myAssembly.dll

Just before shipping, you submit the assembly to your organization's signing authorityfor the actual strong name signing using the –R option with the Strong Name tool.

Sn -R myAssembly.dll sgKey.snk

The above example signs an assembly called myAssembly.dll with a strong nameusing the sgKey.snk key pair.

10. Native Image Generator (Ngen.exe)

The Native Image Generator utility (Ngen.exe) allows you to run the JIT compiler on your assembly's MSIL and generate native machine code which is cached to disk. After the image is created .NET runtime will use the image to run the code rather than from the hard disk. Running Ngen.exe on an assembly potentially allows the assembly to load and execute faster.

ngen.exe install assemblyname.dll