Saturday, April 30, 2011

.NET/ASP.NET Interview Question - Explain about WebServices and also mention difference between webservice and Remoting ?

Answer:
WebServices is a cross platform where we can invoke object which are lying on
different server or different georphical location.

Both WebService and Remoting are used for same Purpose but the difference in
Remoting is that both the server and client should be .NET platform while in
WebService the server and client can be in different platform.


Remoting is faster than WebService.

WebService can be access only through http protocol but Remoting can access by
any kind of protocol like TCP,HTTP,SMPT,FTP.


Please click here to see more .NET/ASP.NET interview questions
Regards,

Visit Authors blog for more .NET/ASP.NET interview questions

Asp.Net Interview Questions:- Single signon using forms authentication in ASP.NET

ASP.NET 4.0 feature - redirectpermanent

Friday, April 29, 2011

.NET/ASP.NET Interview Question - Can you define remoting?

Answer:
Remoting is a .NET technology where we can invoke objects which are lying on different server or different geographical location.

Below is the diagram shows the concept of Remoting.







In the above diagram, a client which is located in India want to access object
of .NET class from the server which is located in US, So this can be done by
Remoting.

Please click here to see more .NET/ASP.NET interview questions
Regards,
Visit Authors blog for more .NET/ASP.NET interview questions

Multiple Files upload in ASP.NET and ASP.NET with jQuery

Working with DataTableReader class in C#

ASP.NET 4.0 Web.config transformation

ASP.NET Authentication,Authorization,Principal and Identity objects

Thursday, April 28, 2011

Comparing implementation of MVC between J2EE Struts 2 & ASP.NET MVC 2, who is the best? Part 2

So, what’s the agenda?
In case you are new to ASP.NET MVC and J2ee Struts framework

Overall Comparison with framework

Automation using template

Passing data from controller to view

Readymade folder structure

Strong type views for intellisense

Helper classes

URL customization and action mapping

URL validation

Security

Final conclusion

Thanks Vishwa



So, what’s the agenda?


In our previous article we had compared MVC implementation for J2ee and ASP.NET without using frameworks; to view comparison click ASP.NET MVC and J2ee MVC.

In today’s world no one implements MVC without help of frameworks. So it’s either ASP.NET or j2ee, framework support is a must. Struts 2 has been the most accepted framework in J2ee while in ASP.NET the ASP.NET MVC template is the king. In this article we will compare these frameworks in terms of how they differ in implementation and their positive and negative points.

In this article we will compare both frameworks using 8 agenda points: -


  • Automation

  • Passing data between controller to views

  • URL customization

  • Security

  • Folder structure management

  • Intellisense support

  • HTML automation (helper classes).


Do watch our .Net interview questions and answers video from this link
.NET interview questions and answers, you can also catch out J2ee Design pattern videos from this link Java J2ee Design pattern.


In case you are new to ASP.NET MVC and J2ee Struts framework


In case you are not aware of the frameworks you can see the below videos to just get a quick start in both the frameworks

Following is the simple ASP.NET MVC video which displays a hello world.



Following is the simple J2EE struts video to teach struts 2 with the help of an example.




Overall Comparison with framework


Before even I start below is a full comparison sheet which gives an overall view of the comparison. The same we will be discussing in more detail as we proceed in the article.




Automation using template


The first thing which caught our eyes is the Microsoft VS IDE which has a nice readymade template from where developers can start. In MVC J2ee framework the core struts framework does not have something inherent as Microsoft MVC has it.



Said and done that it does not mean J2EE community is lagging; you can still take help of open source plug-in to get the template from
http://mvcwebproject.sourceforge.net. Below is a simple snapshot of MVC web project template.

The only difference it’s not inherent like Microsoft MVC.



Conclusion: - Definitely Microsoft wins here in terms of more user friendly interfaces and automation due to the MVC template. In j2ee struts framework we need to hunt for a third party plug which will help us to achieve the same kind automation.


Passing data from controller to view


In MVC one of the most crucial parts is transferring data from controller to view. Microsoft MVC introduces a new variable called as ‘ViewData’ which will help us to transport data between controller and view as shown in the below code snippet.

The below code snippet sets data in the controller.
ViewData["CurrentTime"] = DateTime.Now.ToString();

The below code snippet displays data on the view.



J2ee Struts framework uses the HTTP request object to pass data from controller to the view. The below code snippet sets a simple date value to the request object using the ‘setAttribute’ function. In ASP.NET MVC we cannot change the request object.
request.setAttribute(“CurrentTime”,new Date());

Later we can display the data using ‘getAttribute’.





Conclusion: - First thing both the technologies have the facility of passing data, but somehow j2ee Struts framework thought process looks more convincing. At the end of the day view gets a HTTP request, so it’s more logical to pass data using the request objects rather than creating a new variable like view data for the same.

Many ASP.NET MVC fans (which includes me) can also argue logically that the request object is created by using the data sent by the end user i.e. from the browser. This data should not be allowed to be changed in between by the web application code. The request object should only be allowed to be modified by the end user using POST and GET.

For this I will give equal point to both of them for now.

Readymade folder structure


In ASP.NET MVC the template creates a readymade folder structure (they are termed as areas) which gives a developer a clear picture of where to store the model, views and controllers as shown in the below figure.



In j2EE struts framework we do not have the clear cut vocabulary for folders as we have in ASP.NET MVC. In J2EE framework the controller and model lies in Java resources folder, while the views are saved in web content folder as show in the below diagram.



Said and done you can always manually rename and create different folder structure to have the same logical representation as we have in ASP.NET MVC , only that it’s not automated.

As per our knowledge the above logical structure is not possible currently by using any J2EE struts plug-in either.

Conclusion: - ASP.NET MVC has a slight advantage in terms of better project management due to readymade logical folder structure, while in J2ee framework we need to create them manually.

Strong type views for intellisense


In ASP.NET MVC you have a nice option where you can create strongly typed view. In other words when you add a view you can select the model with which this view will connect.



Later when you go in the view and type model keyword you can get the properties of the object in a strongly typed manner.


In java we do not have the concept of strongly typed view. If you want you can set the object in request.getAttribute and then to a type cast to get the object intellisense



Conclusion: - This feature can look very exciting for ASP.NET community but it was bit amusing for my J2ee friends (I think they are right in lot of sense also). The whole purpose of strong typed views in ASP.NET MVC is for better intellisense which we can be achieved by type casting data from view data object as shown in the below figure.

The biggest problem here is that developers can start thinking that the model is tied up the view. We understand the intention is not that, but the dialog box just makes a visual intention of doing the same. The end goal of MVC is to separate the model from the view.

So concluding it’s a good feature to get maximum from less code but just that it can be confusing for junior developers who are working on MVC. For a small automation I hope we do not end with a logical confusion about MVC fundamental.

Equal points again to both. I am not giving an extra point to ASP.NET MVC as view thing is more confusing and can be achieved by typecasting.



Helper classes


A good MVC framework will always provide helper classes to create HTML code for views.

In ASP.NET MVC we have the helper classes. For instance to create a simple HTML form in ASP.NET MVC you can use the HTML helper class as shown in the below code.



In j2ee struts framework we have tag libraries which help us to generate the HTML code as it is done by using ASP.NET MVC html helper classes.



Conclusion: - Both the frameworks have HTML helper classes. Let’s not get in to which library is better or else we will lose focus on our main comparison. So even points to both the framework on this discussion.


URL customization and action mapping


MVC is all about actions and these actions are mapped to URL. As a developer you would love to see your MVC framework have the capability of customizing and configuring the MVC URL with action mapping. Below is a simple table which explains why developers would expect customization and configuration for MVC URL’s.



In ASP.NET MVC this is achieved by using the inbuilt routing mechanism. In order to configure routes you can go to the global.asx.cs code and use the routes collection to map the URL structure with the controllers and actions.
routes.MapRoute(
              "HelloWorld", // Route name
              "Pages/RegisterAction/{1}", // URL with parameters
              new { controller = "Register", action = "RegisterAction", id = UrlParameter.Optional }); // Parameter defaults


In order to configure MVC URL in J2ee struts framework we can use the Struts XML file to the same. The below mapping is more clean than the routing collection of ASP.NET MVC. In J2ee framework we can see the mappings more better as they are mapped directly to page names.



Conclusion: - J2ee Struts framework definitely wins in terms of MVC URL configuration and mapping to the controller as its defined using XML file. This thing can be really improved in ASP.NET MVC framework. To change the mapping compiling code is more of a burden.

URL validation


In ASP.NET MVC we have the advantage of doing URL validation using regex (regular expression) before the action hits the controller. For instance below is a simple validation where before the view customer action is called we can check that the input to the action is only numeric value with 2 digits.
routes.MapRoute(
              "View", // Route name
              "View/ViewCustomer/{id}", // URL with parameters
              new { controller = "Customer", action = "DisplayCustomer", id = 0 }, new { id = @"\d{1,2}" }
);


Currently J2ee struts framework does not support the same, said and done you can always still do validation after hitting the controller using some custom logic.

Conclusion: - This is definitely a plus point for ASP.NET MVC because MVC URL’s can be invoked from any medium, via browser, via URLs etc. So we would like to ensure that appropriate validation is checked much before it hits the controller.

Security


MVC URL’s are mapped to action and they can be invoked directly which also means that they are subjected to cross site attacks, sql injection etc. ASP.NET MVC framework has provided security attributes by which we can protect our URL from such attacks.

For instance to prevent forgery attacks and cross site scripting attacks we can use the ‘HtmLAntiForgeryToken()’ as shown in the below code snippet.



In the actions later you can then check if there was any violation.
[HttpPost] [ValidateAntiForgeryToken]
public ActionResult Delete(int customerid)
{

}

You can also mark the controller by using validate input attribute to avoid CSS.
[ValidateInput(true)]
public class OurController : Controller

Critical functions on which you do not want actions to be invoked you can mark the methods as ‘nonaction’ as shown in the below code snippet.
[NonAction]
public void DoPasswordChange(string username, string newpassword)
{
   /* Rest of code unchanged */
}

In J2ee Struts framework currently we do not have any inherent security function to achieve the same. Some customized code.

Conclusion: - This is the biggest win for ASP.NET MVC framework security. Hope that J2ee struts framework in coming times has such kind of inherent security feature which will be a great extra added advantage for the framework.


Final conclusion


Below is the final conclusion. ASP.NET MVC framework out performs J2ee in 4 things while J2ee has the flexible XML URL customization which is currently not available in ASP.NET MVC. For all the other points both of them remain on the same page.

I have tried my level best to put forward both the sides and while doing so I never had in my mind that I am an ASP.NET Microsoft MVP and I should hard sell ASP.NET MVC framework. I have made by best effort to make a true comparison and see which one of them is the best. I do understand how every developer loves his technology, by any chance I have hurted….BIG SORRY.



Thanks Vishwa


Special thanks to Mr Vishwanathan Narayanan who helped me to give inputs on the J2EE side without which I would not have achieved the same. You can see his Java and j2ee design patterns videos by clicking on Java J2ee Design pattern videos.

.NET/ASP.NET Interview Question - How to Validate a Controls in ASP.NET page using JavaScript?

Answer:
Let's see an Simple example to understand.

Assuming that we have a Textbox and Button on the ASP.NET page like
below.

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
OnClientClick="return validate()" />

Now, Add the below code snippet on the page source.
<script language="javascript" type="text/javascript">
function ValidateTextBox()  
{
 if(document.getElementById("<%=txtName.ClientID%>").value == "")      
{             
 alert("Name Field Cannot be Empty");
 document.getElementById("<%=txtName.ClientID%>").focus();
  return false;    
 }
  return true;
}
</script>

Once you have completed the above steps, just run the project and see the result.
Regards,
Please click here to see more .NET/ASP.NET interview questions

Wednesday, April 27, 2011

.NET 4.0 MEF

ASP.NET 4.0 Web.config transformation

WCF Interview Question - What are the ways to do security in WCF?

Answer:

In WCF there are two types of Security, transport level security and message level security.
Transport Security: Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level. WCF uses transport protocols like TCP, HTTP, MSMQ etc and every of these protocols have their own security mechanisms. One of the common implementation of transport level security is HTTPS. HTTPS is implemented over HTTP protocols with SSL providing the security mechanism. No coding change is required it’s more of using the existing security mechanism provided by the
protocol.
Message Security: Message level security is implemented with message data itself. Due to this it is independent of the protocol. Some of the common ways of implementing message level security is by encrypting data using some standard encryption algorithm.
Below Diagram illustrate the concept of security in WCF.


Please click here to see more WCF interview questions
Regards,
Visit Authors blog for more WCF interviewquestion

ASP.NET MVC Model view controller ( MVC) Step by Step Part 4

ASP.NET MVC Model view controller ( MVC) Step by Step Part 3

ASP.NET MVC Model view controller ( MVC) Step by Step Part 2

ASP.NET MVC Model view controller ( MVC) Step by Step Part 1

c# and .NET interview questions and answers :- How are interview questio...

c# and .NET interview questions:- What are the different types of colle...

Tuesday, April 26, 2011

.NET C# Interview questions and answers :- What is Garbage Collector, G...

WCF Interview Question - What is the differenceWCF Interview Question - What is the difference between Basic httpbinding and WShttpbinding?

Answer:
Basic Httpbinding:In httpbinding Data is sent as a plain text.In other words,there is no security provided for the message when the client calls happen.

This is aimed for clients who do not have .NET 3.0 installed and it supports wider ranges of clients. Many of the clients like Windows 2000 still do not run .NET 3.0. So older version of .NET can consume this service.

It uses SOAP1.1 version.
WShttpbinding:As WsHttBinding supports WS-*, it has WS-Security enabled by default. So the data is not sent in plain text.

As its built using WS-* specifications, it does not support wider ranges of client and it cannot be consumed by older .NET version less than 3 version.
It uses SOAP 1.2 and WS-Addressing specification.
Regards,
Please click here to see more WCF interview questions

ASP.NET Interview Question:- How to do ASP.NET Tracing and instrumentation ?

Improve SQL Server performance using profiler and tuning advisor

Diffbetweentostringandconvertstring

c# interview questions :- What is the use of private constructor ?

Monday, April 25, 2011

C#/.NET interview Question - Elaborate differentiate between ArrayList and Array?

Answer:


Let’s see an example to prove the above differences.

The below is how we declare Array.

String [ ] str = new String [5]; // here you see that the length is fixed as [5]
and the data type is also defined as string.

Now, see how you can declare ArrayList.
ArrayList   str = new ArrayList (); // here you see that the length is not fixed and
is not tied up with a data type.

If you go to add data to an ArrayList you can see it takes object which is a very generic type. Due to this boxing, unboxing or casting are done. In other words data moves from stack to heap or heap to stack. If you look at Array as they are strong types boxing and unboxing are completely avoided. Therefore, Array performance is faster as compared to ArrayList.





The below diagram gives a better idea of the differences between Array and ArrayList.


Please click here to see more C#/.NET interview questions

Regards,
Visit Authors blog for more C#/.NET interviewquestion

Saturday, April 23, 2011

C# interview questions What is the difference between convert.tostring a...

c# and SQL interview question :- What is the difference between unique k...

ASP.NET and .NET Interview question video :- Wh,

Can we define abstract class as a static?

What kind of questions are asked in C# and .NET interviews ?

c# and .NET interview questions:- What are the different types of colle...

c# and .NET interview questions and answers :- How are interview questio...

ASP.NET MVC Model view controller ( MVC) Step by Step Part 4

ASP.NET MVC Model view controller ( MVC) Step by Step Part 3

ASP.NET MVC Model view controller ( MVC) Step by Step Part 3

ASP.NET MVC Model view controller ( MVC) Step by Step Part 2

ASP.NET MVC Model view controller ( MVC) Step by Step Part 1

c# and .NET interview questions and answers :- How are interview questio...

c# and .NET interview questions:- What are the different types of colle...

Friday, April 22, 2011

C#/.NET interview Question - What are the different types of collections in .NET?

Answer:
Collection: - Collections are basically group of records which can be treated as a one logical unit.
.NET Collections are divided in to four important categories as follows.

  1. Indexed based.

  2. Key Value Pair.

  3. Prioritized Collection.

  4. Specialized Collection.



Let’s begin with Indexed based and key value pair.


Indexed based: -
It helps you to access the value of row by using the internal generated index number by the collection.
Key Value Pair: - It helps you to access value by the user defined key.
Below is the example of country collection for Indexed based and key value pair.



When you want to access India through Index based you have to write like below code.

MessageBox.Show(myarray[0]); //for array
MessageBox.Show(mylist[0]);  //for list

Now, when we want to access the same output “India” by Key value pair.

MessageBox.Show(myhash["IND"].ToString()); //for hashtable

Prioritized Collection: -
It helps us to get the element in a particular sequence.



Specialized Collection: -It is very specific collections which are meant for very specific purpose like hybrid dictionary that start as list and become hashtable.
For more detail on collections watch the below video.




 

Please click here to see more C#/.NET interview questions


Regards,
Visit Authors blog for more C#/.NET interview questions

Thursday, April 21, 2011

WCF Interview Question - Define WCF?

Answer:

WCF is a unification technology, which unites the following technologies:-
1.NET remoting

2.MSMQ

3.Web services

4.COM+.
Below figure depicts WCF fundamentals pictorially.




Please click here to see more WCF interview questions

Regards,

Visit Authors blog for more WCF interview questions

Wednesday, April 20, 2011

WCF Interview Question - How will you define Service Contract,Operation Contract and Data Contract?

Answer:

Service Contract:-Service Contract is used to define the service name.
Operation Contract:-Operation contract defines the methods in the services.
Data Contract:-Data contract defines custom data types in the services.

Please click here to see more WCF interview questions
Regards,
Visit Authors blog for more WCF interview questions

Monday, April 18, 2011

WCF Interview Question - How do you do Self-Hosting?

Answer:
The following steps are followed to do Self-hosting.
Step1: //Create a URI to serve as the base address
// Address as well binding

Uri httpUrl = new Uri("http://localhost:8010/MyService/HelloWorld");
Step2: //Create ServiceHost

 ServiceHost host = new ServiceHost(typeof(ClassLibrary1.HelloWorldService),httpUrl);

Step3: //Add a service endpoint

host.AddServiceEndpoint(typeof(ClassLibrary1.IHelloWorldService) , new WSHttpBinding(), "");

Step4: //Enable metadata exchange

ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;         
host.Description.Behaviors.Add(smb);

Step5: //Start the Service

host.Open();

Step6:

Console.WriteLine("Service is host at " + DateTime.Now.ToString());        
Console.WriteLine("Host is running... Press <Enter> key to stop");         
Console.ReadLine();

Regards,
Please click here to see more WCF interview questions

Saturday, April 16, 2011

.NET and ASP.NET interview question -How will you distinguish between Cache and Application?

Answer:

Application and Cache both help to share global data and cache data across the users.but cache object is proactive and you can define dependency.In application object you can't define depenency.
Below is the code for declaring application and cache object.

CacheDependency objCacheDependency =
new CacheDependency(Server.MapPath("Banner.txt"));

Cache.Insert("Banner", strBanner, objCacheDependency
); Application["Banner"] = "strBanner";

In the above code, for Cache object you can define dependency but in Application object you can't define dependency.when the banner file is changed the Cache object can be refreshed but the application remain static and holds the old text of banner file.

Please click here to see more .NET/ASP.NET interview questions
Regards,
Visit Authors blog for more ASP.NET interview questions

Friday, April 15, 2011

.NET/ASP.NET Interview Question - Types of Validators in ASP.NET with examples.

Answer:

A validator is a computer program used to check the,validity or syntactical correctness of a fragment of code or text.
IN ASP.NET there are six different types of Validators.
1. Required Field Validator.
2. Regular Expression Validator.

3. Compare Validator.

4. Range Validator.

5. CustomValidator.

6. Validation Summary
RequiredFieldValidator:-Ensure that the control,has a value to assign in it or user does not skip an entry.
For Example:-

 <asp:Textbox id="txtMobileNumber" runat="server"></asp:Textbox>
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server"
ControlToValidate="txtMobileNumber"
ErrorMessage="Mobile Number is a required field."
ForeColor="Red">
</asp:RequiredFieldValidator>

Regular ExpressionValidator:-Ensure that the ,value of the control matches the expression of validator that is specified. This ,type of validation enables you to check for sequence of character, such as ,e-mail address, telephone number, postal code and so on.
For Example:-

 <asp:TextBox ID="txtE-Mail" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="txtPassword"
ErrorMessage="Please Enter a Valid E-Mail"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> // for internet E-Mail.
</asp:RegularExpressionValidator>

CompareValidator:-Ensure that the value of one control should be equal to value of another control.which is commonly used in password,less than,greater ,than or equal to.

For Example:-


<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
<asp:TextBox ID="txtConfirmPassword" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToCompare="txtPassword" ControlToValidate="txtConfirmPassword"
ErrorMessage="Password does not match">
</asp:CompareValidator>

RangeValidator:-Ensures that the value of the control is in specified lower and upper boundaries or specified range. You can check ranges within pairs of numbers, alphabetic characters.
For Example:-

<asp:TextBox ID="txtAmount" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="txtPassword"
ErrorMessage="RangeValidator" MaximumValue="5000"
MinimumValue="100">
</asp:RangeValidator>>

CustomValidator:-This control is used to perform user defined validations.
ValidationSummary:-This validator is used to displays a detailed summary on the validation errors that currently exist.

Regards,

Please click here to see more .NET/ASP.NET interview questions

Thursday, April 14, 2011

.NET/ASP.NET Interview Question -Why do we need Sessions?

Answer:
HTTP is a stateless protocol; it can't hold the client information on page. In other words after every request and response the server does not remember the state, data and who the user was. If user inserts some information, and move to the next page, that data will be lost and user would not able to retrieve the information.So, Session provides that facility to store information on server memory.

Below is the diagram to understand in better manner.







In the above example, when the user request the IIS server for the Page1.aspx then the request is broadcasted to the user/client browser and the connection is broken, Now when the same user request the IIS server for the Page2.aspx then again the request is broadcasted to the user/client browser but this time again the same user is treated as a new user as the connection was broken by IIS server after displaying the Page1.aspx page.

Note:-

So every single time a new request is made the same user is treated as a new one, so in order to maintain this we need Sessions.


Regards,

Please click here to see more .NET/ASP.NET interview questions

Wednesday, April 13, 2011

.NET/ASP.NET Interview Question -What is Viewstate?

Answer:

ViewState is a state management technique build in ASP.NET.

ViewState basically maintains the state of the pages between postbacks.

ViewState maintain the session within the same page.

ViewState allows the state of objects to be stored in a hidden field on the page.

Regards,
Please click here to see more .NET/ASP.NET interview questions

Tuesday, April 12, 2011

.NET/ASP.NET Interview Question -What is the difference between SessionState and ViewState?

Answer:
SessionState and ViewState are used to store data value when an respective postback occurs.

SessionState is used to store Value till the user end's the session.

ViewState is used to store Value for the current page only and when we switch to other page the data value of the previous page is lost.

Session is Server type storage whereas View is a client type storage.

Session provide higher security as compared to View as the data value is stored on server side.

Regards,

Please click here to see more .NET/ASP.NET interview questions

Monday, April 11, 2011

.NET and SQL Server Interview Question - What is trigger and different types of Triggers?


Answer:
Trigger is a SQL server code, which execute when a kind of action on a table occurs like insert, update and delete. It is a database object which is bound to a table and execute automatically.
Triggers are basically of two type’s namely "After Triggers" and "Instead of Triggers".

1.After Triggers:- this trigger occurs after when an insert, update and delete operation has been performed on a table.
“After Triggers” are further divided into three types
AFTER INSERT Trigger.
AFTER UPDATE Trigger.
AFTER DELETE Trigger.
Let us consider that we have the following two tables.
Create “Customer” table with the following field as you see in the below table.

Create “Customer_Audit” table with the following field as you see in the below table.

Cust_ID Cust_Name Operation_Performed Date_Time

The main purpose of creating “Customer_Audit” table is to record the data which occurs on the “Customer” table with their respective operation and date-time.
Let’s begin with “After Insert Trigger”:- This trigger fire after an insert operation performed on a table.
Let us see the example of “After Insert Trigger” for better understanding.

Query:-
Create Trigger TrigInsert on Customer
For insert as

declare @Cust_ID int;
declare @Cust_Name varchar(100);
declare @Operation_Performed varchar(100);
select @Cust_ID=i.Cust_ID from inserted i;
select @Cust_Name=i.Cust_Name from inserted i;
set @Operation_Performed='Inserted Record -- After Insert Trigger';
insert into Customer_Audit
(Cust_ID,Cust_Name,Operation_Performed,Date_Time)
values(@Cust_ID,@Cust_Name,@Operation_Performed,getdate());
PRINT 'AFTER INSERT trigger fired.'
Now, insert a record into Customer table:
Query:- insert into Customer values ('A-10','Danish')
Once the insert statement is successfully done, the record is inserted into the “Customer” table and the “After Trigger” (TrigInsert) is fired and the same record is also stored into “Cutomer_Audit” table.
To see the record in “Customer_Audit” table write query as below:-
Query:- select * from Customer_Audit



You can see that the same record is seen in the “Customer_Audit” table with Operation_performed and the date_time when it was updated.
Now let’s see for “After Update Trigger”:-This trigger fire after an update operation performed on a table.

Let us see the example of “After Update Trigger” for better understanding.
Query:- Create trigger TrigUpdate on Customer

For Update as

declare @Cust_ID int;
declare @Cust_Name varchar(100);
declare @Operation_Performed varchar(100);
select @Cust_ID=i.Cust_ID from inserted i;
select @Cust_Name=i.Cust_Name from inserted i;
set @Operation_performed='Inserted Record -- After Insert';
if update(Cust_Name)
set @Operation_Performed='Updated Record -- After Update Trigger.';
insert into Customer_Audit
(Cust_ID,Cust_Name,Operation_Performed,Date_Time)
values(@Cust_ID,@Cust_Name,@Operation_Performed,getdate())
PRINT 'AFTER UPDATE Trigger fired.'
Now, update a record into “Customer” table:-
Query:- update Customer set Cust_Name = 'Khan Wasim' where Cust_Code like 'A-16'
The record is updated into the Customer table and the TrigUpdate is fired and it stores a record into “Cutomer_audit” table.
To see the record Customer_Audit table write query for that.
Query:- select * from Customer_Audit



Now for, “After Delete Trigger”:-This trigger fire after a delete operation performed on a table.
In a similar way, you can code “After Delete trigger on the table.
2.Instead of Triggers:- this trigger fire before the DML operations occur, first inserted and deleted get flourished and then trigger fires
“Instead of Triggers” are further divided into three types
Instead of INSERT Trigger.
Instead of UPDATE Trigger.
Instead of DELETE Trigger.
Let us see the example of “Instead of UPDATE Trigger” for better understanding.
Query:-

CREATE TRIGGER trgInsteadOfUpdate ON Customer

INSTEAD OF update as

declare @cust_id int;
declare @cust_name varchar(100);
declare @cust_salary int;
select @cust_id=d. Cust_ID from deleted d;
select @cust_name=d. Cust_Name from deleted d;
select @cust_salary =d.Cust_Salary from deleted d;
BEGIN
if(@cust_salary >4500)
begin
RAISERROR('Cannot delete where salary > 4500',16,1);
ROLLBACK;
end
else
begin
delete from Customer where Cust_ID =@cust_id;
COMMIT;
insert into
Customer_Audit(Cust_ID,Cust_Name,Cust_Salary,Operation_Performed,Date_Time)
values(@cust_id,@cust_name,@cust_salary,'Updated -- Instead Of Updated Trigger.',getdate());
PRINT 'Record Updated -- Instead Of Updated Trigger.'
end
END
Now, update a record into “Customer” table:-
Query:- update Customer set Cust_Name = 'Khan Wasim' where Cust_Code like 'A-09'
When you try to update Customer table it will raise an error as we have use Instead of Update trigger.
Error:- Server: Msg 50000, Level 16, State 1, Procedure trgInsteadOfUpdate, Line 15

Cannot update where salary > 4500
In a similar way, you can code “Instead Delete trigger” and “Instead Insert trigger” on the table.
Regards,

Please click here to see more .NET and SQL Server interview questions

.NET and SQL Server Interview Question - Difference between Stored Procedure and Function?

Answer:

Function are compiled and executed at run time.

Stored Procedure are stored in parsed and compiled format in the database.

Function cannot affect the state of the database which means we cannot perform
CRUD operation on the database.

Stored Procedure can affect the state of the database by using CRUD operations.

Store Procedure can return zero or n values whereas Function can return only one
value.

Store Procedure can have input, output parameters for it whereas functions can
have only input parameters.

Function can be called from Stored Procedure whereas Stored Procedure cannot be
called from Function.


Regards,

Please click here to see more .NET and SQL Server interview questions

Saturday, April 9, 2011

.NET/ASP.NET Interview Question - How to implement Authentication and Authorization?

Answer:
In ASP.NET there are three way to do Authentication and Authorization.
Windows Authentication:

In this methadology ASP.NET web pages will use local windows users and groups to authenticate and authorize resources.

<authentication mode="Windows">
<forms name="
AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/" timeout="30"
/>
</authentication>

Deny access to the anonymous user in the Authorization section as follows:

<authorization>
   <deny users ="?" />
</authorization>

Forms Authentication:
This is a cookie based authentication where user name and password stored on client machine as cookie files or they are sent to URL for every request. Form-based authentication presents the users with an HTML-based web page that prompts the user for credentials. In case browser doesn't support cookies then username and password passed via URL string for every request.

<authentication mode="Forms">
<forms name=" AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/" timeout="30" />
</authentication>
<credential passwordFormat=”SHA1”>
<username="admin" password="admin">
</credential>

Deny access to the anonymous user in the Authorization section as follows:

<authorization>
  <deny users ="?" />
</authorization>

Passport Authentication:
Passport authentication is based on passport website provided by the microsoft.So when user logins with credentials it will be reached to the passport website(i.e. hotmail,devhood,windows live
etc)where authentication will happen.If authentication is successful it will
return a token to your website.

<authentication mode= "Passport"/>

Regards,

Please click here to see more .NET/ASP.NET interview questions

Friday, April 8, 2011

.NET/ASP.NET Interview Question -What are Authentication, Authorization and it's different types?

Answer:

Authentication:
Who the user is? or Authentication is process of Identifying the user is valid or not from the database.

Authorization: To Identify what kind of authority or rights does user has.

Different Types:
In ASP.NET there are three way to do Authentication and Authorization.
1)Windows Authentication:

In this methadology ASP.NET web pages will use local windows users and groups to authenticate and authorize resources.

2)Forms Authentication: This is a cookie based authentication where user name and password stored on client machine as cookie files or they are sent to URL for every request. Form-based authentication presents the users with an HTML-based web page that prompts the user for credentials.In case browser doesnot support cookies then username and password passed via URL string for every request.

3)Passport Authentication: Passport authentication is based on passport website provided by the microsoft.So when user logins with credentials it will be reached to the passport website(i.e.
hotmail,devhood,windows live etc) where authentication will happen.If authentication is successful it will return a token to your website.
Following is the video for Authentication and Authorization



Regards,

Please click here to see more .NET/ASP. NET interview questions

Thursday, April 7, 2011

.NET and Java J2EE Design pattern interview question: - What is the difference between Facade and Mediator pattern?

Answer:
Facade Design pattern

  1. Aims at simplifying interface.

  2. Existence of façade is not known to sub-system.

  3. Intermediates between client and sub stem.

Mediator Design pattern


  1. Aims at simplifying object interaction.

  2. Existence of mediator is known to objects since they interact using
    the same.

  3. Intermediates between various objects which want to interact.
Regards,

Do visit our .NET design pattern and Java J2EE design pattern interview questions.

.NET and SQL Server Interview Question - What are difference between Cluster index and Non-Cluster index?


Answer:

Both of these indexes uses "B-tree" structure but in Cluster index the "Leaf Node" actually points the physical data, but in Non-Cluster index it point’s to the "Row ID" and then the "Row ID" points to the "Leaf Node" of Cluster Index.
Below is the diagram of Cluster and Non-Clustered index.



Regards,
Please click here to see more .NET and SQL Server interview questions

Wednesday, April 6, 2011

.NET and SQL Server Interview Question - How does index makes search faster?

Answer:

For better understanding, let us consider a simple search example which shows differences between a table, declared with index and without index.
Let's first see an example for a table which is created without declaring an index and look how exactly the SQL search engine will perform action. Below diagram will give u better idea…


In the above example, SQL search engine will search from initial till it finds the respective record and once the record is found it will basically display the record. Further, When we create an index on any column of a table then the large data get divided like following B-Tree diagram, so that search becomes easier and faster.


B-tree structure of a SQL Server index


For Example-

Suppose we have to search value 25 in an indexed column, the query engine will first look in the “Root Node” to determine which node to refer in the “Branch Nodes”. In the above example first “Branch Node” has Value 1 to 20 and the second “Branch Node” has Value 21 to 40, so the query engine will go to the second “Branch Node” and will skip the first “Branch Node” as we have to search Value 25. Same like “Branch Nodes” the query engine will operate the “Leaf Node” to retrieve respected result.

Regards,

Please click here to see more .NET and SQL Server interview questions

Tuesday, April 5, 2011

.NET and SQL Server Interview Question - What is Cross Join and in which scenario do we use Cross Join?

Answer:

CROSS JOIN: Cross join is used to return all records where each row from first table is combined with each row in second table.
Cross join is also called as Cartesian Product join.

The cross join does not apply any predicate to filter records from the joined table. Programmers can further filter the results of a cross join by using a WHERE clause.
For Example:- We have following two tables.
Look at the "Product" table:



Note that the "P_Id" column is the primary key in the "Product" table.
Next, we have the "SubProduct" table:



Note that the "Sub_Id" column is the primary key in the "SubProduct" table.
There are lots of scenarios where we use the cross join(permutation and combination), below are the example of hotel where customer's gets the detail of combined product and its total cost, So that it is easy to select their respective choice.
Query:- select
Product.ProductName,SubProduct.SubProductName,(Product.Cost+SubProduct.Amount)as
TotalCost from Product cross join SubProduct
The output look like below:



Regards,
Please click here to see more .NET and SQL Server interview questions

SQL Server Interview Question - What is Normalization and its different forms?

Answer:
Normalization is the process of organizing the table's data in proper manner.

In other words Normalization is the process of breaking up data into a logical non-repetitive format that can be easily reassembled as a whole.
Normalization have 3 different forms namely 1Normal Form,2Normal Form,3Normal Form.
1Normal Form:

A table is said to be in 1NF if it satisfies the following rules.

• The table must not contain any redundant groups of data

• data must be broken up into the smallest units possible. In addition to breaking data up into the smallest meaningful values.

2Normal Form:
A table is said to be in 2NF if it satisfies the following rules.

• The table must be in 1NF

• All the non-key column must depend on primary key.

3Normal Form:

A table is said to be in 3NF if it satisfies the following rules.

• The table must be in 2NF

• A non-key field should not depend on another Non-key field.

• The data should not be derived further.
For ex:
Below table is in denormalize format:


Applying Normalization on this table.

1NF:After applying 1NF the table look like



The customer Name is divided into two units like Customer FirstName and Customer LastName.

Region field is also divided into two units like Country and State.
2NF:After applying 2NF the table look like

CountryTable

ProductTable

For avoiding duplication Create a new master table of Country and Product.
3NF:After applying 3NF the table look like

A non key field Total is removed from the table.
Regards,
Please click here to see more SQL Server interview questions

Monday, April 4, 2011

SQL Server Interview Question - What are the differences between INNER JOIN, LEFT JOIN and RIGHT JOIN in SQL Server?

Answer:

Let us Assume we have following two tables:-
Create a new table as"Customers":



Note that the "Cust_Id" column is the primary key in the "Customers" table.
This means that no two rows can have the same Cust_Id.

The Cust_Id distinguishes two persons even if they have the same name.

Next, we have the "Orders" table:


Note that the "Order_Id" column is the primary key in the "Orders" table and that the "Cust_Id" column refers to the persons in the "Customers" table without using their names.
Notice that the relationship between the two tables above is the "Cust_Id" column.
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table.
For Example:-
The Following is the example for LEFT JOIN:
Considering the above two tables:
Query:- Select * from Customers left join Orders on Customers.Cust_Id = Orders.Cust_Id
The output will look like following:


RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table.
For Example:-
The Following is the example for RIGHT JOIN:
Considering the above two tables:
Query:- Select * from Customers right join Orders on Customers.Cust_Id = Orders.Cust_Id
The output will look like following:


INNER JOIN: The INNER JOIN keyword return rows when there is at least one match in both tables.
For Example:-

The Following is the example for RIGHT JOIN:

Considering the above two tables:
Query:- Select * from Customers inner join Orders on Customers.Cust_Id = Orders.Cust_Id
The output will look like following:

Regards,
Please click here to see more SQL Server interview questions

Saturday, April 2, 2011

.NET interview question - What is Shadowing?

Answer:

Shadowing is a concept of altering the behaviour of the base class member. It basically replaces complete element of the parent class like method becomes a variable.
For example: In the below example in class1 'i' is declared as variable whereas in class2 'i' is declared as a method.

class Program
  {
      static void Main(string[] args)
      {
          class1 obj = new class1();
          class2 obj1 = new class2();
          obj1.i();                 //here i is treated as method
          Console.WriteLine(obj.i); //here i is treated as variable
          Console.ReadLine();
      }
  }
  class class1
  {
      public int i=2;
  }
  class class2 : class1
  {
      public void i()
      {
          Console.WriteLine("Hello World");
      }
  }
Regards,

Please click here to see more .NET interview questions

.NET interview questions: - What is public, private, protected, internal and internal protected?

Answer:
In the following manner we can describe the C# access modifiers: -

Public - The members (Functions & Variables) declared as public can be accessed from anywhere.

Private - Private members cannot be accessed from outside the class. This is the default access specifier for a member, i.e if you do not specify an access specifier for a member (variable or function), it will be considered as private. Therefore, string PhoneNumber; is equivalent to private string PhoneNumber;

Protected - Protected members can be accessed only from the child classes.

Internal - it can be accessed only within the same assembly.

Internal Protected - internal protected can be accessed within the same assembly
as well as in derived class.

Regards,

Please click here to see .NET and C# interview questions and answers