Questions-For-Dotnet-Professionals - HTML Fresher
Questions-For-Dotnet-Professionals - HTML Fresher
Questions-For-Dotnet-Professionals - HTML Fresher
Last week I attended an interview with Infosys, Chennai. When I entered the compound,
there were very many candidates. The atmosphere and culture in Infosys was very nice.
Please find the original article here : http://sibeeshpassion.com/Infosys-InterviewQuestions-For-DotNet-Professionals.html
You can read another series of interview questions here : http://www.csharpcorner.com/UploadFile/65794e/dot-net-interview-questions-for-experienced-andfresher/
Background
I have attended many interviews in my life. But the interview with Infosys was something
different. I thought to share that experience with you all.
Points to be remember
(There are some mistakes I made in the interview. I don't want you to do the same :) )
1. Please ensure that you are maintaining eye contact with the interviewer.
2. Be confident of what you say. Don't change your answer if the interviewer tries to
make you do so.
3. Please avoid the unwanted examples.
4. Please never use any other technical terms that may provoke the interviewer into
asking questions about.
5. If you don't know the answer, please say "I don't know". It is always better to say
so instead of going with the wrong answer.
You can find more tips here: How to Prepare for a Job Interview
Questions asked and answers
(Here I am giving the answers that I answered .)
1. Tell me about yourself?
A. You can find many answers to this question in the internet. Please see the following
link:
Tell me about yourself
2. What is your role in your project? What is the team size?
A. I said "My main role is coding, unit testing, big fixing and maintenance. My team size is
7".
3. What is the hierarchy of your team?
A. First I was confused by this question. Then I answered "Project Manager, Team Leader,
Software Engineers, Trainees".
4. Describe the projects that you have worked on?
A. I described them. Please include the technologies you used in your projects and what
kind of architecture (for example: 3-tire, n- tier) you used.
5. What is the employee size in your company? You don't need to be accurate. You can
provide the approximate value.
A. I said "150 to 200".
Then he moved to the programming section.
6. Write an algorithm and program to determine whether or not a word is a palindrome.
We can do it in either of the following two ways:
a) Using a built-in function as in the following:
1.
2.
3.
strReal = Console.ReadLine();
4.
5.
Array.Reverse(tmpChar);
6.
strRev=new string(tmpChar);
7.
if(strReal.Equals(strRev, StringComparison.OrdinalIgnoreCase))
8.
9.
10. }
11. else
12. {
13.
14. }
15.
Console.ReadLine();
2.
3.
try
4.
5.
int min = 0;
6.
7.
while (true)
8.
9.
10.
return true;
11.
12.
13.
if (char.ToLower(minChar) != char.ToLower(maxChar))
14.
15.
return false;
16.
17.
min++;
18.
max--;
19.
20.
21.
catch (Exception)
22.
23.
24.
throw;
25.
26.
}
}
1.
using System;
2.
using System.Collections.Generic;
3.
using System.Linq;
4.
using System.Text;
5.
6.
namespace FindCountCharOccurance
7.
8.
class Program
9.
10.
11.
12.
13.
14.
strOccur = Console.ReadLine();
15.
16.
17.
strChar = Console.ReadLine();
18.
19.
20.
Console.ReadLine();
21.
22.
23. }
Please see this for more suggestions: count the number of characters in a string.
8. Next he gave me a program like the following and asked me what the output of this
will be.
1.
2.
public class A
{
3.
4.
5.
6.
7.
A. I said "Here we have a constructor A; a constructor should not have a return type. So
the code above will throw a compilation error."
9. What may be the output of the following program?
1.
using System;
2.
using System.Collections.Generic;
3.
using System.Linq;
4.
using System.Text;
5.
6.
namespace RefClass
7.
8.
class Program
9.
10.
11.
12.
13.
Console.ReadLine();
14.
15.
16.
17.
public class A
18.
19.
public A()
20.
21.
22.
23.
24.
25.
26.
27.
public B()
28.
29.
30.
31.
32. }
class Program
{
3.
4.
5.
6.
Console.ReadLine();
7.
8.
9.
10.
public class A
11.
12.
public A()
13.
14.
15.
16.
17.
public A(int x)
18.
19.
20.
21.
}
}
22.
23.
24.
25.
public B()
26.
27.
28.
29.
}
}
1.
alert('5' + 5 + 5);
2.
alert(5 + 5 + '5');
3.
4.
alert(5 + '5' );
That was little tricky at that time. For a while I thought, and I just wrote the question to a
paper, and replied.
1.
alert('5' + 5 + 5);
Output= 555
2.
alert(5 + 5 + '5');
Output=105
3.
4.
alert(5 + '5' );
Output=55
Hmmm finally he said "You are selected for the next round" :)
Next was the direct HR round. That was a simple round. He just asked me to fill in some
forms.
Finally they sent me an Offer Letter :)
Wish you good luck.
10
I gave an exmple of beginning a transaction and ending a transaction within a try catch
block, if the try raises an error then a rollback will occur within the catch.
Find the third highest salary from a table.
It's a very popular one. I provided an answer with a nested query. First fetch the top 3
highest salaries from the table then filter and pick the minimum one from them. He
asked me to find another method, but at that moment I could not think of an alternative.
Give an example of a nested query.
I have referred to the previous example (of the third highest salary) since I wrote it using
a nested query.
Temporary table and table variable syntax
I provided an example with # and @ symbols.
Difference between local temp table and global temp table
Local temp table (starts with #) has the current user's session scope wherea a global
temp table (starts with ##) has all user's scope.
Save point of transaction
A Save point is needed to rollback up to a certain point.
One insert statement to enter multiple rows.
Written using the following insert command.
Insert into <table> values(1,'a')(2,'b')
I had forgotten to provide a comma between each value pair. He point it out and
corrected me.
What are ldf and mdf files
They are two files of SQL Server and I explained a little about them.
Syntax of function and trigger
I wrote the basic syntax of them. I made the mistake of not writing returns in the
functions. He pointed it out and told me.
Types of trigger
I explained two types of triggers (instead of and after) and a little explanation about
them, when they fire and so on and group by and and having clauses.
I gave an answer with one example to calculate the sum of a salary group by
department. Where we can add a having clause to filter it again.
Find duplicate records
After a little struggle, I wrote one but it was not perfect. (Hmm,. my grip had slipped a
little.)
11
What is a view?
I answered with a small example and also added how to make an index on a view.
Difference between primary key and unique key
It's a very common and popular question. I provided two differences. That is what he was
expecting.
What is a candidate key?
I answered with a small example of a student table. Where roll is the primary key and
registration number is the candidate key.
Then he began to ask about .NET and C# (though it was very basic).
Draw architecture of .NET framework
I had drawn a complete architecture. He told me to point out the location of Entity
Framework and how LINQ provides abstraction on ADO.NET classes.
Latest version of C#
I directly came to the point that he wanted. Yes, asynchronous programming.
What is CLS and CTS?
Discuss them with a little technical knowledge.
How to see IL code?
Answered about ILDASM.
How to collect garbage?
Started to talk about GC.Collect() (it's an overloaded function) and about generation, how
objects are promoted from one generation to another generation and so on.
Is there any other method?
I was taking time to find an alternate to GC.Collect(). After a few moments I suddenly
discovered, hey the finalize dispose pattern is there to collect garbage (although it's not
collection , it's nothing but disposing after use). And he was waiting for that.
How can multiple inheritance problems be overcome?
I provided a small structure and implementation of a class of multiple interfaces.
What is polymorphism and its Types?
I gave a definition of polymorphism with a classic example. The following is the example.
"Let's think about me. Now I am giving an interview, so you are my interviewer and I am
the interviewee. Now when I go to my room, with respect to my roommate, I am his
friend. And I talk to my mother after dinner on the phone (it's my daily routine for the
past 7 years).
I am her son. So, I am not changing but my identity is changing with respect to people
and places. It's nothing but polymorphism. The technical definition is "Ability to take
12
more than one form". At first I was wondering what is its type but then it came to me,
okay runtime and compile time. Actually I had forgotten the terminology. Then I showed
an example of function overloading and overriding.
Then a few more was there but I have forgotten them, uh oh; no it is not coming to mind.
Then we started to talk about ASP.NET but not much.
What is MVC pattern?
Though, I am new to it and currently learning. I have drawn a picture with three bubble
shapes ( yes, a classic MVC model picture, green, yellow and red colors, do you
remember?) and began to discuss them little. Then I was trying to bring him into my safe
zone. (Ha Ha, in ASP.Net web forms.)
How does viwestate work? Internally how does it store data?
I answered with the basic mechanism and how it stores data in key and value pairs and
it's disadvantages when the page is heavy.
How to bind DataTable in grid and how to allow pagin
I answered the dataSource property but forgot about the paging properly. I answered,
most probably it's Allow Paging.
Difference between DataView and DataGrid?
I was thinking and wondering for the answer of how they are related with each other.
What is Dataview? I asked, sir, what is the Dataview? Is it a control? He replied, yes it's a
control in the data section. Again I started to think and fnally I said sir, there is no control
like this. (Or at least I have not used it). Then we discovered that he was a little incorrect
and instead of DataView it is a Data Pager.
What is 3-tier architecture?
I showed a diagram with data flow from layer to layer and the forms of data.
Which namespace is used to make platform independent data access
mechanisms?
I answered System.data.commn. Yes, it contains the DBFactory class.
How to solve the jQuery conflict problem?
I am hearing this question for the very first time, so obviously I was unable to provide an
answer. He said something about a noconflict method. (I need to check that.)
A few more were there but at this moment they are not coming to mind.
So, it ended peacefully and I got confirmation for the next round within a few minutes.
So dear reader, here I have tried to show one motion picture of an interview session from
my experience and knowledge.
The answer I have written here is not a complete and full answer. I have just tried to
touch each and every question with important keywords. If you find any wrong question
or answer then please correct me.
13
14
System.Web.UI.Page.Culture
What's the difference between Codebehind="MyCode.aspx.cs" and
src="MyCode.aspx.cs"?
CodeBehind is relevant to Visual Studio.NET only.
What's a bubbled event?
When you have a complex control, like DataGrid, writing an event processing routine for
each object (cell, button, row and so on) is quite tedious. The controls can bubble up their
event handlers, allowing the main DataGrid event handler to take care of its constituents.
Suppose you want a certain ASP.NET function executed on MouseOver over a certain
button.
Where do you add an event handler?
It's the Attributes property, the Add function of that property. For example:
btnSubmit.Attributes.Add("onMouseOver","someClientCode();")
What data type does the RangeValidator control support?
Integer, String and Date.
What are the various types of caching?
Caching is a technique widely used in computing to increase performance by keeping
frequently accessed or expensive data in memory. In the context of a web application,
caching retains the pages or data across HTTP requests and reuses them without the
expense of recreating them. ASP.NET has 3 kinds of caching, strategiesOutput,
CachingFragment and CachingData.
CachingOutput Caching: Caches the dynamic output generated by a request. Some
times it is useful to cache the output of a website even for a minute, which will result in a
better performance. For caching the entire page the page should have OutputCache
directive.<%@ OutputCache Duration="60" VaryByParam="state" %>
Fragment Caching: Caches the portion of the page generated by the request. Some
times it is not practical to cache the entire page, in such cases we can cache a portion of
page<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>
Data Caching: Caches the objects programmatically. For data caching ASP.Net provides
a cache object for eg: cache["States"] = dsStates;
What do you mean by authentication and authorization?
Authentication is the process of validating a user on the credentials (username and
password) and authorization performs after authentication. After Authentication a user
will be verified for performing the various tasks, It access is limited it is known as
authorization.
What are various types of directives in .NET?
@Page: Defines page-specific attributes used by the ASP.NET page parser and compiler.
Can be included only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %>
@Control: Defines control-specific attributes used by the ASP.NET page parser and
compiler. Can be included only in .ascx files. <%@ Control Language="VB"
15
EnableViewState="false" %>
@Import: Explicitly imports a namespace into a page or user control. The Import
directive cannot have more than one namespace attribute. To import multiple
namespaces, use multiple @Import directives. <% @ Import Namespace="System.web"
%>
@Implements: Indicates that the current page or user control implements the
specified .NET framework interface.<%@ Implements
Interface="System.Web.UI.IPostBackEventHandler" %>
@Register: Associates aliases with namespaces and class names for concise notation in
custom server control syntax.<%@ Register Tagprefix="Acme" Tagname="AdRotator"
src="AdRotator.ascx" %>
@Assembly: Links an assembly to the current page during compilation, making all the
assembly's classes and interfaces available for use on the page. <%@ Assembly
Name="MyAssembly" %><%@ Assembly src="MySource.vb" %>
@OutputCache: Declaratively controls the output caching policies of an ASP.NET page
or a user control contained in a page<%@ OutputCache Duration="#ofseconds"
Location="Any | Client | Downstream | Server | None" Shared="True | False"
VaryByControl="controlname" VaryByCustom="browser | customstring"
VaryByHeader="headers" VaryByParam="parametername" %>
@Reference: Declaratively indicates that another user control or page source file should
be dynamically compiled and linked against the page in which this directive is declared.
Note: A few of the references are were taken from other sites/sources.
How do I debug an ASP.NET application that wasn't written with Visual
Studio.NET and that doesn't use code-behind?
Start the DbgClr debugger that comes with the .NET Framework SDK, open the file
containing the code you want to debug, and set your breakpoints. Start the ASP.NET
application. Go back to DbgClr, choose "Debug Processes" from the Tools menu, and
select "aspnet_wp.exe" from the list of processes. (If "aspnet_wp.exe" doesn't appear in
the list then check the "Show system processes" box.) Click the "Attach" button to attach
to "aspnet_wp.exe" and begin debugging.
Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can
enable ASP.NET to build debug executables by placing a:
<%@ Page Debug="true" %>
statement at the top of an ASPX file or a:
<COMPILATION debug="true" />
statement in a Web.config file.
Can a user browsing my Web site read my Web.config or Global.asax files?
No. The <HTTPHANDLERS> section of Machine.config, which holds the master
configuration settings for ASP.NET, contains entries that map ASAX files, CONFIG files,
and selected other file types to an HTTP handler named HttpForbiddenHandler, which
fails attempts to retrieve the associated file. You can modify it by editing Machine.config
or including a section in a local Web.config file.
What's the difference between Page.RegisterClientScriptBlock and
Page.RegisterStartupScript?
RegisterClientScriptBlock is for returning blocks of client-side script containing functions.
RegisterStartupScript is for returning blocks of client scripts, not packaged in functions. In
other words, code that's to execute when the page is loaded. The latter positions script
16
blocks near the end of the document so elements on the page that the script interacts
with are loaded before the script runs. <%@ Reference Control="MyControl.ascx" %>
Is it necessary to lock application state before accessing it?
Only if you're performing a multi-step update and want the update to be treated as an
atomic operation. Here's an example:
Application.Lock ();
Application["ItemsSold"] = (int) Application["ItemsSold"] + 1;
Application["ItemsLeft"] = (int) Application["ItemsLeft"] - 1;
Application.UnLock ();
By locking application state before updating it and unlocking it afterwards, you ensure
that another request being processed on another thread doesn't read application state at
exactly the wrong time and see an inconsistent view of it. If I update session state then
should I lock it, too?
Are concurrent accesses by multiple requests executing on multiple threads a concern
with session state?
Concurrent accesses aren't an issue with session state, for two reasons. One, it's unlikely
that two requests from the same user will overlap. Two, if they do overlap then ASP.NET
locks down session state during request processing so that two threads can't touch it at
once. Session state is locked down when the HttpApplication instance that's processing
the request fires an AcquireRequestState event and unlocked when it fires a
ReleaseRequestState event.
Do ASP.NET forms authentication cookies provide any protection against replay attacks?
Do they, for example, include the client's IP address or anything else that would
distinguish the real client from an attacker?
No. If an authentication cookie is stolen then it can be used by an attacker. It's up to you
to prevent this from happening by using an encrypted communications channel (HTTPS).
Authentication cookies issued as session cookies, do, however, include a time-out valid
that limits their lifetime. So a stolen session cookie can only be used in replay attacks as
long as the ticket inside the cookie is valid. The default time-out interval is 30 minutes.
You can change that by modifying the timeout attribute accompanying the <forms>
element in the Machine.config or a local Web.config file. Persistent authentication cookies
do not time-out and therefore are a more serious security threat if stolen.
How do I send e-mail from an ASP.NET application?
MailMessage message = new MailMessage ();
message.From = <email>;
message.To = <email>;
message.Subject = "Scheduled Power Outage";
message.Body = "Our servers will be down tonight.";
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send (message);
MailMessage and SmtpMail are classes defined in the .NET Framework Class Library's
System.Web.Mail namespace. Due to a security change made to ASP.NET just before it
shipped, you need to set SmtpMail's SmtpServer property to "localhost" even though
"localhost" is the default. In addition, you must use the IIS configuration applet to enable
localhost (127.0.0.1) to relay messages through the local SMTP service.
What are VSDISCO files?
VSDISCO files are DISCO files that support dynamic discovery of Web services. If you
17
place the following VSDISCO file in a directory on your Web server, for example then it
returns references to all ASMX and DISCO files in the host directory and any
subdirectories not noted in <exclude> elements:
<?xml version="1.0" ?>
<dynamicDiscovery
xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
<exclude path="_vti_cnf" />
<exclude path="_vti_pvt" />
<exclude path="_vti_log" />
<exclude path="_vti_script" />
<exclude path="_vti_txt" />
</dynamicDiscovery>
How does dynamic discovery work?
ASP.NET maps the file name extension VSDISCO to an HTTP handler that scans the host
directory and subdirectories for ASMX and DISCO files and returns a dynamically
generated DISCO document. A client who requests a VSDISCO file gets back what
appears to be a static DISCO document.
Note that VSDISCO files are disabled in the release version of ASP.NET. You can reenable
them by uncommenting the line in the <httpHandlers> section of Machine.config that
maps *.vsdisco to System.Web.Services.Discovery.DiscoveryRequestHandler and granting
the ASPNET user account permission to read the IIS metabase. However, Microsoft is
actively discouraging the use of VSDISCO files because they could represent a threat to
Web server security.
Is it possible to prevent a browser from caching an ASPX page?
Just call SetNoStore on the HttpCachePolicy object exposed through the Response
object's Cache property, as demonstrated here:
<%@ Page Language="C#" %>
<html>
<body>
<%
Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
%>
</body>
</html>
SetNoStore works by returning a Cache-Controll; a private, no-store header in the HTTP
response. In this example, it prevents caching of a Web page that shows the current
time.
What does AspCompat="true" mean and when should I use it?
AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but
should be set to true in any ASPX file that creates apartment-threaded COM objects; that
is, COM objects registered with ThreadingModel=Apartment. That includes all COM
objects written with Visual Basic 6.0. AspCompat should also be set to true (regardless of
threading model) if the page creates COM objects that access intrinsic ASP objects such
as Request and Response. The following directive sets AspCompat to true:
<%@ Page AspCompat="true" %>
Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available
18
to the COM components by placing unmanaged wrappers around the equivalent ASP.NET
objects. Second, it improves the performance of calls that the page places to apartmentthreaded COM objects by ensuring that the page (actually, the thread that processes the
request for the page) and the COM objects it creates share an apartment.
AspCompat="true" forces ASP.NET request threads into single-threaded apartments
(STAs). If those threads create COM objects marked ThreadingModel=Apartment then the
objects are created in the same STAs as the threads that created them. Without
AspCompat="true," request threads run in a multithreaded apartment (MTA) and each
call to an STA-based COM object incurs a performance hit when it's marshaled across
apartment boundaries.
Do not set AspCompat to true if your page uses no COM objects or if it uses COM objects
that don't access ASP intrinsic objects and that are registered ThreadingModel=Free or
ThreadingModel=Both.
Explain the differences between Server-side and Client-side code?
Server-side scripting means that all the script will be executed by the server and
interpreted as needed. ASP doesn't have some of the functionality like sockets,
uploading, and so on. For these you need to make custom components usually in VB or
VC++. Client-side scripting means that the script will be executed immediately in the
browser such as form field validation, clock, email validation, and so on. Client-side
scripting is usually done in VBScript or JavaScript. Download time, browser compatibility,
and visible code, since JavaScript and VBScript code is included in the HTML page, then
anyone can see the code by viewing the page source. Also possible security hazards for
the client computer.
What type of code (server or client) is found in a Code-Behind class?
C#.
Should validation (such as did the user enter a real date) occur serverside or client-side? Why?
Client-side validation because there is no need to request a server-side date
when you could obtain a date from the client machine.
What are ASP.NET Web Forms? How is this technology different than
what is available though ASP?
Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface
(UI) elements that provide your Web applications their look and feel. Web Forms
are similar to Windows Forms in that they provide properties, methods, and
events for the controls that are placed onto them. However, these UI elements
render themselves in the appropriate markup language required by the request,
for example HTML. If you use Microsoft Visual Studio .NET then you will also get
the familiar drag-and-drop interface used to create your UI for your Web
application.
What is the difference between Server.Transfer and Response.Redirect?
Why would I choose one over the other?
In earlier versions of IIS, if we wanted to send a user to a new Web page then the
only option we had was Response.Redirect. While this method does accomplish
our goal, it has several important drawbacks. The biggest problem is that this
method causes each page to be treated as a separate transaction. Besides
making it difficult to maintain your transactional integrity, Response.Redirect
19
web-servers (using round-robbin load balancing) then what would be the best
approach to maintain login-in state for the users?
Use the state server or store the state in the database. This can be easily done
through a simple setting change in the web.config.
<SESSIONSTATE
StateConnectionString="tcpip=127.0.0.1:42424" =""
sqlConnectionString="data source=127.0.0.1; user id=sa;" password=""
cookieless="false" =""
timeout="30" =""/>
You can specify mode as "stateserver" or "sqlserver".
Where would you use an iHTTPModule, and what are the limitations of any
approach you might use in implementing one?
"One of ASP.NET's most useful features is the extensibility of the HTTP pipeline, the path
that data takes between client and server. You can use them to extend your ASP.NET
applications by adding pre-processing and post-processing to each HTTP request coming
into your application. For example, if you wanted custom authentication facilities for your
application then the best technique would be to intercept the request when it comes in
and processes the request in a custom HTTP module.
How do you turn off cookies for one page in your site?
Since no Page Level directive is present, I am afraid that can't be done.
How do you create a permanent cookie?
Permanent cookies are available until a specified expiration date, and are stored on the
hard disk. So set the "Expires" property to a value greater than DataTime.MinValue with
respect to the current datetime. If you want the cookie that never expires set its Expires
property equal to DateTime.maxValue.
Which method do you use to redirect the user to another page without
performing a round trip to the client?
Server.Transfer and Server.Execute
What property do you need to set to tell the grid which page to go to when
using the Pager object?
CurrentPageIndex
Should validation (such as did the user enter a real date) occur server-side or
client-side? Why?
It should occur both at client-side and server-side. By using an expression validator
control with the specified expression, in other words, the regular expression provides the
ability to only validatate the date specified that it is in the correct format. For checking
the date, whether it is the real data or not should hoever be done at the server-side, by
getting the system date ranges and checking the date whether it is between that range
or not.
What does the "EnableViewState" property do? Why would I want it on or off?
Enable ViewState turns on the automatic state management feature that enables server
controls to re-populate their values on a round trip without requiring you to write any
21
code. This feature is not free, however, since the state of a control is passed to and from
the server in a hidden form field. You should be aware of when ViewState is helping you
and when it is not. For example, if you are binding a control to data on every round trip,
then you do not need the control to maintain it's view state, since you will wipe out any
re-populated data in any case. ViewState is enabled for all server controls by default. To
disable it, set the EnableViewState property of the control to false.
What is the difference between Server.Transfer and Response.Redirect? Why
would I choose one over the other?
Server.Transfer(): the client is shown as it is on the requesting page only, but all the
content is of the requested page. Data can be persisted accros the pages using a
Context.Item collection, which is one of the best way to transfer data from one page to
another keeping the page state alive.
Response.Redirect(): client knows the physical location (page name and query string
as well). Context.Items loses the persisitance when nevigating to the destination page. In
earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we
had was Response.Redirect While this method does accomplish our goal, it has several
important drawbacks. The biggest problem is that this method causes each page to be
treated as a separate transaction. Besides making it difficult to maintain your
transactional integrity, Response.Redirect introduces some additionalproblens. First, it
prevents good encapsulation of code. Second, you lose access to all of the properties in
the Request object. Sure, there are workarounds, but they're difficult. Finally,
Response.Redirect necessitates a round trip to the client, which, on high-volume sites,
causes scalability problems. As you might suspect, Server.Transfer fixes all of these
problems. It does this by performing the transfer on the server without requiring a
roundtrip to the client.
Can you give an example of when it would be appropriate to use a web service
as opposed to a non-serviced .NET component?
Software Reuse. This takes place at multiple levels. Code Reuse at the Source
code level or binary componet-based resuse. The limiting factor here is that you
can reuse the code but not the data behind it. Webservice overcomes this
limitation. A scenario could be when you are building an app that aggregates the
functionality of serveral other Applicatons. Each of these functions could be
performed by individual apps, but there is value in perhaps combining the the
multiple apps to present a unifiend view in a Portal or Intranet.
22
Can you give an example of what might be most appropriately placed in the
Application_Start and Session_Start events?
The Application_Start event is guaranteed to occur only once throughout the lifetime of
the application. It's a good place to initialize global variables. For example, you might
want to retrieve a list of products from a database table and place the list in application
state or the Cache object. SessionStateModule exposes both Session_Start and
Session_End events.
What are the advantages and disadvantages of viewstate?
The primary advantages of the ViewState feature in ASP.NET are:
1.
Simplicity. There is no need to write possibly complex code to store form data
between page submissions.
2.
Flexibility. It is possible to enable, configure, and disable ViewState on a controlby-control basis, choosing to persist the values of some fields but not others.
There are, however a few disadvantages that are worth pointing out:
1.
Does not track across pages. ViewState information does not automatically
transfer from page to page. With the session
approach, values can be stored in the session and accessed from other pages.
This is not possible with ViewState, so storing
data into the session must be done explicitly.
2.
ViewState is not suitable for transferring data for back-end systems. That is, data
must still be transferred to the back
end using some form of data object.
Describe session handling in a webfarm, how does it work and what are the
limits?
ASP.NET Sessions support storing of session data in 3 ways, i] In-Process (in the same
memory that ASP.NET uses) , ii] Out-of-Process using a Windows NT Service (in memory
separate from ASP.NET) or iii] in SQL Server (persistent storage). Both the Windows
Service and SQL Server solutions support a webfarm scenario where all the web-servers
can be configured to share a common session state store.
1. Windows Service
We can start this service by "Start" | "Control Panel" | "Administrative Tools" | "Services".
In that we service names ASP.NET State Service. We can start or stop a service manually
or configure it to start automatically. Then we need to configure our web.config file as in
the following:
23
<CONFIGURATION>
<configuration>
<system.web>
<SessionState
mode = "StateServer"
stateConnectionString = "tcpip=127.0.0.1:42424"
stateNetworkTimeout = "10"
sqlConnectionString="data source = 127.0.0.1; uid=sa;pwd="
cookieless ="Flase"
timeout= "20" />
</system.web>
</configuration>
</SYSTEM.WEB>
</CONFIGURATION>
Here ASP.Net Session is directed to use a Windows Service for state management on the
local server (the address 127.0.0.1 is the TCP/IP loop-back address). The default port is
42424. We can configure it to any port but for that we need to manually edit the registry.
Use the following simple procedure:
In a webfarm make sure you have the same config file in all your web servers.
For the session state to be maintained across various web servers in the webfarm,
the application path of the web-site in the IIS Metabase should be identical in all
the web-servers in the webfarm.
img
div
src="images/<%#
b
>
ItemTemplate
>
class
="rItem"
>
Container.DataItem("ImageURL")%>" hspace="10" />
<%
#
Container.DataItem("Title")%>
/div
>
ItemTemplate
>
the
AlternatintItemTemplate
What property must you set, and what method must you call in your code, to
bind the data from some data source to the Repeater control?
Set the DataMember property to the name of the table to bind to. (If this property is not
set
then
by
default
the
first
table
in
the
dataset
is
used.)
The DataBind method uses this method to bind data from a source to a server control.
This method is commonly used after retrieving a data set through a database query.
What
method
do
you
use
to
explicitly
kill
user
session?
You can dump (Kill) the session yourself by calling the method Session.Abandon.
ASP.NET automatically deletes a user's Session object, dumping its contents, after it has
been idle for a configurable timeout interval. This interval, in minutes, is set in the
24
<SESSIONSTATE>section
How
do
you
turn
of
the
off
web.config
cookies
file.
for
The
one
default
page
is
in
20
minutes.
your
site?
Use the Cookie.Discard property, Gets or sets the discard flag set by the server. When
true, this property instructs the client application not to save the Cookie on the user's
hard
disk
when
a
session
ends.
Which
two
properties
are
on
every
validation
control?
We have two common properties for every validation control as in the following:
1.
Control to Validate,
2.
Error Message.
What tags do you need to add within the asp:datagrid tags to bind columns manually?
< asp:DataGrid id="dgCart" AutoGenerateColumns="False" CellPadding="4" Width="448px" runat="server" >
< Columns >
< asp:ButtonColumn HeaderText="SELECT" Text="SELECT" CommandName="select" ><
/asp:ButtonColumn >
< asp:BoundColumn DataField="ProductId" HeaderText="Product ID" >< /asp:BoundColumn >
< asp:BoundColumn DataField="ProductName" HeaderText="Product Name" >< /asp:BoundColumn >
< asp:BoundColumn DataField="UnitPrice" HeaderText="UnitPrice" >< /asp:BoundColumn >
< /Columns >
< /asp:DataGrid >
How do you create a permanent cookie?
Permanent cookies are the ones that are most useful. Permanent cookies are available until a specified expiration
date, and are stored on the hard disk. The location of cookies differs with each browser, but this doesn't matter,
as this is all handled by your browser and the server. If you want to create a permanent cookie called Name with
a value of Nigel, that expires in one month then you'd use the following code:
Response.Cookies ("Name") = "Nigel"
Response.Cookies ("Name"). Expires = DateAdd ("m", 1, Now ())
What tag do you use to add a hyperlink column to the DataGrid?
< asp:HyperLinkColumn > </ asp:HyperLinkColumn>
Which method do you use to redirect the user to another page without performing a round trip to the
client?
Server.transfer
What is the transport protocol you use to call a Web service SOAP ?
HTTP Protocol
Explain role based security
Role Based Security lets you identify groups of users to allow or deny based on their role in the organization. In
Windows NT and Windows XP, roles map to names used to identify user groups. Windows defines several builtin groups, including Administrators, Users, and Guests.To allow or deny access to certain groups of users, add
the <ROLES> element to the authorization list in your Web application's Web.config file. For example:
<AUTHORIZATION>< authorization >
< allow roles="Domain Name\Administrators" / > < !-- Allow Administrators in domain. -- >
< deny users="*" / > < !-- Deny anyone else. -- >
25
26
27
and ASP.Net is fully Object Oriented. ASP.NET has been entirely re-architected to provide
a highly productive programming experience based on the .NET Framework, and a robust
infrastructure for building reliable and scalable web applications."
Name the validation control available in ASP.Net
RequiredField, RangeValidator, RegularExpression, Custom Validator, Compare Validator.
What are the various ways of securing a web site that could prevent hacking
and so on?
1.
Authentication/Authorization
2.
Encryption/Decryption
3.
4.
and so on.
28
If you enable Web Garden mode in the < processModel > element of the
application's Web.config file then do not use in-process session-state mode.
Otherwise, random data loss can occur.
Advantage
in-process session state is by far the fastest solution. If you are storing only small
amounts of volatile data in session state, it is recommended that you use the inprocess provider.
2. The State Server simply stores session state in memory when in out-of-proc mode. In
this mode the worker process talks directly to the State Server
3. SQL mode, session states are stored in a SQL Server database and the worker process
talks directly to SQL. The ASP.NET worker processes are then able to take advantage of
this simple storage service by serializing and saving (using .NET serialization services) all
objects within a client's Session collection at the end of each Web request
Both these out-of-process solutions are useful primarily if you scale your application
across multiple processors or multiple computers, or where data cannot be lost if a server
or process is restarted.
What is the difference between HTTP-Post and HTTP-Get?
29
As their names imply, both HTTP GET and HTTP POST use HTTP as their underlying
protocol. Both of these methods encode request parameters as name/value pairs in the
HTTP request.
The GET method creates a query string and appends it to the script's URL on the server
that handles the request.
The POST method creates name/value pairs that are passed in the body of the HTTP
request message.
Name and describe some HTTP Status Codes and what they express to the
requesting client.
When users try to access content on a server that is running Internet Information
Services (IIS) through HTTP or File Transfer Protocol (FTP), IIS returns a numeric code that
indicates the status of the request. This status code is recorded in the IIS log, and it may
also be displayed in the Web browser or FTP client. The status code can indicate whether
a specific request is successful or unsuccessful and can also reveal the exact reason why
a request is unsuccessful. There are 5 groups ranging from 1xx - 5xx of HTTP status
codes that exist as in the following:
101: Switching protocols.
200: OK. The client request has succeeded
302: Object moved.
400: Bad request.
500.13: Web server is too busy.
Explain < @OutputCache% > and the usage of VaryByParam, VaryByHeader.
OutputCache is used to control the caching policies of an ASP.NET page or user control.
To cache a page @OutputCache directive should be defined as follows < %@
OutputCache Duration="100" VaryByParam="none" % >
VaryByParam: A semicolon-separated list of strings used to vary the output cache. By
default, these strings correspond to a query string value sent with GET method
attributes, or a parameter sent using the POST method. When this attribute is set to
multiple parameters then the output cache contains a different version of the requested
document for each specified parameter. Possible values include none, *, and any valid
query string or POST parameter name.
VaryByHeader: A semicolon-separated list of HTTP headers used to vary the output
cache. When this attribute is set to multiple headers, the output cache contains a
different version of the requested document for each specified header.
What is the difference between repeater over datalist and datagrid?
The Repeater class is not derived from the WebControl class, like the DataGrid and
DataList. Therefore, the Repeater lacks the stylistic properties common to both the
DataGrid and DataList. What this boils down to is that if you want to format the data
displayed in the Repeater then you must do so in the HTML markup.
The Repeater control provides the maximum amount of flexibility over the HTML
produced. Whereas the DataGrid wraps the DataSource contents in an HTML < table >,
and the DataList wraps the contents in either an HTML < table > or < span > tags
(depending on the DataList's RepeatLayout property), the Repeater adds absolutely no
HTML content other than what you explicitly specify in the templates.
While using the Repeater control, if we wanted to display the employee names in a bold
font then we'd need to alter the "ItemTemplate" to include an HTML bold tag. Whereas
30
with the DataGrid or DataList, we could have made the text appear in a bold font by
setting the control's ItemStyle-Font-Bold property to True.
The Repeater's lack of style properties can drastically add to the development time
metric. For example, imagine that you decide to use the Repeater to display data that
needs to be bold, centered, and displayed in a specific font-face with a specific
background color. While all this can be specified using a few HTML tags, these tags will
quickly clutter the Repeater's templates. Such clutter makes it much harder to change
the look at a later date. Along with its increased development time, the Repeater also
lacks any built-in functionality to assist in supporting paging, editing, or editing of data.
Due to this lack of feature-support, the Repeater scores poorly on the usability scale.
However, The Repeater's performance is slightly better than that of the DataList's, and is
noticeably better than that of the DataGrid's. The following figure shows the number of
requests per second the Repeater could handle versus the DataGrid and DataList.
Can we handle the error and redirect to some pages using web.config?
Yes, we can do this, but to handle errors, we must know the error codes; only then we
can take the user to a proper error message page, else it may confuse the user.
CustomErrors Configuration section in web.config file:
The default configuration is:
< customErrors mode="RemoteOnly" defaultRedirect="Customerror.aspx" >
< error statusCode="404" redirect="Notfound.aspx" / >
< /customErrors >
If the mode is set to Off then the custom error messages will be disabled. Users will
receive detailed exception error messages.
If mode is set to On then custom error messages will be enabled.
If mode is set to RemoteOnly then then users will receive custom errors, but users
accessing the site locally will receive detailed error messages.
Add an < error > tag for each error you want to handle. The error tag will redirect the
user to the Notfound.aspx page when the site returns the 404 (Page not found) error.
[Example]
There is a page MainForm.aspx
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
'Put user code to initialize the page here
Dim str As System.Text.StringBuilder
str.Append("hi") ' Error Line as str is not instantiated
Response.Write(str.ToString)
End Sub
[Web.Config]
< customErrors mode="On" defaultRedirect="Error.aspx"/ >
' a simple redirect will take the user to Error.aspx [user defined] error file.
< customErrors mode="RemoteOnly" defaultRedirect="Customerror.aspx" >
31
1.
2.
For SQL Server databases, combine a WHERE clause and a ORDER BY clause with
the TOP predicate.
3.
If data does not change often then just cache records locally in a DataSet and take
some records from the DataSet to display.
32
1.
2.
3.
4.
What are the various security methods that IIS Provides apart from .NET?
The various security methods that IIS provides are:
Authentication Modes
SSL
33
operating system and doesn't include any custom semantics for doing this.
All in all, the Web Garden model is not necessarily a big win for all applications. The more
stateful applications are, the more they risk to pay in terms of real performance. Working
data is stored in blocks of shared memory so that any changes entered by a process are
immediately visible to others. However, for the time it takes to service a request, working
data is copied in the context of the process. Each worker process, therefore, will handle
its own copy of working data, and the more stateful the application, the higher the cost in
performance. In this context, careful and savvy application benchmarking is an absolute
must.
Changes made to the section of the configuration file are effective only after IIS is
restarted. In IIS 6, Web Gardening parameters are stored in the IIS metabase; the
webGarden and cpuMask attributes are ignored.
What is view state? Where is it stored? Can we disable it?
The web is a state-less protocol, so the page is instantiated, executed, rendered and then
disposed of on every round trip to the server. The developer's code to add "statefulness"
to the page by using server-side storage for the state or posting the page to itself. When
required to persist and read the data in a control on a webform, the developer must read
the values and store them in a hidden variable (in the form), that were then used to
restore the values. With the advent of the .NET Framework, ASP.NET offers the ViewState
mechanism that tracks the data values of server controls on an ASP.NET webform. In
effect, ViewState can be viewed as "hidden variable managed by the ASP.NET
framework!". When an ASP.NET page is executed, data values from all server controls on
a page are collected and encoded as a single string that is then assigned to the page's
hidden atrribute "< input type=hidden >", that is part of the page sent to the client.
The ViewState value is temporarily saved in the client's browser. ViewState can be
disabled for a single control, for an entire page or for an entire web application. The
syntax is:
Disable ViewState for control (Datagrid in this example)
< asp:datagrid EnableViewState="false" ... / >
Disable ViewState for a page, using Page directive
< %@ Page EnableViewState="False" ... % >
Disable ViewState for application through entry in web.config
< Pages EnableViewState="false" ... / >
.NET FrameWork FAQ's
When was .NET announced?
Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET
"vision". The July 2000 PDC had a number of sessions on .NET technology, and delegates
were given CDs containing a pre-release version of the .NET Framework/SDK and Visual
Studio.NET.
When was the first version of .NET released?
The final version of the 1.0 SDK and runtime was made publicly available around 6 PM
PST on 15-Jan-2002. At the same time, the final version of Visual Studio.NET was made
available to MSDN subscribers.
What platforms does the .NET Framework run on?
The runtime supports Windows XP, Windows 2000, NT4 SP6a and Windows ME/98.
34
Windows 95 is not supported. Some parts of the framework do not work on all platforms;
for example, ASP.NET is only supported on Windows XP and Windows 2000. Windows
98/ME cannot be used for development.
IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET.
However, the ASP.NET Web Matrix web server does run on XP Home.
The Mono project is attempting to implement the .NET framework on Linux.
What is the CLR?
CLR = Common Language Runtime. The CLR is a set of standard resources that (in
theory) any .NET program can take advantage of, regardless of programming language.
Robert Schmidt (Microsoft) lists the following CLR resources in his MSDN PDC# article:
Security model
Type system
What this means is that in the .NET world, various programming languages will be more
equal in capability than they have ever been before, although clearly not all languages
will support all CLR services.
What is the CTS?
CTS = Common Type System. This is the range of types that the .NET runtime
understands, and therefore that .NET applications can use. However note that not all
.NET languages will support all the types in the CTS. The CTS is a superset of the CLS.
What is the CLS?
CLS = Common Language Specification. This is a subset of the CTS that all .NET
languages are expected to support. The idea is that any program that uses CLScompliant types can interoperate with any .NET program written in any language.
In theory this allows very tight interop between various .NET languages, for example
allowing a C# class to inherit from a VB class.
What is IL?
IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or
CIL (Common Intermediate Language). All .NET source code (of any language) is
compiled to IL. The IL is then converted to machine code at the point where the software
35
36
using the Finalize method. Finalize provides a backup to prevent resources from
permanently leaking if the programmer fails to call Dispose.
What is Partial Assembly References?
Full Assembly reference: A full assembly reference includes the assembly's text name,
version, culture, and public key token (if the assembly has a strong name). A full
assembly reference is required if you reference any assembly that is part of the common
language runtime or any assembly located in the Global Assembly Cache.
Partial Assembly reference: We can dynamically reference an assembly by providing only
partial information, such as specifying only the assembly name. When you specify a
partial assembly reference, the runtime looks for the assembly only in the
application directory.
We can make partial references to an assembly in your code in one of the following ways:
37
38
It's certainly an issue that affects component design. If you have objects that maintain
expensive or scarce resources (for example database locks), you need to provide some
way for the client to tell the object to release the resource when it is done. Microsoft
recommends that you provide a method called Dispose() for this purpose. However, this
causes problems for distributed objects, in a distributed system who calls the Dispose()
method? Some form of reference-counting or ownership-management mechanism is
needed to handle distributed objects, unfortunately the runtime offers no help with this.
What is serialization?
Serialization is the process of converting an object into a stream of bytes. Deserialization
is the opposite process of creating an object from a stream of bytes. Serialization /
Deserialization is mostly used to transport objects (for example during remoting), or to
persist objects (for example to a file or database).
Does the .NET Framework have in-built support for serialization?
There are two separate mechanisms provided by the .NET class library, XmlSerializer and
SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses
SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own
code.
Can I customise the serialization process?
Yes. XmlSerializer supports a range of attributes that can be used to configure
serialization for a specific class. For example, a field or property can be marked with the
[XmlIgnore] attribute to exclude it from serialization. Another example is the
[XmlElement]
attribute, that can be used to specify the XML element name to be used for a specific
property or field.
Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by
attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's
[XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by
implementing the the ISerializable interface on the class whose instances are to be
serialized.
Why is XmlSerializer so slow?
There is a once-per-process-per-type overhead with XmlSerializer. So the first time you
serialize or deserialize an object of a given type in an application, there is a significant
delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a
poor choice for loading configuration settings during startup of a GUI application.
Why do I get errors when I try to serialize a Hashtable?
XmlSerializer will refuse to serialize instances of any class that implements IDictionary,
for example Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.
What are attributes?
There are at least two types of .NET attributes. The first type I will refer to as a metadata
attribute, it allows some data to be attached to a class or method. This data becomes
part of the metadata for the class, and (like other class metadata) can be accessed via
reflection.
The other type of attribute is a context attribute. Context attributes use a similar syntax
to metadata attributes but they are fundamentally different. Context attributes provide
an interception mechanism whereby instance activation and method calls can be
pre- and/or post-processed.
39
40
easy to manipulate from the command-line. The underlying runtime never sees it.
How do I change the permission set for a code group?
Use caspol. If you are the machine administrator then you can operate at the "machine"
level, which means that not only do the changes you make become the default for the
machine, but also those users cannot change the permissions to be more permissive. If
you are a normal (non-admin) user then you can still modify the permissions, but only to
make them more restrictive. For example, to allow intranet code to do what it likes you
might do this:
caspol -cg 1.2 FullTrust
Note that because this is more permissive than the default policy (on a standard system),
you should only do this at the machine level, doing it at the user level will have no effect.
I can't be bothered with all this CAS stuff. Can I turn it off?
Yes, as long as you are an administrator. Just run:
caspol -s off
Can I look at the IL for an assembly?
Yes. Microsoft supplies a tool called Ildasm that can be used to view the metadata and IL
for an assembly.
Can source code be reverse-engineered from IL?
Yes, it is often relatively straightforward to regenerate high-level source (for example C#)
from IL.
How can I stop my code being reverse-engineered from IL?
There is currently no simple way to stop code being reverse-engineered from IL. In the
future it is likely that IL obfuscation tools will become available, either from Microsoft or
from third parties. These tools work by "optimising" the IL in such a way that reverseengineering becomes much more difficult.
Of course if you are writing web services then reverse-engineering is not a problem as
clients do not have access to your IL.
Is there built-in support for tracing/logging?
Yes, in the System.Diagnostics namespace. There are two main classes that deal with
tracing, Debug and Trace. They both work in a similar way, the difference is that tracing
from the Debug class only works in builds that have the DEBUG symbol defined, whereas
tracing from the Trace class only works in builds that have the TRACE symbol defined.
Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing
that you want to work in debug and release builds, and
System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug
builds.
Can I redirect tracing to a file?
Yes. The Debug and Trace classes both have a Listeners property, that is a collection of
sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine
respectively. By default the Listeners collection contains a single sink, that is an
instance of the DefaultTraceListener class. This sends output to the Win32
OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method.
41
This is useful when debugging, but if you're trying to trace a problem at a customer site
then redirecting the output to a file is more appropriate. Fortunately, the
TextWriterTraceListener class is provided for this purpose.
What are the contents of an assembly?
In general, a static assembly can consist of the four elements:
1.
2.
Type metadata.
3.
4.
A set of resources.
42
operations. Before code can be executed, MSIL must be converted to CPU-specific code,
usually by a Just-In-Time (JIT) compiler. Because the Common Language Runtime supplies
one or more JIT compilers for each computer architecture it supports, the same set of
MSIL can be JIT-compiled and executed on any supported architecture.
When a compiler produces MSIL, it also produces metadata. Metadata describes the
types in your code, including the definition of each type, the signatures of each type's
members, the members that your code references, and other data that the runtime uses
at execution time. The MSIL and metadata are contained in a Portable Executable (PE) file
that is based on and extends the published Microsoft PE and Common Object File Format
(COFF) used historically for executable content. This file format, that accommodates MSIL
or native code as well as metadata, enables the operating system to recognize Common
Language Runtime images. The presence of metadata in the file along with the MSIL
enables your code to describe itself, that means that there is no need for type libraries or
Interface Definition Language (IDL). The runtime locates and extracts the metadata from
the file as needed during execution.
IL: (Intermediate Language)
A language used as the output of a number of compilers and as the input to a Just-InTime (JIT) compiler. The Common Language Runtime includes a JIT compiler for
converting MSIL to native code.
CTS: (Common Type System)
The specification that determines how the Common Language Runtime defines, uses,
and manages types.
CLR: (Common Language Runtime)
The engine at the core of managed code execution. The runtime supplies managed code
with services such as cross-language integration, code access security, object lifetime
management, and debugging and profiling support.
What is Reference type and value type ?
Reference Type
Reference types are allocated on the managed CLR heap, just like object types. A data
type that is stored as a reference to the value's location. The value of a reference type is
the location of the sequence of bits that represent the type's data. Reference types can
be self-describing types, pointer types, or interface types.
Value Type
Value types are allocated on the stack just like primitive types in VBScript, VB6 and C/C+
+. Value types that are not instantiated using new go out of scope when the function
they are defined within returns. Value types in the CLR are defined as types that derive
from system.valueType.
A data type that fully describes a value by specifying the sequence of bits that
constitutes the value's representation. Type information for a value type instance is not
stored with the instance at run time, but it is available in metadata. Value type instances
can be treated as objects using boxing.
What is Boxing and unboxing ?
Boxing
43
The conversion of a value type instance to an object, that implies that the instance will
carry full type information at run time and will be allocated in the heap. The Microsoft
Intermediate Language (MSIL) instruction set's box instruction converts a value type to
an object by making a copy of the value type and embedding it in a newly allocated
object.
Un-Boxing
The conversion of an object instance to a value type.
What is JIT and how does it work?
An acronym for "Just-In-Time", a phrase that describes an action that is taken only when
it becomes necessary, such as Just-In-Time compilation or Just-In-Time object activation.
What is Portable Executable (PE)?
The file format used for executable programs and for files to be linked together to form
executable programs.
What is a strong name?
A name that consists of an assembly's identity; its simple text name, version number,
and culture information (if provided) strengthened by a public key and a digital signature
generated over the assembly. Because the assembly manifest
contains file hashes for all the files that constitute the assembly implementation, it is
sufficient to generate the digital signature over just the one file in the assembly that
contains the assembly manifest. Assemblies with the same strong name are expected to
be identical.
What is Global Assembly Cache?
A machine-wide code cache that stores assemblies specifically installed to be shared by
many applications on the computer. Applications deployed in the Global Assembly Cache
must have a strong name.
What is the difference between constants, readonly and, static?
Constants: The value can't be changed
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.
What is difference between shared and public?
An assembly that can be referenced by more than one application. An assembly must be
explicitly built to be shared by giving it a cryptographically strong name.
What is namespace used for loading assemblies at run time and name the
methods?
System.Reflection
What are the types of authentication in .Net?
We have three types of authentication:
1.
Form authentication
44
2.
Windows authentication
3.
Passport
45
Stack.
Where do the reference-type variables go in the RAM?
The references go on the stack, while the objects themselves go on the heap.
What is the difference between the value-type variables and reference-type
variables in terms of garbage collection?
The value-type variables are not garbage-collected, they are just popped off the stack
when they go out of scope, the reference-type objects
are picked up by GC when their references go null.
How do you convert a string into an integer in .NET?
Int32.Parse(string)
How do you box a primitive data type variable?
Assign it to the object, pass an object.
Why do you need to box a primitive variable?
To pass it by reference.
What's the difference between Java and .NET garbage collectors?
Sun left the implementation of a specific garbage collector up to the JRE developer, so
their performance varies widely, depending on whose JRE you're using. Microsoft
standardized on their garbage collection.
How do you enforce garbage collection in .NET?
System.GC.Collect();
What's different about namespace declaration when comparing that to
package declaration in Java?
No semicolon.
What's the difference between const and readonly?
You can initialize readonly variables to some runtime values. Let's say your program uses
current date and time as one of the values that won't change. This way you declare
public readonly string DateT = new DateTime().ToString().
What happens when you encounter a continue statement inside the for loop?
The code for the rest of the loop is ignored, the control is transferred back to the
beginning of the loop.
What's the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in the cases where a lot of manipulation is done to the
text. Strings are immutable, so each time it's being operated on, a new instance is
created.
Can you store multiple data types in System.Array?
46
No.
What's the difference between the System.Array.CopyTo() and
System.Array.Clone()?
The first one performs a deep copy of the array, the second one is shallow.
How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.
What's the .NET datatype that allows the retrieval of data by a unique key?
HashTable.
What's class SortedList underneath?
A sorted HashTable.
Will a finally block be executed if the exception had not occurred?
Yes.
Can multiple catch blocks be executed?
No, once the proper catch code fires off, the control is transferred to the finally block (if
there are any) and then whatever follows the finally block.
Why is it a bad idea to throw your own exceptions?
Well, if at that point you know that an error has occurred, then why not write the proper
code to handle that error instead of passing a new Exception object to the catch block?
Throwing your own exceptions signifies some design flaws in the project.
What's a delegate?
A delegate object encapsulates a reference to a method. In C++ they were referred to as
function pointers.
What's a multicast delegate?
It's a delegate that points to and eventually fires off several methods.
How's the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run
(that was available under Win32), but also the version of the assembly.
What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.
What's a satellite assembly?
When you write a multilingual or multi-cultural application in .NET and want to distribute
the core application separately from the localized modules, the localized assemblies that
modify the core application are called satellite assemblies.
47
48
System.Object.
How's method overriding different from overloading?
When overriding, you change the method behavior for a derived class. Overloading
simply involves having a method with the same name within the class.
What does the keyword virtual mean in the method definition?
The method can be overridden.
Can you declare the override method static while the original method is nonstatic?
No, you can't, the signature of the virtual method must remain the same, only the
keyword virtual is changed to keyword override.
Can you override private virtual methods?
No, moreover, you cannot access private methods in inherited classes, you need to be
protected in the base class to allow any sort of access.
Can you prevent your class from being inherited and becoming a base class for
some other classes?
Yes, that's what the keyword sealed in the class definition is for. The developer trying to
derive from your class will get a message: cannot inherit from Sealed class
WhateverBaseClassName. It's the same concept as final class in Java.
Can you allow a class to be inherited, but prevent the method from being
overridden?
Yes, just leave the class public and make the method sealed.
Why can't you specify the accessibility modifier for methods inside the
interface?
They all must be public. Therefore, to prevent you from getting the false impression that
you have any freedom of choice, you are not allowed to specify any accessibility, it's
public by default.
Can you inherit multiple interfaces?
Yes, why not?
And if they have conflicting method names?
It's up to you to implement the method inside your own class, so implementation is left
entirely up to you. This might cause a problem on a higher-level scale if similarly named
methods from different interfaces expect different data, but as far as the compiler cares
you're okay.
What's the difference between an interface and abstract class?
In the interface all methods must be abstract, in the abstract class some methods can be
concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract
classes.
How can you overload a method?
49
50
1.
2.
When the class itself is inherited from an abstract class, but not all base abstract
methods have been overridden.
What's an interface?
It's an abstract class with public abstract methods all of which must be implemented in
the inherited classes.
Why can't you specify the accessibility modifier for methods inside the
interface?
They all must be public. Therefore, to prevent you from getting the false impression that
you have any freedom of choice,
you are not allowed to specify any accessibility, it's public by default.
What's the difference between an interface and abstract class?
In an interface class, all methods must be abstract. In an abstract class some methods
can be concrete. In an interface class, no accessibility modifiers are allowed, which is ok
in an abstract class.
How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class.
Overloading a method simply involves having another method with the same name
within the class.
Can you declare an override method to be static if the original method is nonstatic?
No. The signature of the virtual method must remain the same, only the keyword virtual
is changed to keyword override.
Can you override private virtual methods?
No. Private methods are not accessible outside the class.
Can you write a class without specifying a namespace? Which namespace does
it belong to by default?
Yes, you can, then the class belongs to the global namespace that has no name. For
commercial products, naturally, you wouldn't want the global namespace.
What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into
messages on one end, and deserializing and decoding messages into data on the other
end.
51
Total Sys.
Cost
16,785
16,785
33,375
33,375
Escala EPC2450
110,403
110,403
52
Total Sys.
Cost
PowerEdge 4400
ProLiant ML-570-6/700-3P
PowerEdge 6400 30,
Netfinity 7600 c/s
ProLiant 8500-X550-64P
ProLiant 8500-X700-64P
ProLiant 8500-X550-96P
ProLiant 8500-X700-96P
ProLiant 8500-700-192P
16,263 $273,487
20,207 $201,717
231 $334,626
32,377 $443,463
161,720 $3,534,272
179,658 $3,546,582
229,914 $5,305,571
262,244 $5,305,571
505,303 $10,003,826
Framework Support
The .NET platform includes an eCommerce framework called Commerce Server. At this
point, there is no equivalent vendor-neutral framework in the J2EE space. With J2EE, you
should assume that you will be building your new eCommerce solution from scratch.
Moreover, no matter what [J2EE] vendor you choose, if you expect a component
framework that will allow you to quickly field complete e-business applications, you are in
for a frustrating experience.
Language
In the language arena, the choice is about as simple as it gets. J2EE supports Java, and
only Java. It will not support any other language in the foreseeable future. The .NET
platform supports every language except Java (although it does support a language that
is syntactically and functionally equivalent to Java, C#). In fact, given the importance of
the .NET platform as a language independent vehicle, it is likely that any language that
comes out in the near future will include support for the .NET platform.
Some companies are under the impression that J2EE supports other languages. Although
both IBM's WebSphere and BEA's WebLogic support other languages, neither does it
through their J2EE technology. There are only two official ways in the J2EE platform to
access other languages, one through the Java Native Interface and the other through
CORBA interoperability. Sun recommends the later approach. As Sun's Distinguished
Scientist and Java Architect Rick Cattell said in a recent interview.
Portability
The reason that operating system portability is a possibility with J2EE is not so much
because of any inherent portability of J2EE, as it is that most of the J2EE vendors support
multiple operating systems. Therefore as long as one sticks with a given J2EE vendor and
a given database vendor, moving from one operating system to another should be
possible. This is probably the single most important benefit in favor of J2EE over the .NET
platform, that is limited to the Windows operating system. It is worth noting, however,
that Microsoft has submitted the specifications for C# and a subset of the .NET
Framework (called the Common Language Infrastructure) to ECMA, the group that
standardizes JavaScript.
J2EE offers an acceptable solution to ISVs when the product must be marketed to nonWindows customers, particularly when the J2EE platform itself can be bundled with the
ISV's product as an integrated offering.
If the primary customer base for the ISV is Windows customers then the .NET platform
should be chosen. It will provide much better performance at a much lower cost.
Client device independence
53
The major difference is that with Java, it is the presentation tier programmer that
determines the ultimate HTML that will be delivered to the client, and with .NET, it is a
Visual Studio.NET control.
This Java approach has three problems. First, it requires a lot of code on the presentation
tier, since every possible thin client system requires a different code path. Second, it is
very difficult to test the code with every possible thin client system. Third, it is very
difficult to add new thin clients to an existing application, since to do so involves
searching through, and modifying a tremendous amount of presentation tier logic.
The .NET Framework approach is to write device independent code that interacts with
visual controls. It is the control, not the programmer, that is responsible for determining
what HTML to deliver, based on the capabilities of the client device.. In the .NET
Framework model, one can forget that such a thing as HTML even exists!
Conclusion
Sun's J2EE vision is based on a family of specifications that can be implemented by many
vendors. It is open in the sense that any company can license and implement the
technology, but closed in the sense that it is controlled by a single vendor, and a selfcontained architectural island with very limited ability to interact outside of itself. One of
J2EE's major disadvantages is that the choice of the platform dictates the use of a single
programming language, and a programming language that is not well suited for most
businesses. One of J2EE's major advantages is that most of the J2EE vendors do offer
operating system portability.
Microsoft's .NET platform vision is a family of products rather than specifications, with
specifications used primarily to define points of interoperability. The major disadvantage
of this approach is that it is limited to the Windows platform, so applications written for
the .NET platform can only be run on .NET platforms. Their are several important
advantages to the .NET platform:
The ability to scale up is much greater, with the proven ability to support at least
ten times the number of clients any J2EE platform has shown itself able to
support.
54
Assemblies
Defines the concept of assemblies, that are a collections of types and resources that form logical units of
functionality. Assemblies are the fundamental units of deployment, version control, reuse, activation scoping,
and security permissions.
Application Domains
Explains how to use application domains to provide isolation between applications.
Runtime Hosts
Describes the runtime hosts supported by the .NET Framework, including ASP.NET, Internet Explorer, and shell
executables.
Common Type System
Identifies the types supported by the Common Language Runtime.
Metadata and Self-Describing Components
Explains how the .NET Framework simplifies component interoperation by allowing compilers to emit
additional declarative information, or metadata, into all modules and assemblies.
Cross-Language Interoperability
Explains how managed objects created in various programming languages can interact with one another.
.NET Framework Security
Describes mechanisms for protecting resources and code from unauthorized code and unauthorized users.
.NET Framework Class Library
Introduces the library of types provided by the .NET Framework, that expedites and optimizes the development
process and gives you access to system functionality.
What is the use of JIT ?
Just- In-Time (JIT) is a compiler that converts MSIL code to Native Code (in other words, CPU-specific code
that runs on the same computer architecture).
Because the Common Language Runtime supplies a JIT compiler for each supported CPU architecture,
developers can write a set of MSIL that can be JIT-compiled and run on computers with various architectures.
However, your managed code will run only on a specific operating system if it calls platform-specific native
APIs, or a platform-specific class library.
JIT compilation takes into account the fact that some code might never get called during execution. Rather than
using time and memory to convert all the MSIL in a Portable Executable (PE) file to native code, it converts the
MSIL as needed during execution and stores the resulting native code so that it is accessible for subsequent
calls. The loader creates and attaches a stub to each of a type's methods when the type is loaded. On the initial
call to the method, the stub passes control to the JIT compiler, that converts the MSIL for that method into
native code and modifies the stub to direct execution to the location of the native code. Subsequent calls of the
JIT-compiled method proceed directly to the native code that was previously generated, reducing the time it
takes to JIT-compile and run the code.
Assembly and Global Assembly Cache (GAC) and Metadata
Assembly: An assembly is the primary building block of a .NET based application. It is a collection of
functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). All
55
managed types and resources are marked either as accessible only within their implementation unit, or as
accessible by code outside that unit. It overcomes the problem of "DLL Hell".The .NET Framework uses
assemblies as the fundamental unit for several purposes:
Security
Type Identity
Reference Scope
Versioning
Deployment
Global Assembly Cache: Assemblies can be shared among multiple applications on the
machine by registering them in the Global Assembly Cache (GAC). The GAC is a machine
wide local cache of assemblies maintained by the .NET Framework. We can register the
assembly to the Global Assembly Cache using the gacutil command.
We can navigate to the GAC directory, "C:\winnt\Assembly", in Windows Explorer. In the
tools menu select the cache properties; in the windows displayed you can set the
memory limit in MB used by the GAC
MetaData: Assemblies have Manifests. This Manifest contains Metadata information of
the Module/Assembly as well as detailed Metadata of other assemblies/modules
referenced (exported). It's the Assembly Manifest that differentiates between an
Assembly and a Module.
What are the mobile devices supported by the .Net platform
The Microsoft .NET Compact Framework is designed to run on mobile devices such as
mobile phones, Personal Digital Assistants (PDAs), and embedded devices. The easiest
way to develop and test a Smart Device Application is to use an emulator.
These devices are divided into the following two main divisions:
1.
Those that are directly supported by .NET (Pocket PCs, i-Mode phones, and WAP
devices)
2.
56
57
58
Protected: Access is limited to the containing class or types derived from the
containing class.
Protected intetnal: Access is limited to the current assembly or types derived from
the containing class.
Struct Type
Enumeration Type
Class
Interface
Delegate
59
object
string
The constituent files can include any file types like image files, text files and so
on. along with DLLs or EXEs
When you compile your source code by default the exe/DLL generated is actually
an assembly
60
Unless your code is bundled as assembly it can not be used in any other
application
When you talk about version of a component you are actually talking about
version of the assembly to which the component belongs.
Every assembly file contains information about itself. This information is called as
Assembly Manifest.
Sign your DLL/EXE with the private key by modifying AssemblyInfo file
Use an installer designed to work with the Global Assembly Cache. This is the
preferred option for installing assemblies into the Global Assembly Cache.
Use a developer tool called the Global Assembly Cache tool (Gacutil.exe),
provided by the .NET Framework SDK.
What is MSIL?
When compiling to managed code, the compiler translates your source code into
Microsoft Intermediate Language (MSIL), which is a CPU-independent set of instructions
that can be efficiently converted to native code. MSIL includes instructions for loading,
storing, initializing, and calling methods on objects, as well as instructions for arithmetic
and logical operations, control flow, direct memory access, exception handling, and other
operations. Before code can be run, MSIL must be converted to CPU-specific code, usually
by a Just-In-Time (JIT) compiler. Because the Common Language Runtime supplies one or
more JIT compilers for each computer architecture it supports, the same set of MSIL can
be JIT-compiled and run on any supported architecture.
When a compiler produces MSIL, it also produces metadata. Metadata describes the
types in your code, including the definition of each type, the signatures of each type's
members, the members that your code references, and other data that the runtime uses
61
at execution time. The MSIL and metadata are contained in a Portable Executable (PE) file
that is based on and extends the published Microsoft PE and common object file format
(COFF) used historically for executable content. This file format, that accommodates MSIL
or native code as well as metadata, enables the operating system to recognize Common
Language Runtime images. The presence of metadata in the file along with the MSIL
enables your code to describe itself, that means that there is no need for type libraries or
Interface Definition Language (IDL). The runtime locates and extracts the metadata from
the file as needed during execution.
What is Jit compilers?.how many are available in clr?
Just-In-Time compiler- it converts the language that you write in .Net into machine
language that a computer can understand. there are tqo types of JITs one is memory
optimized and other is performace optimized.
What is tracing?Where it used.Explain few methods available
Tracing refers to collecting information about the application while it is running. You use
tracing information to troubleshoot an application.
Tracing allows us to observe and correct programming errors. Tracing enables you to
record information in various log files about the errors that might occur at run time. You
can analyze these log files to find the cause of the errors.
In .NET we have objects called Trace Listeners. A listener is an object that receives the
trace output and outputs it somewhere; that somewhere could be a window in your
development environment, a file on your hard drive, a Windows Event log, a SQL Server
or Oracle database, or any other customized data store.
The System.Diagnostics namespace provides the interfaces, classes, enumerations and
structures that are used for tracing The System.Diagnostics namespace provides two
classes named Trace and Debug that are used for writing errors and application execution
information in logs.
All Trace Listeners have the following functions. Functionality of these functions is same
except that the target media for the tracing output is determined by the Trace Listener.
Method Name
Result Fail Outputs the specified text with the Call Stack.
Write Outputs the specified text.
WriteLine Outputs the specified text and a carriage return.
Flush Flushes the output buffer to the target media.
Close Closes the output stream in order to not receive the tracing/debugging output.
How to set the debug mode?
Debug Mode for ASP.NET applications - To set ASP.NET appplication in debugging mode,
edit the application's web.config and assign the "debug" attribute in < compilation >
section to "true" as show below:
< configuration >
< system.web >
< compilation defaultLanguage="vb" debug="true" / >
....
62
...
..
< / configuration >
This case-sensitive attribute "debug tells ASP.NET to generate symbols for dynamically
generated files and enables the
debugger to attach to the ASP.NET application. ASP.NET will detect this change
automatically, without the need to restart the server. Debug Mode for ASP.NET
Webservices, Debugging an XML Web service created with ASP.NET is similar to the
debugging an ASP.NET Web application.
What is the property available to check if the page posted or not?
The Page_Load event handler in the page checks for IsPostBack property value, to
ascertain whether the page is posted. The Page.IsPostBack gets a value indicating
whether the page is being loaded in response to the client postback, or it is for the first
time. The value of Page.IsPostBack is True, if the page is being loaded in response to the
client postback; while its value is False, when the page is loaded for the first time. The
Page.IsPostBack property facilitates execution of certain routine in Page_Load, only once
(for for example in Page load, we need to set default value in controls, when page is
loaded for the first time. On post-back, we check for true value for IsPostback value and
then invoke server-side code to update data).
What are the abstract classes available under system.xml namespace?
The System.XML namespace provides XML related processing ability in .NET framework.
XmlReader and XMLWriter are the two abstract classes at the core of .NET Framework
XML classes:
1.
2.
Both XmlReader and XmlWriter are abstract base classes, that define the functionality
that all derived classes must support.
Is it possible to use multipe inheritance in .net?
Multiple Inheritance is an ability to inherit from more than one base class in other words
ability of a class to have more than one superclass, by inheriting from different sources
and thus combine separately-defined behaviors in a single class. There are two types of
multiple inheritance: multiple type/interface inheritance and multiple implementation
inheritance. C# and VB.NET supports only multiple type/interface inheritance, in other
words
you can derive an class/interface from multiple interfaces. There is no support for
multiple implementation inheritance in .NET. That means a class can only derived from
one class.
What are the derived classes from xmlReader and xmlWriter?
Both XmlReader and XmlWriter are abstract base classes, that define the functionality
that all derived classes must support.
There are three concrete implementations of XmlReader:
63
1.
XmlTextReader
2.
XmlNodeReader
3.
XmlValidatingReader
1.
XmlTextWriter
2.
XmlNodeWriter
XmlTextReader and XmlTextWriter support reading data to/from text-based stream, while
XmlNodeReader and XmlNodeWriter are designed for working with in-memory DOM tree
structure. The custom readers and writers can also be developed to extend the built-in
functionality of XmlReader and XmlWriter.
What is managed and unmanaged code?
The .NET framework provides several core run-time services to the programs that run
within it, for example exception handling and security. For these services to work, the
code must provide a minimum level of information to the runtime. in other words., code
executing under the control of the CLR is called managed code. For example, any code
written in C# or Visual Basic .NET is managed code.
Code that runs outside the CLR is referred to as "unmanaged code." COM components,
ActiveX components, and Win32 API functions are examples of unmanaged code.
How you deploy .NET assemblies?
One way is simply use xcopy. others are use and the setup projects in .net. and one more
way is use of nontuch deployment.
What is Globalizationa and Localization ?
Globalization is the process of creating an application that meets the needs of users from
multiple cultures. It includes using the correct currency, date and time format, calendar,
writing direction, sorting rules, and other issues. Accommodating these cultural
differences in an application is called localization.Using classes of System.Globalization
namespace, you can set application's current culture.
This can be done by using any of the following 3 approaches.
1.
2.
Run-time adjustment
3.
64
65
66
67
PID is the process Id of the application in Windows. Whenever a process starts running in
the Windows environment, it is associated with an individual process Id or PID.
The PID (Process ID) a unique number for each item on the Process Tab, Image Name list.
How do you get the PID to appear? In Task Manger, select the View menu, then select
columns and check PID (Process Identifier).
In Linux, PID is used to debug a process explicitly. However we cannot do this in a
windows environment.
Microsoft has launched a SDK called as Microsoft Operations Management (MOM). This
uses the PID to determine which DLL's have been loaded by a process in the memory.
This is essentially helpful in situations where the Process that has a memory leak is to be
traced to a erring DLL. Personally I have never used a PID, our Windows debugger does
the things required to determine.
What is the GAC? What problem does it solve?
Each computer where the Common Language Runtime is installed has a machine-wide
code cache called the Global Assembly Cache. The Global Assembly Cache stores
assemblies that are to be shared by several applications on the computer. This area is
typically the folder under windows or winnt in the machine.
All the assemblies that need to be shared across applications need to be done through
the Global Assembly Cache only. However it is not necessary to install assemblies into
the Global Assembly Cache to make them accessible to COM interop or unmanaged code.
There are several ways to deploy an assembly into the Global Assembly Cache:
Use an installer designed to work with the Global Assembly Cache. This is the
preferred option for installing assemblies into the Global Assembly Cache.
Use a developer tool called the Global Assembly Cache tool (Gacutil.exe),
provided by the .NET Framework SDK.
GAC solves the problem of DLL Hell and DLL versioning. Unlike earlier situations, GAC can
hold two assemblies of the same name but different version. This ensures that the
applications that access a specific assembly continue to access the same assembly even
if another version of that assembly is installed on that machine.
Describe what an Interface is and how it's different from a Class.
An interface is a structure of code that is similar to a class. An interface is a prototype for
a class and is useful from a logical design perspective. Interfaces provide a means to
define the protocols for a class without worrying about the implementation details. The
syntax for creating interfaces follows:
interface Identifier {
InterfaceBody
}
Identifier is the name of the interface and InterfaceBody refers to the abstract methods
and static final variables that make up the interface. Because it is assumed that all the
methods in an interface are abstract, it isn't necessary to use the abstract keyword
An interface is a description of some of the members available from a class. In practice,
the syntax typically looks similar to a class definition, except that there's no code defined
68
for the methods just their name, the arguments passed and the type of the value
returned.
So what good is it? None by itself. But you create an interface so that classes will
implement it.
But what does it mean to implement an interface. The interface acts as a contract or
promise. If a class implements an interface, then it must have the properties and
methods of the interface defined in the class. This is enforced by the compiler.
Broadly the differentiators between classes and interfaces is as follows
What is the difference between XML Web Services using ASMX and .NET
Remoting using SOAP?
ASP.NET Web services and .NET Remoting provide a full suite of design options for crossprocess and cross-plaform communication in distributed applications. In general, ASP.NET
Web services provide the highest levels of interoperability with full support for WSDL and
SOAP over HTTP, while .NET Remoting is designed for Common Language Runtime typesystem fidelity and supports additional data format and communication channels. Hence
if we looking cross-platform communication than web services is the choice coz for .NET
remoting .Net framework is requried that may or may not present for the other platform.
Serialization and Metadata
ASP.NET Web services rely on the System.Xml.Serialization.XmlSerializer class to marshal
data to and from SOAP messages at runtime. For metadata, they generate WSDL and
XSD definitions that describe what their messages contain. The reliance on pure WSDL
and XSD makes ASP.NET Web services metadata portable; it expresses data structures in
a way that other Web service toolkits on various platforms and with various programming
models can understand. In some cases, this imposes constraints on the types you can
expose from a Web serviceXmlSerializer will only marshal things that can be expressed
in XSD. Specifically, XmlSerializer will not marshal object graphs and it has limited
support for container types.
.NET Remoting relies on the pluggable implementations of the IFormatter interface used
by the System.Runtime.Serialization engine to marshal data to and from messages.
There are two standard formatters,
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter and
System.Runtime.Serialization.Formatters.Soap.SoapFormatter. The BinaryFormatter and
SoapFormatter, as the names suggest, marshal types in binary and SOAP format
respectively. For metadata, .NET Remoting relies on the Common Language Runtime
assemblies, that contain all the relevant information about the data types they
implement, and expose it via reflection. The reliance on the assemblies for metadata
makes it easy to preserve the full runtime type-system fidelity. As a result, when the .NET
Remoting plumbing marshals data, it includes all of a class's public and private members;
handles object graphs correctly; and supports all container types (for example,
69
70
Name uniqueness. Shared assemblies must have names that are globally unique.
Strong names are implemented using standard public key cryptography. In general, the
process works as follows: The author of an assembly generates a key pair (or uses an
existing one), signs the file containing the manifest with the private key, and makes the
public key available to callers. When references are made to the assembly, the caller
records the public key corresponding to the private key used to generate the strong
name.
71
Weak named assemblies are not suitable to be added in GAC and shared. It is essential
for an assembly to be strong named.
Strong naming prevents tampering and enables assemblies to be placed in the GAC
alongside other assemblies of the same name.
How does the generational garbage collector in the .NET CLR manage object
lifetime? What is non-deterministic finalization?
The hugely simplistic version is that every time it garbage-collects, it starts by assuming
everything to be garbage, then goes through and builds a list of everything reachable.
Those become not-garbage, everything else doesn't, and gets thrown away. What makes
it generational is that every time an object goes through this process and survives, it is
noted as being a member of an older generation (up to 2, right now). When the garbagecollector is trying to free memory, it starts with the lowest generation (0) and only works
up to higher ones if it can't free up enough space, on the grounds that shorter-lived
objects are more likely to have been freed than longer-lived ones.
Non-deterministic finalization implies that the destructor (if any) of an object will not
necessarily be run (nor its memory cleaned up, but that's a relatively minor issue)
immediately upon its going out of scope. Instead, it will wait until first the garbage
collector gets around to finding it, and then the finalisation queue empties down to it;
and if the process ends before this happens, it may not be finalised at all. (Although the
operating system will usually clean up any process-external resources left open, note the
usually there, especially as the exceptions tend to hurt a lot.)
What is the difference between Finalize() and Dispose()?
Dispose() is called by the user of an object to indicate that he is finished with it, enabling
that object to release any unmanaged resources it holds. Finalize() is called by the runtime to allow an object that has not had Dispose() called on it to do the same. However,
Dispose() operates determinalistically, whereas there is no guarantee that Finalize() will
be called immediately when an object goes out of scope, or indeed at all, if the program
ends before that object is GCed, and as such Dispose() is generally preferred.
How is the using() pattern useful? What is IDisposable? How does it support
deterministic finalization?
The using() pattern is useful because it ensures that Dispose() will always be called when
a disposable object (defined as one that implements IDisposable, and thus the Dispose()
method) goes out of scope, even if it does so by an exception being thrown, and thus
that resources are always released.
What does this useful command line do? tasklist /m "mscor*"
Lists all the applications and associated tasks/process currently running on the system
with a module whose name begins "mscor" loaded into them; that in nearly all cases in
other words "all the .NET processes".
What's wrong with a line like this? DateTime.Parse(myString);
Therez nothing wrong with this declaration.Converts the specified string representation of
a date and time to its DateTime equivalent.But If the string is not a valid DateTime,It
throws an exception.
What are PDBs? Where must they be located for debugging to work?
A program database (PDB) files holds debugging and project state information that allows
incremental linking of debug configuration of your program.There are several different
types of symbolic debugging information. The default type for Microsoft compiler is the
72
so-called PDB file. The compiler setting for creating this file is /Zi, or /ZI for C/C++(that
creates a PDB file with additional information that enables a feature called ""Edit and
Continue"") or a Visual Basic/C#/JScript .NET program with /debug.
A PDB file is a separate file, placed by default in the Debug project subdirectory, that has
the same name as the executable file with the extension .pdb. Note that the Visual C++
compiler by default creates an additional PDB file called VC60.pdb for VisulaC++6.0 and
VC70.PDB file for VisulaC++7.0. The compiler creates this file during compilation of the
source code, when the compiler isn't aware of the final name of the executable. The
linker can merge this temporary PDB file into the main one if you tell it to, but it won't do
it by default. The PDB file can be useful to display the detailed stack trace with source
files and line numbers.
What is FullTrust? Do GAC'ed assemblies have FullTrust?
Before the .NET Framework existed, Windows had two levels of trust for downloaded
code. This old model was a binary trust model. You only had two choices: Full Trust, and
No Trust. The code could either do anything you could do, or it wouldn't run at all.
The permission sets in .NET include FullTrust, SkipVerification, Execution, Nothing,
LocalIntranet, Internet and Everything. Full Trust Grants unrestricted permissions to
system resources. Fully trusted code run by a normal, nonprivileged user cannot do
administrative tasks, but can access any resources the user can access, and do anything
the user can do. From a security standpoint, you can think of fully trusted code as being
similar to native, unmanaged code, like a traditional ActiveX control.
GAC assemblies are granted FullTrust. In v1.0 and 1.1, the fact that assemblies in the
GAC seem to always get a FullTrust grant is actually a side effect of the fact that the GAC
lives on the local machine. If anyone were to lock down the security policy by changing
the grant set of the local machine to something less than FullTrust, and if your assembly
did not get extra permission from some other code group, it would no longer have
FullTrust even though it lives in the GAC.
What does this do? gacutil /l | find /i "Corillian"
The Global Assembly Cache tool allows you to view and manipulate the contents of the
Global Assembly Cache and download cache.The tool comes with various optional
params to do that.
""/l"" option Lists the contents of the Global Assembly Cache. If you specify the
assemblyName parameter(/l [assemblyName]), the tool lists only the assemblies
matching that name.
What does this do .. sn -t foo.dll ?
Sn -t option displays the token for the public key stored in infile. The contents of infile
must be previously generated using -p.
Sn.exe computes the token using a hash function from the public key. To save space, the
Common Language Runtime stores public key tokens in the manifest as part of a
reference to another assembly when it records a dependency to an assembly that has a
strong name. The -tp option displays the public key in addition to the token.
How do you generate a strong name?
.NET provides an utility called strong name tool. You can run this toolfrom the VS.NET
command prompt to generate a strong name with an option "-k" and providing the strong
key file name. in other words sn- -k < file-name >
What is the difference between a Debug and Release build? Is there a
73
74
75
1.
2.
Together they form a unique name. The various purpose of XML Namespace are
<
<
<
<
<
<
<
<
<
<
<
<
<
<
1.
Combine fragments from various documents without any naming conflicts. (See
example below.)
2.
Write reusable code modules that can be invoked for specific elements and
attributes. Universally unique names guarantee that such modules are invoked
only for the correct elements and attributes.
3.
Define elements and attributes that can be reused in other schemas or instance
documents without fear of name collisions. For example, you might use XHTML
elements in a parts catalog to provide part descriptions. Or you might use the nil
attribute defined in XML Schemas to indicate a missing value.
Department >
Name >DVS1< /Name >
addr:Address xmlns:addr="http://www.tu-darmstadt.de/ito/addresses" >
addr:Street >Wilhelminenstr. 7< /addr:Street >
addr:City >Darmstadt< /addr:City >
addr:State >Hessen< /addr:State >
addr:Country >Germany< /addr:Country >
addr:PostalCode >D-64285< /addr:PostalCode >
/addr:Address >
serv:Server xmlns:serv="http://www.tu-darmstadt.de/ito/servers" >
serv:Name >OurWebServer< /serv:Name >
serv:Address >123.45.67.8< /serv:Address >
/serv:Server >
/Department >
76
1.
Check up the total space if there's any free space on the declared list.
2.
3.
4.
Create new Array with size ( Last Array Size + Increase Value )
5.
Copy back values from temp and reference this new array as original array.
6.
77
78
1.
.NET class should be implement its functionality through interface. First define
interface in code, then have the class to imlpement it. This way, it prevents
breaking of COM client, if/when .NET component changes.
2.
Secondly, .NET class, that is to be visible to COM clients must be declared public.
The tools that create the CCW only define types based on public classes. The
same rule applies to methods, properties, and events that will be used by COM
clients.
Implementation Steps -
1.
Generate type library of .NET component, using TLBExporter utility. A type library
is the COM equivalent of the metadata contained within
a .NET assembly. Type libraries are generally contained in files with the
extension .tlb. A type library contains the necessary information to allow a COM
client to determine which classes are located in a specific server, as well as the
methods, properties, and events supported by those classes.
2.
Secondly, use Assembly Registration tool (regasm) to create the type library and
register it.
3.
79
The Type Library Exporter generates a type library that describes the types defined in a
Common Language Runtime assembly.
The Type Library Importer converts the type definitions found within a COM type library
into equivalent definitions in a Common Language Runtime assembly. The output of
Tlbimp.exe is a binary file (an assembly) that contains runtime metadata for the types
defined within the original type library.
What benefit do you get from using a Primary Interop Assembly (PIA)?
PIAs are important because they provide unique type identity. The PIA distinguishes the
official type definitions from counterfeit definitions provided by other interop assemblies.
Having a single type identity ensures type compatibility among applications that share
the types defined in the PIA. Because the PIA is signed by its publisher and labeled with
the PrimaryInteropAssembly attribute, it can be differentiated from other interop
assemblies that define the same types.
ADO.NET
Explain what a diffgram is and its usage ?
A DiffGram is an XML format that is used to identify current and original versions of data
elements. The DataSet uses the DiffGram format to load and persist its contents, and to
serialize its contents for transport across a network connection. When a DataSet is
written as a DiffGram, it populates the DiffGram with all the necessary information to
accurately recreate the contents, though not the schema, of the DataSet, including
column values from both the Original and Current row versions, row error information,
and row order.
When sending and retrieving a DataSet from an XML Web service, the DiffGram format is
implicitly used. Additionally, when loading the contents of a DataSet from XML using the
ReadXml method, or when writing the contents of a DataSet in XML using the WriteXml
method, you can select that the contents be read or written as a DiffGram.
The DiffGram format is divided into three sections: the current data, the original (or
"before") data, and an errors section, as shown in the following example.
<?xml version="1.0"?>
<diffgr:diffgram
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<DataInstance>
</DataInstance>
<diffgr:before>
</diffgr:before>
<diffgr:errors>
</diffgr:errors>
</diffgr:diffgram>
The DiffGram format consists of the following blocks of data:
<DataInstance>
The name of this element, DataInstance, is used for explanation purposes in this
documentation. A DataInstance element represents a DataSet or a row of a DataTable.
Instead of DataInstance, the element would contain the name of the DataSet or
DataTable. This block of the DiffGram format contains the current data, whether it has
been modified or not. An element, or row, that has been modified is identified with the
80
diffgr:hasChanges annotation.
<diffgr:before>
This block of the DiffGram format contains the original version of a row. Elements in this
block are matched to elements in the DataInstance block using the diffgr:id annotation.
<diffgr:errors>
This block of the DiffGram format contains error information for a specific row in the
DataInstance block. Elements in this block are matched to elements in the DataInstance
block using the diffgr:id annotation.
Which method do you invoke on the DataAdapter control to load your
generated dataset with data?
You must use the Fill method of the DataAdapter control and pass the dataset object as
an argument to load the generated data.
Can you edit data in the Repeater control?
NO.
Which are the various IsolationLevels ?
Following are the various IsolationLevels:
Read Committed A transaction cannot read data that is being modified by another
transaction that has not committed. This is the default isolation level in
Microsoft SQL Server.
Read Uncommitted A transaction can read any data, even if it is being modified by
another transaction. This is the least safe isolation level but allows the highest
concurrency.
Any Any isolation level is supported. This setting is most commonly used by
downstream components to avoid conflicts. This setting is useful because any
downstream component must be configured with an isolation level that is equal to
or less than the isolation level of its immediate upstream component. Therefore, a
downstream component that has its isolation level configured as Any always uses
the same isolation level that its immediate upstream component uses. If the root
object in a transaction has its isolation level configured to Any, its isolation level
becomes Serialized.
81
82
the data store, even though other transactions may be running at the same time. A
transaction should never see the intermediate stages of another transaction.
Transactions attain the highest level of isolation when they are serializable. At this level,
the results obtained from a set of concurrent transactions are identical to the results
obtained by running each transaction serially. Because a high degree of isolation can
limit the number of concurrent transactions, some applications reduce the isolation level
in exchange for better throughput.
Durability
A transaction is also a unit of recovery. If a transaction succeeds, the system guarantees
that its updates will persist, even if the computer crashes immediately after the commit.
Specialized logging allows the system's restart procedure to complete unfinished
operations, making the transaction durable.
Whate are various types of Commands available with DataAdapter ?
The SqlDataAdapter has SelectCommand, InsertCommand, DeleteCommand and
UpdateCommand
What is a Dataset?
Datasets are the result of bringing together ADO and XML. A dataset contains one or
more data of tabular XML, known as DataTables, these data can be treated separately, or
can have relationships defined among them. Indeed these relationships give you ADO
data SHAPING without needing to master the SHAPE language, that many people are not
comfortable with.
The dataset is a disconnected in-memory cache database. The dataset object model
looks like this:
Dataset
DataTableCollection
DataTable
DataView
DataRowCollection
DataRow
DataColumnCollection
DataColumn
ChildRelations
ParentRelations
Constraints
PrimaryKey
DataRelationCollection
Let's have a look at each of these:
DataTableCollection: As we say that a DataSet is an in-memory database. So it has this
collection, that holds data from multiple tables in a single DataSet object.
DataTable: In the DataTableCollection, we have DataTable objects, that represents the
individual tables of the dataset.
DataView: The way we have views in database, same way we can have DataViews. We
can use these DataViews to do Sort, filter data.
DataRowCollection: Similar to DataTableCollection, to represent each row in each Table
we have DataRowCollection.
DataRow: To represent each and every row of the DataRowCollection, we have
DataRows.
83
DataAdapter: Populates a DataSet and resolves updates with the data source.
The .NET Framework includes the .NET Framework Data Provider for SQL Server (for
Microsoft SQL Server version 7.0 or later), the .NET Framework Data Provider for OLE DB,
and the .NET Framework Data Provider for ODBC.
The .NET Framework Data Provider for SQL Server: The .NET Framework Data Provider for
SQL Server uses its own protocol to communicate with SQL Server. It is lightweight and
performs well because it is optimized to access a SQL Server directly without adding an
OLE DB or Open Database Connectivity (ODBC) layer. The following illustration contrasts
the .NET Framework Data Provider for SQL Server with the .NET Framework Data Provider
for OLE DB. The .NET Framework Data Provider for OLE DB communicates to an OLE DB
data source through both the OLE DB Service component, that provides connection
pooling and transaction services, and the OLE DB Provider for the data source
The .NET Framework Data Provider for OLE DB: The .NET Framework Data Provider for
OLE DB uses native OLE DB through COM interoperability to enable data access. The
.NET Framework Data Provider for OLE DB supports both local and distributed
84
transactions. For distributed transactions, the .NET Framework Data Provider for OLE DB,
by default, automatically enlists in a transaction and obtains transaction details from
Windows 2000 Component Services.
The .NET Framework Data Provider for ODBC: The .NET Framework Data Provider for
ODBC uses native ODBC Driver Manager (DM) through COM interoperability to enable
data access. The ODBC data provider supports both local and distributed transactions.
For distributed transactions, the ODBC data provider, by default, automatically enlists in
a transaction and obtains transaction details from Windows 2000 Component Services.
The .NET Framework Data Provider for Oracle: The .NET Framework Data Provider for
Oracle enables data access to Oracle data sources through Oracle client connectivity
software. The data provider supports Oracle client software version 8.1.7 and later. The
data provider supports both local and distributed transactions (the data provider
automatically enlists in existing distributed transactions, but does not currently support
the EnlistDistributedTransaction method).
The .NET Framework Data Provider for Oracle requires that Oracle client software (version
8.1.7 or later) be installed on the system before you can use it to connect to an Oracle
data source.
.NET Framework Data Provider for Oracle classes are located in the
System.Data.OracleClient namespace and are contained in the
System.Data.OracleClient.dll assembly. You will need to reference both the
System.Data.dll and the System.Data.OracleClient.dll when compiling an application that
uses the data provider.
Choosing a .NET Framework Data Provider
.NET Framework Data Provider for SQL Server: Recommended for middle-tier applications
using Microsoft SQL Server 7.0 or later. Recommended for single-tier applications using
Microsoft Data Engine (MSDE) or Microsoft SQL Server 7.0 or later.
Recommended over use of the OLE DB Provider for SQL Server (SQLOLEDB) with the .NET
Framework Data Provider for OLE DB. For Microsoft SQL Server version 6.5 and earlier,
you must use the OLE DB Provider for SQL Server with the .NET Framework Data Provider
for OLE DB.
.NET Framework Data Provider for OLE DB: Recommended for middle-tier applications
using Microsoft SQL Server 6.5 or earlier, or any OLE DB provider. For Microsoft SQL
Server 7.0 or later, the .NET Framework Data Provider for SQL Server is recommended.
Recommended for single-tier applications using Microsoft Access databases. Use of a
Microsoft Access database for a middle-tier application is not recommended.
.NET Framework Data Provider for ODBC: Recommended for middle-tier applications
using ODBC data sources. Recommended for single-tier applications using ODBC data
sources.
.NET Framework Data Provider for Oracle: Recommended for middle-tier applications
using Oracle data sources. Recommended for single-tier applications using Oracle data
sources. Supports Oracle client software version 8.1.7 and later. The .NET Framework
Data Provider for Oracle classes are located in the System.Data.OracleClient namespace
and are contained in the System.Data.OracleClient.dll assembly. You need to reference
both the System.Data.dll and the System.Data.OracleClient.dll when compiling an
application that uses the data provider.
Can you explain the difference between an ADO.NET Dataset and an ADO
Recordset?
Let's have a look at the differences between ADO Recordset and ADO.Net DataSet:
85
1.
Table Collection: ADO Recordset provides the ability to navigate through a single
table of information. That table would have been formed with a join of multiple
tables and returning columns from multiple tables. ADO.NET DataSet is capable of
holding instances of multiple tables. It has got a Table Collection, that holds
multiple tables in it. If the tables are having a relation, then it can be manipulated
on a Parent-Child relationship. It has the ability to support multiple tables with
keys, constraints and interconnected relationships. With this ability the DataSet
can be considered as a small, in-memory relational database cache.
2.
3.
Connectivity Model: The ADO Recordset was originally designed without the
ability to operate in a disconnected environment. ADO.NET DataSet is specifically
designed to be a disconnected in-memory database. ADO.NET DataSet follows a
pure disconnected connectivity model and this gives it much more scalability and
versatility in the amount of things it can do and how easily it can do that.
4.
5.
Firewalls and DCOM and Remoting: Those who have worked with DCOM know
that how difficult it is to marshal a DCOM component across a router. People
generally came up with workarounds to solve this issue. ADO.NET DataSet uses
Remoting, through which a DataSet / DataTable component can be serialized into
XML, sent across the wire to a new AppDomain, and then Desterilized back to a
fully functional DataSet. As the DataSet is completely disconnected, and it has no
dependency, we lose absolutely nothing by serializing and transferring it through
Remoting.
86
show how to implement this type of flag and how to maintain its value after each
database update.
Is Your Glass Half Full?
There are three common techniques for managing what happens when users try to
modify the same data at the same time: pessimistic, optimistic, and last-in wins. They
each handle concurrency issues differently.
The pessimistic approach says: "Nobody can cause a concurrency violation with my data
if I do not let them get at the data while I have it." This tactic prevents concurrency in the
first place but it limits scalability because it prevents all concurrent access. Pessimistic
concurrency generally locks a row from the time it is retrieved until the time updates are
flushed to the database. Since this requires a connection to remain open during the
entire process, pessimistic concurrency cannot successfully be implemented in a
disconnected model like the ADO.NET DataSet, that opens a connection only long enough
to populate the DataSet then releases and closes, so a database lock cannot be held.
Another technique for dealing with concurrency is the last-in wins approach. This model
is pretty straightforward and easy to implement-whatever data modification was made
last is what gets written to the database. To implement this technique you only need to
put the primary key fields of the row in the UPDATE statement's WHERE clause. No
matter what is changed, the UPDATE statement will overwrite the changes with its own
changes since all it is looking for is the row that matches the primary key values. Unlike
the pessimistic model, the last-in wins approach allows users to read the data while it is
being edited on screen. However, problems can occur when users try to modify the same
data at the same time because users can overwrite each other's changes without being
notified of the collision. The last-in wins approach does not detect or notify the user of
violations because it does not care. However the optimistic technique does detect
violations. Contd....
In optimistic concurrency models, a row is only locked during the update to the database.
Therefore the data can be retrieved and updated by other users at any time other than
during the actual row update operation. Optimistic concurrency allows the data to be
read simultaneously by multiple users and blocks other users less often than its
pessimistic counterpart, making it a good choice for ADO.NET. In optimistic models, it is
important to implement some type of concurrency violation detection that will catch any
additional attempt to modify records that have already been modified but not committed.
You can write your code to handle the violation by always rejecting and canceling the
change request or by overwriting the request based on some business rules. Another way
to handle the concurrency violation is to let the user decide what to do. The sample
application that is shown in Figure 1 illustrates some of the options that can be presented
to the user in the event of a concurrency violation.
Where Did My Changes Go?
When users are likely to overwrite each other's changes, control mechanisms should be
put in place. Otherwise, changes could be lost. If the technique you're using is the last-in
wins approach, then these types of overwrites are entirely possible.For example, imagine
Julie wants to edit an employee's last name to correct the spelling. She navigates to a
screen that loads the employee's information into a DataSet and has it presented to her
in a Web page. Meanwhile, Scott is notified that the same employee's phone extension
has changed. While Julie is correcting the employee's last name, Scott begins to correct
his extension. Julie saves her changes first and then Scott saves his.Assuming that the
application uses the last-in wins approach and updates the row using a SQL WHERE
clause containing only the primary key's value, and assuming a change to one column
requires the entire row to be updated, neither Julie nor Scott may immediatelyrealize the
concurrency issue that just occurred. In this specific situation, Julie's changes were
overwritten by Scott's changes because he saved last, and the last name reverted to the
misspelled version.
87
So as you can see, even though the users changed various fields, their changes collided
and caused Julie's changes to be lost. Without some sort of concurrency detection and
handling, these types of overwrites can occur and even go unnoticed.When you run the
sample application included in this column's download, you should open two separate
instances of Microsoft Internet Explorer. When I generated the conflict, I opened two
instances to simulate two users with two separate sessions so that a concurrency
violation would occur in the sample application. When you do this, be careful not to use
Ctrl+N because if you open one instance and then use the Ctrl+N technique to open
another instance, both windows will share the same session.
Detecting Violations
The concurrency violation reported to the user in Figure 1 demonstrates what can happen
when multiple users edit the same data at the same time. In Figure 1, the user attempted
to modify the first name to "Joe" but since someone else had already modified the last
name to "Fuller III," a concurrency violation was detected and reported. ADO.NET detects
a concurrency violation when a DataSet containing changed values is passed to a
SqlDataAdapter's Update method and no rows are actually modified. Simply using the
primary key (in this case the EmployeeID) in the UPDATE statement's WHERE clause will
not cause a violation to be detected because it still updates the row (in fact, this
technique has the same outcome as the last-in wins technique). Instead, more conditions
must be specified in the WHERE clause in order for ADO.NET to detect the violation.
The key here is to make the WHERE clause explicit enough so that it not only checks the
primary key but that it also checks for another appropriate condition. One way to
accomplish this is to pass in all modifiable fields to the WHERE clause in addition to the
primary key. For example, the application shown in Figure 1 could have its UPDATE
statement look like the Stored Procedure that's shown in Figure 2.
Notice that in the code in Figure 2 nullable columns are also checked to see if the value
passed in is NULL. This technique is not only messy but it can be difficult to maintain by
hand and it requires you to test for a significant number of WHERE conditions just to
update a row. This yields the desired result of only updating rows where none of the
values have changed since the last time the user got the data, but there are other
techniques that do not require such a huge WHERE clause.
Another way to ensure that the row is only updated if it has not been modified by another
user since you got the data is to add a timestamp column to the table. The SQL
Server(tm) TIMESTAMP datatype automatically updates itself with a new value every time
a value in its row is modified. This makes it a very simple and convenient tool to help
detect concurrency violations.
A third technique is to use a DATETIME column in which to track changes to its row. In my
sample application I added a column called LastUpdateDateTime to the Employees
table.
ALTER TABLE Employees ADD LastUpdateDateTime DATETIME
There I update the value of the LastUpdateDateTime field automatically in the UPDATE
Stored Procedure using the built-in SQL Server GETDATE function.
The binary TIMESTAMP column is simple to create and use since it automatically
regenerates its value each time its row is modified, but since the DATETIME column
technique is easier to display on screen and demonstrate when the change was made, I
chose it for my sample application. Both of these are solid choices, but I prefer the
TIMESTAMP technique since it does not involve any additional code to update its value.
Retrieving Row Flags
88
89
class could live in a logical or physical middle tier. (I wanted to make this a separate class
so it would be easy to pull the code out and separate it from the presentation logic.)
Notice that I did not use the GetChanges method to pull out only the modified rows and
pass them to the Employee object's Save method. I skipped this step here since there is
only one row. However, if there were multiple rows in the DataSet's DataTable, it would
be better to use the GetChanges method to create a DataSet that contains only the
modified rows.
If the save succeeds, the Employee.SaveEmployee method returns a DataSet containing
the modified row and its newly updated row version flag (in this case, the
LastUpdateDateTime field's value). This DataSet is then merged into the original DataSet
so that the LastUpdateDateTime field's value can be updated in the original DataSet. This
must be done because if the user wants to make more changes she will need the current
values from the database merged back into the local DataSet and shown on screen. This
includes the LastUpdateDateTime value that is used in the WHERE clause. Without this
field's current value, a false concurrency violation would occur.
Reporting Violations
If a concurrency violation occurs, it will bubble up and be caught by the exception
handler shown in Figure 3 in the catch block for DBConcurrencyException. This block calls
the FillConcurrencyValues method, that displays both the original values in the DataSet
that were attempted to be saved to the database and the values currently in the
database. This method is used merely to show the user why the violation occurred.
Notice that the exDBC variable is passed to the FillConcurrencyValues method. This
instance of the special database concurrency exception class (DBConcurrencyException)
contains the row where the violation occurred. When a concurrency violation occurs, the
screen is updated to look like Figure 1.
The DataSet not only stores the schema and the current data, it also tracks changes that
have been made to its data. It knows which rows and columns have been modified and it
keeps track of the before and after versions of these values. When accessing a column's
value via the DataRow's indexer, in addition to the column index you can also specify a
value using the DataRowVersion enumerator. For example, after a user changes the value
of the last name of an employee, the following lines of C# code will retrieve the original
and current values stored in the LastName column:
string sLastName_Before = oEmpRow["LastName", DataRowVersion.Original];
string sLastName_After = oEmpRow["LastName", DataRowVersion.Current];
The FillConcurrencyValues method uses the row from the DBConcurrencyException and
gets a fresh copy of the same row from the database. It then displays the values using
the DataRowVersion enumerators to show the original value of the row before the update
and the value in the database alongside the current values in the textboxes.
User's Choice
Once the user has been notified of the concurrency issue, you could leave it up to her to
decide how to handle it. Another alternative is to code a specific way to deal with
concurrency, such as always handling the exception to let the user know (but refreshing
the data from the database). In this sample application I let the user decide what to do
next. She can either cancel changes, cancel and reload from the database, save changes,
or save anyway.
The option to cancel changes simply calls the RejectChanges method of the DataSet and
rebinds the DataSet to the controls in the ASP.NET page. The RejectChanges method
reverts the changes that the user made back to its original state by setting all of the
current field values to the original field values. The option to cancel changes and reload
90
the data from the database also rejects the changes but additionally goes back to the
database via the Employee class in order to get a fresh copy of the data before rebinding
to the control on the ASP.NET page.
The option to save changes attempts to save the changes but will fail if a concurrency
violation is encountered. Finally, I included a "save anyway" option. This option takes the
values the user attempted to save and uses the last-in wins technique, overwriting
whatever is in the database. It does this by calling a different command object associated
with a Stored Procedure that only uses the primary key field (EmployeeID) in the WHERE
clause of the UPDATE statement. This technique should be used with caution as it will
overwrite the record.
If you want a more automatic way of dealing with the changes, you could get a fresh
copy from the database. Then overwrite just the fields that the current user modified,
such as the Extension field. That way, in the example I used the proper LastName would
not be overwritten. Use this with caution as well, however, because if the same field was
modified by both users, you may want to just back out or ask the user what to do next.
What is obvious here is that there are several ways to deal with concurrency violations,
each of which must be carefully weighed before you decide on the one you will use in
your application.
Wrapping It Up
Setting the SqlDataAdapter's ContinueUpdateOnError property tells the SqlDataAdapter
to either throw an exception when a concurrency violation occurs or to skip the row that
caused the violation and to continue with the remaining updates. By setting this property
to false (its default value), it will throw an exception when it encounters a concurrency
violation. This technique is ideal when only saving a single row or when you are
attempting to save multiple rows and want them all to commit or all to fail.
I have split the topic of concurrency violation management into two parts. Next time I will
focus on what to do when multiple rows could cause concurrency violations. I will also
discuss how the DataViewRowState enumerators can be used to show what changes
have been made to a DataSet.
How you will set the datarelation between two columns?
ADO.NET provides DataRelation object to set relation between two columns.It helps to
enforce the following constraints,a unique constraint, that guarantees that a column in
the table contains no duplicates and a foreign-key constraint,that can be used to
maintain referential integrity.A unique constraint is implemented either by simply setting
the Unique property of a data column to true, or by adding an instance of the
UniqueConstraint class to the DataRelation object's ParentKeyConstraint. As part of the
foreign-key constraint, you can specify referential integrity rules that are applied at three
points,when a parent record is updated,when a parent record is deleted and when a
change is accepted or rejected.
WebServices And Windows Services
Can you give an example of when it would be appropriate to use a web service as
opposed to non-serviced .NET component
Web service is one of main component in Service Oriented Architecture. You could use
web services when your clients and servers are running on different networks and also
different platforms. This provides a loosely coupled system. And also if the client is
behind the firewall it would be easy to use web service since it runs on port 80 (by
default) instead of having some thing else in Service Oriented Architecture applications.
What is the standard you use to wrap up a call to a Web service
"SOAP.
91
"
What is the transport protocol you use to call a Web service SOAP
HTTP with SOAP
What does WSDL stand for?
"WSDL stands for Web Services Dsescription Langauge. There is WSDL.exe that creates a
.wsdl Files that defines how an XML Web service behaves and instructs clients as to how
to interact with the service.
eg: wsdl http://LocalHost/WebServiceName.asmx"
Where on the Internet would you look for Web Services?
www.uddi.org
What does WSDL stand for?
Web Services Description Language
True or False: To test a Web service you must create a windows application or
Web application to consume this service?
False.
What are the various ways of accessing a web service ?
1. Asynchronous Call
Application can make a call to the Webservice and then continue todo watever oit wants
to do.When the service is ready it will notify the application.Application can use BEGIN
and END method to make asynchronous call to the webmethod.We can use either a
WaitHandle or a Delegate object when making asynchronous call.
The WaitHandle class share resources between several objects. It provides several
methods that will wait for the resources to become available
The easiest and most powerful way to to implement an asynchronous call is using a
delegate object. A delegate object wraps up a callback function. The idea is to pass a
method in the invocation of the web method. When the webmethod has finished it will
call this callback function to process the result
2. Synchronous Call
Application has to wait until execution has completed.
Note: Few of the references are taken from other sites/sources
What are VSDISCO files?
VSDISCO files are DISCO files that support dynamic discovery of Web services. If you
place the following VSDISCO file in a directory on your Web server, for example, it returns
references to all ASMX and DISCO files in the host directory and any subdirectories not
noted in <EXCLUDE>elements:
<DYNAMICDISCOVERY
xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
<EXCLUDE path="_vti_cnf" />
<EXCLUDE path="_vti_pvt" />
<EXCLUDE path="_vti_log" />
92
93
94
Right-click the Taskbar, and then click Task Manager. The Windows Task Manager
dialog box appears.
Click the Processes tab of the Windows Task Manager dialog box.
Under Image Name, click the image name of the process that hosts the service
that you want to debug. Note the process ID of this process as specified by the
value of the corresponding PID field.
Click Start, and then click Run. The Run dialog box appears.
At the command prompt, change the directory path to reflect the location of the
tlist.exe file on your computer
Note: The tlist.exe file is typically located in the following directory: C:\Program
Files\Debugging Tools for Windows
d. At the command prompt, type tlist to list the image names and the process IDs
of all processes that are currently running on your computer.
Note Make a note of the process ID of the process that hosts the service that you want to
debug.
2. At a command prompt, change the directory path to reflect the location of the
windbg.exe file on your computer.
Note: If a command prompt is not open, follow steps a and b of Method 1. The
windbg.exe file is typically located in the following directory: C:\Program Files\Debugging
Tools for Windows.
3. At the command prompt, type windbg p ProcessID to attach the WinDbg debugger to
the process that hosts the service that you want to debug.
Note ProcessID is a placeholder for the process ID of the process that hosts the service
that you want to debug.
95
Use the image name of the process that hosts the service that you want to debug
You can use this method only if there is exactly one running instance of the process that
hosts the service that you want to run. To do this, follow these steps:
1.
Click Start, and then click Run. The Run dialog box appears.
2.
In the Open box, type cmd, and then click OK to open a command prompt.
3.
At the command prompt, change the directory path to reflect the location of the
windbg.exe file on your computer.
Note: The windbg.exe file is typically located in the following directory: C:\Program
Files\Debugging Tools for Windows.
4. At the command prompt, type windbg pn ImageName to attach the WinDbg
debugger to the process that hosts the service that you want to debug.
NoteImageName is a placeholder for the image name of the process that hosts the
service that you want to debug. The "-pn" command-line option specifies that the
ImageName command-line argument is the image name of a process.
back to the top
Start the WinDbg debugger and attach to the process that hosts the service that you
want to debug
1.
2.
3.
4.
On the File menu, click Attach to a Process to display the Attach to Process dialog
box.
5.
Click to select the node that corresponds to the process that hosts the service
that you want to debug, and then click OK.
6.
In the dialog box that appears, click Yes to save base workspace information.
Notice that you can now debug the disassembled code of your service.
96
In the Image File Name text box, type the image name of the process that hosts
the service that you want to debug. For example, if you want to debug a service
that is hosted by a process that has MyService.exe as the image name, type
MyService.exe.
Under Image Debugger Options, click to select the Debugger check box.
In the Debugger text box, type the full path of the debugger that you want to use.
For example, if you want to use the WinDbg debugger to debug a service, you can
type a full path that is similar to the following: C:\Program Files\Debugging Tools
for Windows\windbg.exe
Click Apply, and then click OK to quit the Global Flags Editor.
Click Start, and then click Run. The Run dialog box appears.
In the Open box, type regedit, and then click OK to start Registry Editor.
Warning If you use Registry Editor incorrectly, you may cause serious problems
that may require you to reinstall your operating system. Microsoft cannot
guarantee that you can solve problems that result from using Registry Editor
incorrectly. Use Registry Editor at your own risk.
In Registry Editor, locate, and then right-click the following registry subkey:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image
File Execution Options
Point to New, and then click Key. In the left pane of Registry Editor, notice that
New Key #1 (the name of a new registry subkey) is selected for editing.
Type ImageName to replace New Key #1, and then press ENTER.
Note ImageName is a placeholder for the image name of the process that hosts
the service that you want to debug. For example, if you want to debug a service
that is hosted by a process that has MyService.exe as the image name, type
MyService.exe.
97
Point to New, and then click String Value. In the right pane of Registry Editor,
notice that New Value #1, the name of a new registry entry, is selected for
editing.
Right-click the Debugger registry entry that you created in step h, and then click
Modify. The Edit String dialog box appears.
In the Value data text box, type DebuggerPath, and then click OK.
Note: DebuggerPath is a placeholder for the full path of the debugger that you
want to use. For example, if you want to use the WinDbg debugger to debug a
service, you can type a full path that is similar to the following: C:\Program
Files\Debugging Tools for Windows\windbg.exe
2. For the debugger window to appear on your Desktop, and to interact with the
debugger, make your service interactive. If you do not make your service interactive, the
debugger will start but you cannot see it and you cannot issue commands. To make your
service interactive, use one of the following methods:
Method 1: Use the Services console
On the Programs menu, point to Administrative Tools, and then click Services. The
Services console appears.
In the right pane of the Services console, right-click ServiceName, and then click
Properties.
Note: ServiceName is a placeholder for the name of the service that you want to
debug.
On the Log On tab, click to select the Allow service to interact with Desktop check
box under Local System account, and then click OK.
In Registry Editor, locate, and then click the following registry subkey:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\ServiceName
Note Replace ServiceName with the name of the service that you want to debug.
For example, if you want to debug a service named MyService, locate and then
click the following registry key:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MyService
Under the Name field in the right pane of Registry Editor, right-click Type, and
then click Modify. The Edit DWORD Value dialog box appears.
Change the text in the Value data text box to the result of the binary OR operation
with the binary value of the current text and the binary value, 0x00000100, as the
two operands. The binary value, 0x00000100, corresponds to the
SERVICE_INTERACTIVE_PROCESS constant that is defined in the WinNT.h header
98
3. When a service starts, the service communicates to the Service Control Manager how
long the service must need to start (the time-out period for the service). If the Service
Control Manager does not receive a "service started" notice from the service within this
time-out period, the Service Control Manager terminates the process that hosts the
service. This time-out period is typically less than 30 seconds. If you do not adjust this
time-out period, the Service Control Manager ends the process and the attached
debugger while you are trying to debug. To adjust this time-out period, follow these
steps:
In Registry Editor, locate, and then right-click the following registry subkey:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
Point to New, and then click DWORD Value. In the right pane of Registry Editor,
notice that New Value #1 (the name of a new registry entry) is selected for
editing.
Type ServicesPipeTimeout to replace New Value #1, and then press ENTER.
Right-click the ServicesPipeTimeout registry entry that you created in step c, and
then click Modify. The Edit DWORD Value dialog box appears.
In the Value data text box, type TimeoutPeriod, and then click OK
Note: TimeoutPeriod is a placeholder for the value of the time-out period (in
milliseconds) that you want to set for the service. For example, if you want to set
the time-out period to 24 hours (86400000 milliseconds), type 86400000.
Restart the computer. You must restart the computer for Service Control Manager
to apply this change.
On the Programs menu, point to Administrative Tools, and then click Services. The
Services console appears.
In the right pane of the Services console, right-click ServiceName, and then click
Start.
Note: ServiceName is a placeholder for the name of the service that you want to
debug.
99
100
5. An abstract class is allowed to have all access modifiers for all of its member
declarations whereas in an interface we cannot declare any access modifier
(including public) since all the members of an interface are implicitly public.
Note: here I am talking about the access specifiers of the member of interfaces
and not about the interface.
101
In this approach we can define multiple methods with the same name changing
their signature. In other words different parameters
Doesn't require any permission from the parent for overloading its method in the
child
Overriding
It is an approach of defining multiple methods with the same name and the same
signature
Requires an explicit permission from the parent to override its methods in the
child
102
103
Assigning:
StringBuilder sbuild= new
StringBuilder("something important");
Assigning:
String s= "something important";
ArrayList
BitArray
Stack
Queue
Comparer
HashTable
SortedList
ArrayList
The ArrayList is one of the important classes in the System.Collection namespace. We
can say it is the next generation of the Array in C#.
ArrayList is a dynamic array; it will increase the size of the storage location as required. It
stores the value as an object. The allocation of the ArrayList can be done through the
TrimToSize property.
Methods
1 Add
2 AddRange
104
3 Clear
4
BinarySearc
It will return the position of the search object as integer value.
h
5 Insert
It will insert the element in the specified location of the index in the
ArrayList.
6 InsertRange
7 Remove
It will remove the given object in the first occurrence in the ArrayList.
8 RemoveAt
RemoveRan
It will remove the set of objects in the ArrayList from the range specified.
ge
1
Sort
0
1
Reverse
1
1 GetEnumera
2 tor
It will return the collection of objects in the ArrayList as an enumerator.
1
Contains
3
Description
Capcity
Count
IsFixedSize
IsReadOnly
Advantages
It can insert and delete the elements between positions in the ArrayList.
Disadvantages
ArrayList is not strongly typed. Type casting is necessary when retrieving the
content. When we do the type casting every time, it affects performance.
105
It uses the LinkedList storage approach, because if you insert or delete the
specific position then it must adjust forward/backward in the storage address.
ArrayList
Conclusion
So far we have seen the ArrayList and its members and properties. I hope that this has
provided enough of a practical idea about ArrayList. Next we will discuss the BitArray in
the same collection class. If you have any queries or further clarifications about ArrayList
then please free to post your feedback and corrections.
5. What are cursors and constraints ?
Cursors
A cursor is a database object that helps in accessing and manipulating data in a given
result set.The main advantage of cursors is that you can process data row-by-row.
A result set is defined as a collection of rows obtained from a SELECT statement that
meet the criteria specified in the WHERE clause.
Cursors, therefore, serve as a mechanism for applications to operate on a single row or a
set of rows. Cursors enable the processing of rows in the given result set in the following
ways:
1. Allow specific rows to be retrieved from the result set.
2. Allow the current row in the result set to be modified.
3. Help navigate from the current row in the result set to a different row.
4. Allow data modified by other users to be visible in the result set.
106
/* Create two variables that would store the values returned by the fetch statement */
DECLARE @DepartmentName char(25)
DECLARE @DepartmentHead char(25)
/* Define the cursor that can be used to access the records of the table,row by row */
DECLARE curDepartment cursor for
SELECT vDepartmentName,vDepartmentHead from Department
-- Open the cursor
OPEN curDepartment
-- Fetch the rows into variables
FETCH curDepartment into @DepartmentName,@DepartmentHead
--Start a loop to display all the rows of the cursor
WHILE(@@fetch_status=0)
BEGIN
Print 'Department Name =' + @DepartmentName
Print 'Department Head =' + @DepartmentHead
--Fetch the next row from the cursor
FETCH curDepartment into @DepartmentName,@DepartmentHead
END
-- Close the cursor
CLOSE curDepartment
-- Deallocate the cursor
DEALLOCATE curDepartment
The following are various types of cursors available in SQL Server 2005:
1. Base table
2. Static
3. Forward-only
4. Forward-only/Read-only
5. Keyset-driven
107
Base table: Base table cursors are the lowest level of cursor available. Base table
cursors can scroll forward or backward with minimal cost, and can be updated
Static: Cursors can move to any record but the changes on the data can't be seen.
Dynamic: Most resource-intensive. Cursors can move anywhere and all the changes on
the data can be viewed.
Forward-only: The cursor moves forward but can't move backward.
Keyset-driven: Only updated data can be viewed, deleted and inserted data cannot be
viewed.
Constraint
SQL Constraints
SQL constraints are used to specify rules for the data in a table.
If there is any violation between the constraint and the data action, the action is aborted
by the constraint.
Constraints can be specified when the table is created (inside the CREATE TABLE
statement) or after the table is created (inside the ALTER TABLE statement).
SQL CREATE TABLE + CONSTRAINT Syntax:
CREATE TABLE table_name
(
column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name,
column_name3 data_type(size) constraint_name,
....
);
In SQL, we have the following constraints:
UNIQUE: Ensures that each row for a column must have a unique value
PRIMARY KEY: A combination of a NOT NULL and UNIQUE. Ensures that a column
(or combination of two or more columns) have a unique identity that helps to find
a specific record in a table more easily and quickly
FOREIGN KEY: Ensures the referential integrity of the data in one table to match
values in another table
DEFAULT: Specifies a default value when none is specified for this column
6. What are the differences among foreign, primary, and unique keys
While unique and primary keys both enforce uniqueness on the column(s) of one table,
foreign keys define a relationship between two tables. A foreign key identifies a column
or group of columns in one (referencing) table that refers to a column or group of
columns in another (referenced) table; in our example above, the Employee table is the
referenced table and the Employee Salary table is the referencing table.
7. Difference Between SCOPE_IDENTITY() and @@IDENTITY
108
@@IDENTITY: Returns the last identity values that were generated in any table in the
current session. @@IDENTITY is not limited to a specific scope.
SCOPE_IDENTITY(): Returns the last identity values that are generated in any table in the
current session. SCOPE_IDENTITY returns values inserted only within the current scope.
8. Delegates and Events
The delegate topic seems to be confusing and tough for most developers. This article
explains the basics of delegates and event handling in C# in a simple manner.
A delegate is one of the base types in .NET. Delegate is a class to create delegates at
runtime.
A delegate in C# is similar to a function pointer in C or C++. It's a new type of object in
C#. A delegate is a very special type of object since earlier the entire the object was
used to defined contained data but a delegate just contains the details of a method.
The need for delegates
There might be a situation in which you want to pass methods around to other methods.
For this purpose we create delegates.
A delegate is a class that encapsulates a method signature. Although it can be used in
any context, it often serves as the basis for the event-handling model in C# but can be
used in a context removed from event handling (for example passing a method to a
method through a delegate parameter).
One good way of understanding delegates is by thinking of a delegate as something that
gives a name to a method signature.
Example
public delegate int DelegateMethod(int x, int y);
Any method that matches the delegate's signature, that consists of the return type and
parameters, can be assigned to the delegate. This makes is possible to programmatically
change method calls, and also plug new code into existing classes. As long as you know
the delegate's signature, you can assign your own-delegated method.
This ability to refer to a method as a parameter makes delegates ideal for defining
callback methods.
Delegate magic
In a class we create its object, that is an instance, but in a delegate when we create an
instance it is also referred to as a delegate (in other words whatever you do, you will get
a delegate).
A delegate does not know or care about the class of the object that it references. Any
object will do; all that matters is that the method's argument types and return type
match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
Benefit of delegates
In simple words delegates are object oriented and type-safe and very secure since
they ensure that the signature of the method being called is correct. Delegates help in
code optimization.
109
Types of delegates
1. Singlecast delegates
2. Multiplecast delegates
A delegate is a class. Any delegate is inherited from the base delegate class of the .NET
class library when it is declared. This can be from either of the
two classes System.Delegate or System.MulticastDelegate.
Singlecast delegate
a Singlecast delegate points to a single method at a time. In this the delegate is assigned
to a single method at a time. They are derived from the System.Delegate class.
Multicast Delegate
When a delegate is wrapped with more than one method then that is known as a
multicast delegate.
In C#, delegates are multicast, which means that they can point to more than one
function at a time. They are derived from the System.MulticastDelegate class.
There are three steps in defining and using delegates:
1. Declaration
To create a delegate, you use the delegate keyword.
[attributes] [modifiers] delegate ReturnType Name ([formal-parameters]);
The attributes factor can be a normal C# attribute.
The modifier can be one, or an appropriate combination, of the following keywords: new,
public, private, protected, or internal.
The ReturnType can be any of the data types we have used so far. It can also be a type
void or the name of a class.
"Name" must be a valid C# name.
Because a delegate is some type of a template for a method, you must use parentheses,
required for every method. If this method will not take any arguments then leave the
parentheses empty.
Example
public delegate void DelegateExample();
The code piece defines a delegate DelegateExample() that has a void return type and
accepts no parameters.
2. Instantiation
DelegateExample d1 = new DelegateExample(Display);
The preceding code piece shows how the delegate is initiated.
110
3. Invocation
d1();
The preceding code piece invokes the delegate d1().
The following is a sample to demonstrate a Singlecast delegate:
using System;
namespace ConsoleApplication5
{
class Program
{
public delegate void delmethod();
public class P
{
public static void display()
{
Console.WriteLine("Hello!");
}
public static void show()
{
Console.WriteLine("Hi!");
}
public void print()
{
Console.WriteLine("Print");
}
}
static void Main(string[] args)
{
// here we have assigned static method show() of class P to delegate delmethod()
delmethod del1 = P.show;
// here we have assigned static method display() of class P to delegate
delmethod() using new operator
// you can use both ways to assign the delagate
delmethod del2 = new delmethod(P.display);
P obj = new P();
// here first we have create instance of class P and assigned the method print() to
the delegate i.e. delegate with class
delmethod del3 = obj.print;
}
}
del1();
del2();
del3();
Console.ReadLine();
111
using System;
namespace delegate_Example4
{
class Program
{
public delegate void delmethod(int x, int y);
public class TestMultipleDelegate
{
public void plus_Method1(int x, int y)
{
Console.Write("You are in plus_Method");
Console.WriteLine(x + y);
}
public void subtract_Method2(int x, int y)
{
Console.Write("You are in subtract_Method");
Console.WriteLine(x - y);
}
}
static void Main(string[] args)
{
TestMultipleDelegate obj = new TestMultipleDelegate();
delmethod del = new delmethod(obj.plus_Method1);
// Here we have multicast
del += new delmethod(obj.subtract_Method2);
// plus_Method1 and subtract_Method2 are called
del(50, 10);
Console.WriteLine();
//Here again we have multicast
del -= new delmethod(obj.plus_Method1);
//Only subtract_Method2 is called
del(20, 10);
Console.ReadLine();
}
Delegates are similar to C++ function pointers, but are type safe.
Delegates can be chained together; for example, multiple methods can be called
on a single event.
C# version 2.0 introduces the concept of Anonymous Methods, that permit code
blocks to be passed as parameters in place of a separately defined method.
112
Delegates are also used for generic class libraries, that have generic functionality,
defined.
An Anonymous Delegate
You can create a delegate, but there is no need to declare the method associated with it.
You do not need to explicitly define a method prior to using the delegate. Such a method
is referred to as anonymous.
In other words, if a delegate itself contains its method definition then it is known as an
anonymous method.
The following is a sample to show an anonymous delegate:
using System;
public delegate void Test();
public class Program
{
static int Main()
{
Test Display = delegate()
{
Console.WriteLine("Anonymous Delegate method");
};
Display();
return 0;
}
113
It starts with a class that declares an event. Any class, including the same class
that the event is declared in, may register one of its methods for the event. This
occurs through a delegate, that specifies the signature of the method that is
registered for the event. The event keyword is a delegate modifier. It must
always be used in connection with a delegate.
The delegate may be one of the pre-defined .NET delegates or one you declare
yourself. Whichever is appropriate, you assign the delegate to the event, that
effectively registers the method that will be called when the event fires.
How to use events?
Once an event is declared, it must be associated with one or more event
handlers before it can be raised. An event handler is nothing but a method that is
called using a delegate. Use the += operator to associate an event with an
instance of a delegate that already exists.
The following is an example:
obj.MyEvent += new MyDelegate(obj.Display);
An event has the value null if it has no registered listeners.
Although events are most commonly used in Windows Controls programming,
they can also be implemented in console, web and other applications.
The following is a sample of creating a custom Singlecast delegate and event:
using System;
namespace delegate_custom
{
class Program
{
public delegate void MyDelegate(int a);
public class XX
{
public event MyDelegate MyEvent;
public void RaiseEvent()
{
MyEvent(20);
Console.WriteLine("Event Raised");
}
114
}
}
obj.RaiseEvent();
Console.ReadLine();
Events/Method
Page Initialization
Page_Init
LoadViewState
LoadPostData
Page Loading
Page_Load
RaisePostDataChangedEvent
RaisePostBackEvent
Page_PreRender
SaveViewState
Page_Render
Page Rendering
Page_UnLoad
Page Unloading
115
Some of the events listed above are not visible at the page level. It will be visible if you
happen to write server controls and write a class that is derived from page.
1. PreInit
The entry point of the page life cycle is the pre-initialization phase called "PreInit". This is
the only event where programmatic access to master pages and themes is allowed. You
can dynamically set the values of master pages and themes in this event. You can also
dynamically create controls in this event.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
116
{
// Raised by the Page object. Use this event for processing tasks that require all
initialization be complete.
}
4. PreLoad
Raised after the page loads the view state for itself and all controls and then processes
postback data included with the Request instance.
Loads ViewState: ViewState data are loaded to controls
Note: The page viewstate is managed by ASP.NET and persists information over a page
roundtrip to the server. Viewstate information is saved as a string of name/value pairs
and contains information such as control text or value. The viewstate is held in the value
property of a hidden control that is passed from page request to page request.
Loads Postback data: postback data are now handed to the page controls.
Note: During this phase of the page creation, form data that was posted to
the server (termed postback data in ASP.NET) is processed against each control that
requires it. Hence, the page fires the LoadPostData event and parses through the page to
find each control and updates the control state with the correct postback data. ASP.NET
updates the correct control by matching the control's unique ID with the name/value pair
in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each
control on any given page.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected override void OnPreLoad(EventArgs e)
{
// Use this event if you need to perform processing on your page or control before
the Load event.
// Before the Page instance raises this event, it loads view state for itself and all
controls, and
// then processes any postback data included with the Request instance.
}
5. Load
The important thing to note about this event is the fact that by now, the page has been
restored to its previous state in case of postbacks. Code inside the page load event
typically checks for PostBack and then sets control properties appropriately. This method
is typically used for most code, since this is the first place in the page lifecycle that all
values are restored. Most code checks the value of IsPostBack to avoid unnecessarily
resetting state. You may also wish to call Validate and check the value of IsValid in this
method. You can also create dynamic controls in this method.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected void Page_Load(object sender, EventArgs e)
{
// The Page calls the OnLoad event method on the Page, then recursively does the
same for each child
// control, which does the same for each of its child controls until the page and all
controls are loaded.
// Use the OnLoad event method to set properties in controls and establish database
117
connections.
}
6. Control (PostBack) event(s)
ASP.NET now calls any events on the page or its controls that caused the PostBack to
occur. This might be a button's click event or a dropdown's selectedindexchange event,
for example.
These are the events, the code for which is written in your code-behind class (.cs file).
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected void Button1_Click(object sender, EventArgs e)
{
// This is just an example of control event.. Here it is button click event that caused
the postback
}
7. LoadComplete
This event signals the end of Load.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected void Page_LoadComplete(object sender, EventArgs e)
{
// Use this event for tasks that require that all other controls on the page be loaded.
}
8. PreRender
Allows final changes to the page or its control. This event takes place after all regular
PostBack events have taken place. This event occurs before saving ViewState, so any
changes made here are saved.
For example: After this event, you cannot change any property of a button or change any
viewstate value. Because, after this event, the SaveStateComplete and Render events
are called.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected override void OnPreRender(EventArgs e)
{
// Each data bound control whose DataSourceID property is set calls its DataBind
method.
// The PreRender event occurs for each control on the page. Use the event to make
final
// changes to the contents of the page or its controls.
}
9. SaveStateComplete
Prior to this event the view state for the page and its controls is set. Any changes to the
page's controls at this point or beyond are ignored.
118
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected override void OnSaveStateComplete(EventArgs e)
{
// Before this event occurs, ViewState has been saved for the page and for all
controls.
// Any changes to the page or controls at this point will be ignored.
// Use this event perform tasks that require view state to be saved, but that do not
make any changes to controls.
}
10. Render
This is a method of the page object and its controls (and not an event). At this point,
ASP.NET calls this method on each of the page's controls to get its output. The Render
method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML),
and script that are necessary to properly display a control at the browser.
Note: Right-click on the web page displayed in the client's browser and view the page's
source. You will not find any aspx server control in the code. Because all aspx controls are
converted to their respective HTML representation. The browser is capable of displaying
HTML and client-side scripts.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
// Render stage goes here. This is not an event
11. UnLoad
This event is used for cleanup code. After the page's HTML is rendered, the objects are
disposed of. During this event, you should destroy any objects or references you have
created in building the page. At this point, all processing has occurred and it is safe to
dispose of any remaining objects, including the Page object.
Cleanup can be performed on:
(a)Instances of classes in other words objects
(b)Closing opened files
(c)Closing database connections.
Example: Override the event as given below in your code-behind cs file of your aspx
page.
protected void Page_UnLoad(object sender, EventArgs e)
{
// This event occurs for each control and then for the page. In controls, use this
event to do final cleanup
// for specific controls, such as closing control-specific database connections.
// During the unload stage, the page and its controls have been rendered, so you
cannot make further
// changes to the response stream.
//If you attempt to call a method such as the Response.Write method, the page will
throw an exception.
}
}
10. Request and response in IIS
119
When the client requests some information from a web server, the request first reaches
to HTTP.SYS of IIS. HTTP.SYS then sends the request to the respective Application Pool.
The Application Pool then forwards the request to the worker process to load the ISAPI
Extension that will create an HTTPRuntime Object to process the request via HTTPModule
and HTTPHanlder. After that the ASP.NET Page LifeCycle events start.
11. What are ADO.net objects ?
ADO.NET is designed to help developers work efficiently with multi tier databases, across
intranet or internet scenarios.
The ADO.NET object model consists of two key components as follows:
Connection
The Connection object is the first component of ADO.NET. The connection object opens a
connection to your data source.
All of the configurable aspects of a database connection are represented in the
Connection object, that includes ConnectionString and ConnectionTimeout.
Connection object helps in accessing and manipulating a database. Database
transactions are also dependent upon the Connection object.
In ADO.NET the type of the Connection is dependent on what database system you are
working with. The following are the most commonly used for connections in ADO.NET:
SqlConnection
OleDbConnection
OdbcConnection
Command
The Command object is used to perform an action on the data source. The Command
object can execute Stored Procedures and T-SQL commands.
You can execute SQL queries to return data in a DataSet or a DataReader object. The
Command object performs the standard Select, Insert, Delete and Update T-SQL
operations.
DataReader
The DataReader is built as a way to retrieve and examine the rows returned in response
to your query as quickly as possible.
No DataSet is created; in fact, no more than one row of information from the data source
is in-memory at a time. This makes the DataReader very efficient at returning large
amounts of data.
120
The data returned by a DataReader is always read only. This class was built to be a
lightweight forward only, read only, way to run through data quickly (this was called a
Firehose cursor in ADO).
However, if you need to manipulate a schema or use some advanced display features
such as automatic paging then you must use a DataAdapter and DataSet.
A DataReader object works in the connected model.
DataAdapter
The DataAdapter takes the results of a database query from a Command object and
pushes them into a DataSet using the DataAdapter.Fill() method. Additionally the
DataAdapter.Update() method will negotiate any changes to a DataSet back to the
original data source.
A DataAdapter object works in a connected model. A DataAdapter performs the following
five steps:
1. Create/open the connection
2. Fetch the data as per command specified
3. Generate XML file of data
4. Fill data into DataSet.
5. Close connection.
Command Builder
It is used to save changes made in an in-memory cache of data on the backend. The
work of Command Builder is to generate a Command as per changes in DataRows.
Command Builder generates commands on the basis of row state. There are five row
states:
1. Unchanged
2. Added
3. Deleted
4. Modified
5. Detached
Command Builder works on add, delete and modified row state only.
Detached is used when an object is not created from row state.
Transaction
The Transaction object is used to execute a backend transaction. Transactions are used to
ensure that multiple changes to database rows occur as a single unit of work.
The Connection class has a BeginTransaction method that can be used to create a
121
Transaction.
A definite best practice is to ensure that transactions are placed in Using statements for
rapid cleanup if they are not committed. Otherwise the objects (and any internal locks
that may be needed) will remain active until the GC gets around to cleaning it up.
Parameters
A Parameter object is used to solve SQL Injection attack problems while dealing with the
user input parameters.
A Parameter object allows passing parameters into a Command object. The Parameter
class allows you to quickly put parameters into a query without string concatenation.
Note: See my other article on ADO.NET Objects Part II.
Conclusion
Hope the article has helped you to understand ADO.NET objects.
Your feedback and constructive contributions are welcome. Please feel free to contact
me for feedback or comments you may have about this article. ADO.NET is designed to
help developers work efficiently with multi-tier databases, across intranet or Internet
scenarios.
The ADO.NET object model consists of two key components as follows:
DataSet
The DataSet Object is the parent object to most of the other objects in the System.Data
namespace. The DataSet is a disconnected, in-memory representation of data.
Its primary role is to store a collection of DataTables and the relations and constraints
between those DataTables.
DataSet also contains several methods for reading and writing XML, as well as merging
other DataSets, DataTables and DataRows.
Some of the advantages of the new DataSet object are:
Read / Write
Connectionless
122
DataTable
DataTable stores a table of information, typically retrieved from a data source. DataTable
allows you to examine the actual rows of a DataSet through rows and columns
collections.
Once the DataTable is filled the database connection is released and operates
disconnected only.
You can complex-bind a control to the information contained in a data table. Controls like
DataGrid are used for this purpose.
DataTable also stores metatable information such as the primary key and constraints.
DataRows
The DataRow class permits you to reference a specific row of data in a DataTable. This is
the class that permits you to edit, accept, or reject changes to the individual
DataColumns of the row.
You would use a DataRow object and its properties and methods to retrieve and evaluate
the values in a DataTable object.
The DataRowCollection represents the actual DataRow objects that are in the DataTable
object, and the DataColumnCollection contains the DataColumn objects that describe the
schema of the DataTable object.
DataColumns
DataColumns is the building block of the DataTable. A number of such objects make up a
table. Each DataColumn object has a DataType property that determines the kind of data
that the column is holding. data table.
DataColumn instances are also the class of object that you use to read and write
individual columns of a database. The Items property of a DataRow returns a
DataColumn.
DataView
A DataView is an object that provides a custom view of data in a DataTable. DataViews
provide sorting, filtering, and other types of customizations.
Each DataTable object has a DefaultView property, that holds the default DataView object
for that DataTable. Modifying the DefaultView object sets the default display
characteristics for the DataTable.
You can create an instance of a DataView and associate it with a specific DataTable in a
DataSet. This permits you to have two or more different views of the same DataTable
simultaneously available.
DataRelation
A DataRelation identifies that two or more of the DataTables in a DataSet contain data
related in a one-to-one or one-to-many (parent-child) association. You define a
relationship between two tables by adding a new DataRelation object to the DataSets.
Constraints
Each DataColumn may have multiple Constraints. Conditions such as unique are applied
123
through this class. Constraint objects are maintained through the DataTables Constraints
collection.
DataRowView
A DataRowView is a special object that represents a row in a DataView. Each DataView
can have a different RowStateFilter, the DataRowView obtained from a DataView will
contain data consistent with the DataView's RowStateFilter, providing a custom view of
the data.
12. What is the difference between Stored Procedures and functions?
1. Procedures can have input/output parameters for it whereas functions can have only
input parameters. 2. Procedure allows select as well as DML statement in it whereas a
function only allows select statements in it. 3. We can go for transaction management in
procedures whereas we can't for functions. 4. Procedures cannot be utilized in a select
statement whereas functions can be embedded in a select statement.
13. What is the difference between Stored Procedures and triggers?
Stored Procedures normally used to performing user specified tasks. It can have the
parameters. It can return multiple results set.
Triggers normally are used for auditing work. It can be used to trace the activities of the
table events.
Procedures can have the input and output parameters with all the data types available in
the SQL Server as well as user defined data types.
The Stored Procedures can be run independently. They are stored as a database object. It
can be called from the application.
The DML triggers are get executed based on the table events defined on the specific
table. There are various types of triggers, like DML triggers, DDL triggers (from 2005
onwards) and logon triggers (from 2008 onwards).
The DDL triggers can control the Stored Procedures creation, drop and so on.
124
The Stored Procedures cannot call the triggers directly. But when we do the DML
operations on the table, if the corresponding table has the trigger then it will then be
triggered.
Holds the connection open until you are finished (don't forget to close it!).
DataSet
DataSet is a disconnected oriented architecture. That means that there is no need for
active connections to work with DataSets and it is a collection of DataTables and relations
between tables. It holds multiple tables with data. You can select data form tables, create
views based on tables and ask child rows over relations. Also DataSet provides you with
rich features like saving data as XML and loading XML data.
protected void BindGridview()
{
SqlConnection conn = new SqlConnection("Data Source=abc;Integrated
Security=true;Initial Catalog=Test");
conn.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First
Name,LastName,Location FROM Users", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
125
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
DataAdapter
A DataAdapter will act as a bridge between a DataSet and the database. This
DataAdapter object reads the data from the database and binds that data to a DataSet.
DataAdapter is a disconnected oriented architecture. Check the following sample code to
see how to use a DataAdapter in code:
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=abc;Integrated
Security=true;Initial Catalog=Test");
conn.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First
Name,LastName,Location FROM Users", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
Lets you close the connection as soon it's done loading data, and may even close
it for you automatically
You can iterate over it as many times as you need, or even look up a specific
record by index
DataTable
DataTable represents a single table in the database. It has rows and columns. There is
not much difference between DataSet and datatable, a DataSet is simply a collection of
datatables.
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=abc;Integrated
Security=true;Initial Catalog=Test");
conn.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First
Name,LastName,Location FROM Users", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
gridview1.DataSource = dt;
gvidview1.DataBind();
}
15. Differnce between JavaScript jQuery and AJAX?
126
JavaScript
1. JavaScript is a client-side (in the browser) scripting language.
2. JavaScript lets you supercharge your HTML with animation, interactivity, and
dynamic visual effects
3. JavaScript can make web pages more useful by supplying immediate feedback.
4. JavaScript is the common term for a combination of the ECMAScript programming
language plus some means for accessing a web browser's windows and the
document object model (DOM).
5. JavaScript was designed to add interactivity to HTML pages
6. Everyone can use JavaScript without purchasing a license
jQuery
1. jQuery is a library/framework built with JavaScript.
2. It abstracts away cross-browser compatibility issues and it emphasises
unobtrusive and callback-driven JavaScript programming
3. jQuery (website) is a JavaScript framework that makes working with the DOM
easier by building many high level functionality that can be used to search and
interact with the DOM
4. jQuery implements a high-level interface to do AJAX requests
5. jQuery is a fast and concise JavaScript Library that simplifies HTML document
traversing, event handling, animating, and AJAX interactions for rapid web
development
Asynchronous JavaScript XML (AJAX)
1. Asynchronous JavaScript XML (AJAX) is a method to dynamically update parts of
the UI without having to reload the page, to make the experience more similar to
a Desktop application.
2. AJAX is a technique to do an XMLHttpRequest (out of band Http request) from a
web page to the server and send/retrieve data to be used on the web page
3. It uses JavaScript to construct an XMLHttpRequest, typically using various
techniques on various browsers.
4. AJAX is a set of functions of the language JavaScript
5. Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook
tabs.
Why AJAX?
This is probably one of the most asked questions about AJAX.
127
The main advantage of using AJAX enabled ASP.NET Web applications is improved
efficiency and a reduction of the page refresh time. AJAX enables us to refresh only parts
of a Web page that have been updated, rather refreshing the entire page.
For example, if you have four controls on a web page, say a DropDownList, a TextBox, a
ListBox, and a GridView. The GridView control shows some data based on the selection in
a DropDownList and other controls. Now let's say a GridView also has paging and sorting
options. So whenever you move to the next page or apply a sort, the entire page and all
four controls on the page will be refreshed and you will notice a page flicker because
ASP.NET must render the entire page on the client-side and it happens once.
In an AJAX-enabled web page, you will see only the GridView data is being refreshed and
rest of the page and controls do not. Doing so, we not only get better performance and
faster refresh, we also get a better (or should I say "smoother") user experience.
You may want to see a live example of an AJAX enabled GridView on
our www.mindcracker.com web site in the Jobs section
here: http://www.mindcracker.com/Jobs/ . On this page, if you click on the "Next" page
link then you will see only the GridView data is being refreshed. We are also
implementing AJAX on C# Corner and other sites as well.
What Browsers Does AJAX Support?
AJAX is JavaScript based and supports most of the browsers including Internet
Explorer, Mozilla Firefox, and Apple Safari.
What are ASP.NET AJAX Extensions?
ASP.NET AJAX is a combination of client-script libraries (JavaScript) and ASP.NET server
components that are integrated to provide a robust development framework.
What are ASP.NET AJAX Server Controls?
The ASP.NET AJAX server controls consist of server and client code that integrate to
produce AJAX-like behavior. The following controls are available in the AJAX 1.0 library:
1. ScriptManager: Manages script resources for client components, partial-page
rendering, localization, globalization, and custom user scripts. The ScriptManager
control is required for the use of the UpdatePanel, UpdateProgress, and Timer
controls.
2. UpdatePanel: Enables you to refresh selected parts of the page instead of
refreshing the entire page by using a synchronous postback.
3. UpdateProgress: Provides status information about partial-page updates in
UpdatePanel controls.
4. Timer: Performs postbacks at defined intervals. You can use the Timer control to
post the entire page, or use it together with the UpdatePanel control to perform
partial-page updates at a defined interval.
What is the ASP.NET AJAX Control Toolkit?
The ASP.NET AJAX Control Toolkit is a collection of samples and components that show
you some of the experiences you can create with rich client ASP.NET AJAX controls and
extenders. The Control Toolkit provides both samples and a powerful SDK to simplify
creation and reuse of your custom controls and extenders. You can download the ASP.NET
AJAX Control Toolkit from the ASP.NET AJAX Web site.
128
A chat service that allows two people to communicate or exchange data in real
time.
A dashboard application that polls one or more services for data and presents it in
a logical presentation.
Features of WCF
Service Orientation
Interoperability
Service Metadata
Data Contracts
Security
129
Durable Messages
Transactions
Extensibility
Only Public fields or Properties of .NET types can be translated into XML
Classes that implement the IDictionary interface, such as Hash table cannot be
serialized
XML Serialization does not indicate which fields or properties of the type are
serialized into XML whereasDataCotractSerializer
130
Explicitly shows the which fields or properties are serialized into XML
Only Public fields or Properties of .NET types can be translated into XML
Classes that implement the IDictionary interface, such as Hash table cannot be
serialized
XML Serialization does not indicate which fields or properties of the type are
serialized into XML whereas DataContractSerializer explicitly shows which fields or
properties are serialized into XML.
Developing Service
To develop a service using ASP.NET, we must add the WebService attribute to the class
and WebMethodAttribute to any of the class methods.
Example
[WebService]
131
Copy the service file with an extension .SVC into a virtual directory and assembly
into bin sub directory of the virtual directory.
Client Development
Clients for the ASP.NET Web services are generated using the command-line
tool WSDL.EXE.
WCF uses the ServiceMetadata tool (svcutil.exe) to generate the client for the service.
Message Representation
The Header of the SOAP Message can be customized in ASP.NET Web service.
132
WCF provides
attributes MessageContractAttribute, MessageHeaderAttribute andMessageBodyMember
Attribute to describe the structure of the SOAP Message.
Service Description
Issuing a HTTP GET Request with query WSDL causes ASP.NET to generate WSDL to
describe the service. It returns the WSDL as a response to the request.
The generated WSDL can be customized by deriving the class
of ServiceDescriptionFormatExtension.
Issuing a Request with the query WSDL for the .svc file generates the WSDL. The WSDL
that generated by WCF can be customized by using ServiceMetadataBehavior class.
Exception Handling
In ASP.NET Web services, unhandled exceptions are returned to the client as SOAP faults.
In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A
configuration setting is provided to have the unhandled exceptions returned to clients for
the purpose of debugging.
16. SOAP, WSDL, UDDI overview.
XML: Describes only data. So, any application that understands XML, regardless of the
application's programming language or platform, has the ability to format XML in a
variety of ways (well-formed or valid).
SOAP: Provides a communication mechanism between services and applications.
WSDL: Offers a uniform method of describing web services to other programs.
UDDI: Enables the creation of searchable Web services registries
133
ASP.NET MVC is a web development framework from Microsoft that is based on the
Model-View-Controller (MVC) architectural design pattern. Microsoft has streamlined the
development of MVC based applications using the ASP.NET MVC Framework.
3. What are the differences between ASP.NET MVC and ASP.NET WebForms?
ASP.NET Web Forms use the Page Controller Pattern for rendering layout, whereas
ASP.NET MVC uses the Front Controller approach. In the case of the Page Controller
Pattern, every page has its own Controller, in other words a code-behind file that
processes the request. On the other hand, in ASP.NET MVC, a common Controller for all
pages processes the requests.
Follow the link for the difference between the ASP.NET MVC and ASP.NET WebForms.
4. What are the Core features of ASP.NET MVC?
The core features of the ASP.NET MVC Framework are:
134
the redirect occurs. So, in short, it's a mechanism to maintain state between Controller
and corresponding View.
ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0
feature). Since viewData is a dictionary object it is accessible using strings as keys and
also requires typecasting for complex types. On the other hand, ViewBag doesn't have
typecasting and null checks.
TempData is also a dictionary object that persists for the life of a HTTP Request. So,
Tempdata can be used to maintain data between redirects, in other words from one
Controller to another Controller.
8. What are Action Methods in ASP.NET MVC?
As previously stated about request flows in the ASP.NET MVC Framework, a request
coming from a client hits the Controller first. Actually the MVC application determines the
corresponding Controller using routing rules defined in Global.asax. And Controllers have
specific methods for each user actions. Each request coming to the Controller is for a
specific Action Method. The following code example, "ShowBooks" is an example of an
Action Method.
public ViewResult ShowBooks(int id)
{
var computerBook = db.Books.Where(p => P.BookID == id).First();
return View(computerBook);
}
9. Explain the role of Model in ASP.NET MVC?
One of the core features of ASP.NET MVC is that it separates the input and UI logic from
business logic. The role of the Model in ASP.NET MVC is to contain all application logic
including validation, business and data access logic except View. In other words input and
Controller; in other words UI logic.
The Model is normally responsible for accessing data from some persistent medium such
as a database and manipulates it.
10. What are Action Filters in ASP.NET MVC?
If we need to apply some specific logic before or after action methods then we use action
filters. We can apply these action filters to a Controller or a specific Controller action.
Action filters are basically custom classes that provide a way for adding pre-action or
post-action behavior to Controller actions.
For example:
An OutputCache filter can cache the output of a Controller action for a specific
duration.
135
interviews/tests/exams.
The sole purpose of this article is to sum up important questions and answers that can be
used by developers to brush-up on MVC before they go to an interview including it.
What is MVC?
MVC is a framework pattern that splits an application's implementation logic into three
component roles: models, views, and controllers.
Model: The business entity on which the overall application operates. Many
applications use a persistent storage mechanism (such as a database) to store
data. MVC does not specifically mention the data access layer because it is
understood to be encapsulated by the Model.
View: The user interface that renders the Model into a form of interaction.
Controller: Handles a request from a View and updates the Model that results in
a change of the Model's state.
To implement MVC in .NET we need mainly three classes (View, Controller and the
Model).
Explain MVC Architecture?
The architecture is self-explanatory. The browser (as usual) sends a request to IIS, IIS
searches for the route defined in the MVC application and passes the request to the
controller as specified by the route, the controller communicates with the model and
passes the populated model (entity) to View (front end), Views are populated with model
properties, and are rendered on the browser, passing the response to the browser
through IIS via controllers that invoked the specified View.
What are the new features of MVC 2?
ASP.NET MVC 2 was released in March 2010. Its main features are:
136
There were also many API enhancements and "pro" features, based on feedback
from developers building a variety of applications on ASP.NET MVC 1, such as:
Greater control and flexibility with support for dependency resolution and global
action filters.
Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON
binding.
Display Modes.
137
2. Routing
3. Instantiate and execute controller
4. Locate and invoke controller action
5. Instantiate and render view
Advantages of MVC Framework
1. Provides a clean separation of concerns among UI (Presentation layer), model
(Transfer objects/Domain Objects/Entities) and Business Logic (Controller).
2. Easy to UNIT Test.
3. Improved reusability of views/model. One can have multiple views that can point
to the same model and vice versa.
4. Improved structuring of the code.
What is meant by Separation of Concerns?
As per Wikipedia 'the process of breaking a computer program into distinct features that
overlap in functionality as little as possible'. The MVC design pattern aims to separate
content from presentation and data-processing from content.
Where do we see Separation of Concerns in MVC?
Between the data-processing (Model) and the rest of the application.
When we talk about Views and Controllers, their ownership itself explains separate. The
views are just the presentation form of an application, it does not need to know
specifically about the requests coming from the controller. The Model is independent of
View and Controllers, it only holds business entities that can be passed to any View by
the controller as required for exposing them to the end user. The controller is
independent of Views and Models, its sole purpose is to handle requests and pass it on as
per the routes defined and as per the need of rendering the views. Thus our business
entities (model), business logic (controllers) and presentation logic (views) lie in
logical/physical layers independent of each other.
What is Razor View Engine?
Razor is the first major update to render HTML in MVC 3. Razor was designed specifically
as a view engine syntax. It has one main focus: code-focused templating for HTML
generation. Here's how that same markup would be generated using Razor:
@model MvcMusicStore.Models.Genre
@{ViewBag.Title = "Browse Albums";}
<div class="genre">
<h3><em>@Model.Name</em> Albums</h3>
<ul id="album-list">
@foreach (var album in Model.Albums)
{
<li>
<a href="@Url.Action("Details", new { id = album.AlbumId })">
<img alt="@album.Title" src="@album.AlbumArtUrl" />
<span>@album.Title</span>
</a>
138
</li>
}
</ul>
</div>
The Razor syntax is easier to type, and easier to read. Razor doesn't have the XML-like
heavy syntax of the Web Forms view engine.
What is Unobtrusive JavaScript?
Unobtrusive JavaScript is a general term that conveys a general philosophy, similar to the
term REST (Representational State Transfer). The high-level description is that
unobtrusive JavaScript doesn't intermix JavaScript code in your page markup. For
example, rather than hooking in via event attributes like onclick and onsubmit, the
unobtrusive JavaScript attaches to elements by their ID or class, often based on the
presence of other attributes (such as HTML5 data-attributes).
It's got semantic meaning and all of it; the tag structure, element attributes and so on
should have a precise meaning. Strewing JavaScript gunk across the page to facilitate
interaction (I'm looking at you, -doPostBack!) harms the content of the document.
What is JSON Binding?
MVC 3 included JavaScript Object Notation (JSON) binding support via the new
JsonValueProviderFactory, enabling the action methods to accept and model-bind data in
JSON format. This is especially useful in advanced Ajax scenarios like client templates
and data binding that need to post data back to the server.
What is Dependency Resolution?
MVC 3 introduced a new concept called a dependency resolver, that greatly simplified
the use of dependency injection in your applications. This made it easier to decouple
application components, making them more configurable and easier to test.
Support was added for the following scenarios:
Views (registering and injecting view engines, injecting dependencies into view
pages)
139
view titled "Index.Mobile.cshtml" then MVC 4 will automatically use the mobile view when
viewed in a mobile browser.
Additionally, we can register your own custom device modes that will be based on your
own custom criteria, all in just one code statement. For example, to register a WinPhone
device mode that would serve views ending with ".WinPhone.cshtml" to Windows Phone
devices, you'd use the following code in the Application_Start method of your
Global.asax:
DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("WinPhone")
{
ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf
("Windows Phone OS", StringComparison.OrdinalIgnoreCase) >= 0)
});
What is AuthConfig.cs in MVC 4?
"AuthConfig.cs" configures security settings, including sites for OAuth login.
What is BundleConfig.cs in MVC 4?
"BundleConfig.cs" in MVC4 registers bundles used by the bundling and minification
system. Several bundles are added by default, including jQuery, jQueryUI, jQuery
validation, Modernizr, and default CSS references.
What is FilterConfig.cs in MVC 4?
This is used to register global MVC filters. The only filter registered by default is the
HandleErrorAttribute, but this is a great place to put other filter registrations.
What is RouteConfig.cs in MVC 4?
"RouteConfig.cs" holds the granddaddy of the MVC config statements and Route
configuration.
What is WebApiConfig.cs in MVC 4?
Used to register Web API routes, as well as set any additional Web API configuration
settings.
What's new for adding a controller in a MVC 4 application?
Previously (in MVC 3 and MVC 2), the Visual Studio Add Controller menu item only
displayed when we right-clicked on the Controllers folder. However, the use of the
Controllers folder was purely for organization. (MVC will recognize any class that
implements the IController interface as a Controller, regardless of its location in your
application.) The MVC 4 Visual Studio tooling has been modified to display the Add
Controller menu item for any folder in your MVC project. This allows us to organize
controllers however you would like, perhaps separating them into logical groups or
separating MVC and Web API controllers.
What are the software requirements of an ASP.NET MVC 4 application?
MVC 4 runs on the following Windows client operating systems:
Windows XP
Windows Vista
140
Windows 7
Windows 8
MVC 4 development tooling is included with Visual Studio 2012 and can be installed on
Visual Studio 2010 SP1/Visual Web Developer 2010 Express SP1.
What are the various types of Application Templates used to create an MVC application?
The various templates are as follows:
1. The Internet Application template: This contains the beginnings of an MVC
web application, enough that you can run the application immediately after
creating it
and see a few pages. This template also includes some basic account
management functions that run against the ASP.NET Membership.
3. The Basic template: This template is pretty minimal. It still has the basic
folders, CSS, and MVC application infrastructure in place, but no more. Running an
application created using the Empty template just gives you an error message.
Why use Basic template? The Basic template is intended for experienced MVC
developers who want to set up and configure things exactly how they want them.
4. The Empty template: The Basic Template was previously called the Empty
Template, but developers complained that it wasn't quite empty enough. With
MVC 4, the previous Empty
Template was renamed Basic, and the new Empty Template is about as empty as
possible.
It has the assemblies and basic folder structure in place, but that's about it.
141
6. The Web API template: The ASP.NET Web API is a framework for creating HTTP
services.
The Web API template is similar to the Internet Application template but is
streamlined for Web API development. For instance, there is no user account
management functionality, since Web API account management is often
significantly different from standard MVC account management. Web API
functionality is also available in the other MVC project templates, and even in nonMVC project types.
What are the default Top-level directories created when adding a MVC 4
application?
The default Top-level directories are:
/Models: For classes that represent and manipulate data and business objects
/Views: For UI template files that are responsible for rendering output like HTML
/Content: For CSS and other site content, other than scripts and images
/App_Start: For configuration code of features like Routing, Bundling, Web API.
142
Their value becomes null when any redirection occurs, because their role is to
provide a way to communicate between controllers and views. It's a
communication mechanism within the server call.
What are the differences between ViewData and ViewBag (taken from a blog)?
ViewBag is a dynamic property that takes advantage of the new dynamic features
in C# 4.0.
ViewData requires typecasting for complex data types and checks for null values
to avoid error.
NOTE: Although there might not be a technical advantage to choosing one format over
the other, there are some critical differences to be aware of between the two syntaxes.
One obvious difference is that ViewBag works only when the key being accessed is a
valid C# identifier. For example, if you place a value in ViewData["KeyWith Spaces"] then
you can't access that value using ViewBag because the code won't compile.
Another key issue to be aware of is that dynamic values cannot be passed in as
parameters to extension methods. The C# compiler must know the real type of every
parameter at compile time in order for it to choose the correct extension method.
If any parameter is dynamic then compilation will fail. For example, this code will always
fail: @Html.TextBox("name", ViewBag.Name). To work around this, either use
ViewData["Name"] or cast the value to a specifi c type: (string) ViewBag.Name.
What is TempData?
TempData is a dictionary derived from the TempDataDictionary class and stored in a
short-lived session. It is a string key and object value.
It maintains the information for the duration of an HTTP Request. This means only from
one page to another. It helps to maintain data when we move from one controller to
143
another controller or from one action to another action. In other words, when we redirect
Tempdata, it helps to maintain the data between those redirects. It internally uses
session variables. Temp data used during the current and subsequent request only
means it is used when we are sure that the next request will be redirecting to the next
view. It requires typecasting for complex data types and checks for null values to avoid
errors. Generally it is used to store only one-time messages, like error messages and
validation messages.
How can you define a dynamic property using viewbag in ASP.NET MVC?
Assign a key name with the syntax "ViewBag.[Key]=[ Value]" and value using the equal
to operator.
For example, you need to assign a list of students to the dynamic Students property of
ViewBag as in the following:
List<string> students = new List<string>();
countries.Add("Akhil");
countries.Add("Ekta");
ViewBag.Students = students;
//Students is a dynamic property associated with ViewBag.
Note: Some of the content has been taken from various books/articles.
What is ViewModel (taken from stackoverflow)?
Accepted A view model represents data that you want to have displayed on your
view/page.
Let's say that you have an Employee class that represents your employee domain model
and it contains the following 4 properties:
public class Employee : IEntity
{
public int Id { get; set; } // Employee's unique identifier
public string FirstName { get; set; } // Employee's first name
public string LastName { get; set; } // Employee's last name
public DateTime DateCreated { get; set; } // Date when employee was created
}
View models differ from domain models in that view models only contain the data
(represented by properties) that you want to use on your view. For example, let's say that
you want to add a new employee record, your view model might look like this:
public class CreateEmployeeViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
As you can see it only contains 2 of the properties of the employee domain model. Why is
this you may ask? Id might not be set from the view and it might be auto-generated by
the Employee table. And DateCreated might also be set in the Stored Procedure or in the
service layer of your application. So Id and DateCreated is not needed in the view model.
When loading the view/page, the create action method in your employee controller will
create an instance of this view model, populate any fields if required, and then pass this
view model to the view:
144
145
model with 30 properties and you only want to update a single value. Given this scenario
you would only have this one value/property in the view model and not the entire domain
object.
How do you check for AJAX requests with C# in MVC.NET?
The solution is independed of the MVC.NET framework and is global across server side
technologies. Most modern AJAX applications utilize XmlHTTPRequest to send async
requests to the server. Such requests will have a distinct request header:
X-Requested-With = XMLHTTPREQUEST
MVC.NET provides helper functions to check for ajax requests that internally inspects the
"X-Requested-With" request header to set the "IsAjax" flag.
What are Scaffold templates?
These templates use the Visual Studio T4 templating system to generate a view based on
the model type selected. Scaffolding in ASP.NET MVC can generate the boilerplate code
we need to create, read, update, and delete (CRUD) functionality in an application. The
scaffolding templates can examine the type definition for it then generate a controller
and the controller's associated views. The scaffolding knows how to name controllers,
how to name views, what code needs to go to each component, and where to place all
these pieces in the project for the application to work.
What are the types of Scaffolding Templates?
Empty: Creates an empty view. Only the model type is specified using the model
syntax.
Create: Creates a view with a form for creating new instances of the model.
Generates a label and input field for each property of the model type.
Delete: Creates a view with a form for deleting existing instances of the model.
Displays a label and the current value for each property of the model.
Details: Creates a view that displays a label and the value for each property of
the model type.
Edit: Creates a view with a form for editing existing instances of the model.
Generates a label and input field for each property of the model type.
146
List: Creates a view with a table of model instances. Generates a column for
each property of the model type. Make sure to pass an
IEnumerable<YourModelType> to this view from your action method.
The view also contains links to actions for performing the create/edit/delete operations.
Show an example of the difference in syntax in Razor and WebForm Views
Razor <span>@model.Message</span>
Web Forms <span><%: model.Message %></span>
Code expressions in Razor are always HTML encoded. This Web Forms syntax also
automatically HTML encodes the value.
What are Code Blocks in Views?
Unlike code expressions that are evaluated and sent to the response, blocks of code are
simply sections of code that are executed. They are useful for declaring variables that we
may need to use later.
Razor
@{
int x = 123;
string y = because.;
}
Web Forms
<%
int x = 123;
string y = "because.";
%>
What is the "HelperPage.IsAjax" Property?
The HelperPage.IsAjax property gets a value that indicates whether Ajax is being used
during the request of the Web page.
Namespace: System.Web.WebPages
Assembly: System.Web.WebPages.dll
However, the same can be done by checking request headers directly:
Request["X-Requested-With"] == "XmlHttpRequest".
Explain combining text and markup in Views using an example
This example shows what intermixing text and markup looks like using Razor as
compared to Web Forms:
Razor
@foreach (var item in items) {
<span>Item @item.Name.</span>
}
Web Forms
147
It provides a flexible architecture that can be adapted as the overall design of the
application evolves.
In a Repository we write our entire business logic of CRUD operations using Entity
Framework classes that will not only result in meaningful test driven code but will also
reduce our controller code of accessing data.
How can you call a JavaScript function/method on the change of a Dropdown
List in MVC?
Create a JavaScript method:
<script type="text/javascript">
function selectedIndexChanged() {
}
</script>
Invoke the method:
<%:Html.DropDownListFor(x => x.SelectedProduct,
new SelectList(Model.Users, "Value", "Text"),
"Please Select a User", new { id = "ddlUsers",
onchange="selectedIndexChanged()" })%>
Explain Routing in MVC
A route is a URL pattern that is mapped to a handler. The handler can be a physical file,
such as an .aspx file in a Web Forms application. A Routing module is responsible for
mapping incoming browser requests to specific MVC controller actions.
Routing within the ASP.NET MVC framework serves the following two main purposes:
It matches incoming requests that would not otherwise match a file on the file
system and maps the requests to a controller action.
148
149
150
The RenderPartial helper is similar to Partial, but RenderPartial writes directly to the
response output stream instead of returning a string. For this reason, you must place
RenderPartial inside a code block instead of a code expression. To illustrate, the following
two lines of code render the same output to the output stream:
@{Html.RenderPartial("AlbumDisplay "); }
@Html.Partial("AlbumDisplay ")
If they are same then which one to use?
In general, you should prefer Partial to RenderPartial because Partial is more convenient
(you don't need to wrap the call in a code block with curly braces). However,
RenderPartial may result in better performance because it writes directly to the response
stream, although it would require a lot of use (either high site traffic or repeated calls in a
loop) before the difference would be noticeable.
How do you return a partial view from controller?
return PartialView(options); //options could be Model or View name
There are various ways for returning/rendering a view in MVC Razor. For example "return
View()", "return RedirectToAction()", "return Redirect()" and "return RedirectToRoute()".
Conclusion
I hope we covered many of questions to brush-up. Since MVC is very vast now, I know we
have missed a lot stuff too. The content in the question and answer form is also taken
from few renowned books like Professional ASP.NET MVC4 from Wrox and a few of the
content is taken from my MVC articles posted earlier. My future articles will provide
interview questions for EntityFramework too.
151
update TblEmployee
set EmpName = (CASE
WHEN EmpName='A' THEN 'B'
WHEN EmpName='B' THEN 'A'
ELSE EmpName
END)
4. Get the nth Largest
Consider you have a table TblEmployee with columns EmployeeName
and Salary. Find the third largest salary.
153
1. Delete b1
from BookIssue b1
join BookIssue b2
on b1.id>b2.id and b1.Book=b2.Book
155
156
Index
Only 1 allowed per table physically rearranges the data in the table to confirm to the
index constraints for use on columns that are frequently searched for ranges of data for
use on columns with low selectivity.
157
Non-Clustered
Index
Up to 249 allowed per table creates a separate list of key values with pointers to the
location of the data in the data pages For use on columns that are searched for single
values
A clustered index is a special type of index that reorders the way records in the table are
physically stored. Therefore table can have only one clustered index. The leaf nodes of a
clustered index contain the data pages. A non-clustered index is a special type of index
in which the logical order of the index does not match the physical stored order of the
rows on disk. The leaf node of a non-clustered index does not consist of the data pages.
Instead, the leaf nodes contain index rows.
Included
Column
Index
(New
in
SQL
Server
2005)
158
159
160
161
162
Ans: No in this case the finally block will not execute because when you say
system.exit(0),the control immediately goes out of the program, and thus finally never
executes.
What are the different levels of State management in ASP.NET?
Ans:
State management is the process by which you maintain state and page information
over multiple requests for the same or different pages.
There are 2 types State Management:
1. Client Side State Management
This stores information on the client's computer by embedding the information into a
Web page, a uniform resource locator (url), or a cookie. The techniques available to
store the state information at the client end are listed down below:
a. View State Asp.Net uses View State to track the values in the Controls. You can add
custom values to the view state. It is used by the Asp.net page framework to
automatically save the values of the page and of each control just prior to rendering to
the page. When the page is posted, one of the first tasks performed by page processing
is to restore view state.
b. Control State If you create a custom control that requires view state to work
properly, you should use control state to ensure other developers dont break your
control by disabling view state.
c. Hidden fields Like view state, hidden fields store data in an HTML form without
displaying it in the user's browser. The data is available only when the form is
processed.
d. Cookies Cookies store a value in the user's browser that the browser sends with
every page request to the same server. Cookies are the best way to store state data that
must be available for multiple Web pages on a web site.
e. Query Strings - Query strings store values in the URL that are visible to the user. Use
query strings when you want a user to be able to e-mail or instant message state data
with a URL.
2. Server Side State Management
a. Application State - Application State information is available to all pages, regardless of
which user requests a page.
b. Session State Session State information is available to all pages opened by a user
during a single visit.
Both application state and session state information is lost when the application restarts.
To persist user data between application restarts, you can store it using profile
properties.
Abstract Class:
Abstract class is a class which cant be instantiate. Class should have Abstract key word
with the name. In any one of the method of class having abstract method with in it,
then it should be define as abstract class. The class which derived the abstract class
should have definition of the abstract method. These classes which derived the abstract
163
164
get;
set;
}
String LastName
{
get;
set;
}
Public String GetStudentDetails()
{
// Implementation of Method
}
public String SaveStudentDetails ()
{
// Implementation of Method
}
public abstract String CalculateWage();
}
Interface can only contain the methods declaration and can be implemented in the class.
As for Example:
Public interface IStudnet
{
String Roll
{
get;
set;
}
String FirstName
{
get;
set;
}
String LastName
{
get;
set;
}
String GetStudentDetails();
String SaveStudentDetails ();
}
Below are the few main difference between Abstract Class and Interface
a. In abstract class method can have definition as well as declaration also. But
Interface should have only definition.
b. All the Methods are Public as default and dont have any access Modifier Controls in
165
interface, whereas for abstract class we can have access modifier for methods.
c. Abstract class can have constructor or destructor, whereas interface not.
d. Abstract class cant be part of multiple inheritance and we can implement
multiple interface.
What do you mean by String objects are immutable?
String objects are immutable as its state cannot be modified once created. Every time
when we perform any operation like add, copy, replace, and case conversion or when we
pass a string object as a parameter to a method a new object will be created.
Example:
String str = "ABC";
str.Replace("A","X");
Here Replace() method will not change data that "str" contains, instead a new string
object is created to hold data "XBC" and the reference to this object is returned by
Replace() method.
So in order to point str to this object we need to write below line.
str = str.Replace("A","X");
Now the new object is assigned to the variable str. earlier object that was assigned to str
will take care by garbage collector as this one is no longer in used.
What is dll hell problem in .NET and how it will solve?
Ans: Dll hell, is kind of conflict that occurred previously, due to the lack of version
supportability of dll for (within) an application
.NET Framework provides operating system with a global assembly cache. This cache is a
repository for all the .net components that are shared globally on a particular machine.
When a .net component installed onto the machine, the global assembly cache looks at
its version, its public key and its language information and creates a strong name for the
component. The component is then registered in the repository and indexed by its strong
name, so there is no confusion between the different versions of same component, or
DLL
What is a Partial class?
Ans: Instead of defining an entire class, you can split the definition into multiple classes
by using partial class keyword. When the application compiled, c# compiler will group all
the partial classes together and treat them as a single class. There are a couple of good
reasons to use partial classes. Programmers can work on different parts of classes
without needing to share same physical file
Ex:
Public partial class employee
{
Public void somefunction()
{
}
}
Public partial class employee
{
Public void function ()
166
{
}
}
What is difference between constants, read-only and, static?
Constants: The value cant be changed
Read-only: The value will be initialized only once from the constructor of the class.
Static: Value can be initialized once.
What is the cross page post backing?
Asp.Net 2.0 fixed this with built-in features that allowed us to easily send information
from one page to another.
Button control has property PostBackUrl that can be set to URL of any page in our
ASP.Net WebSite where we want to transfer all form values to.
Along with that Asp.Net 2.0 Page class has a property PreviousPage that allows us to
get reference to the Page object that initiated the postback (in other words to get the
actual reference to the Page object of the aspx page on which user clicked the Submit
button on a HTML form).
So for example lets create two sample pages in our Web Application:
SourcePage.aspx
DestinationPage.aspx
In SoucePage in Html form we will put two TextBox controls (one for First Name and one
for Last Name) and one Button component and set its PostBackUrl property to
"~/DestinationPage.aspx".
SourcePage.aspx:
<form id="form1" runat="server">
<div>
First
Name: <asp:TextBox ID="FirstName" runat="server"></asp:TextBox><br />
Last
Name: <asp:TextBox ID="LastName" runat="server"></asp:TextBox><br /><br
/>
<asp:Button ID="Button1" runat="server" Text="Submit To Destination
Page"PostBackUrl="~/CrossPagePostbacks/DestinationPage.aspx" />
</div>
</form>
When our user clicks the Submit button, all the values from the HTML Form on
SourcePage.aspx will be transfered to the DestinationPage.aspx and we will also be able
to get reference to the SourcePage.aspx in our DestinationPage with
the PreviousPage property like this:
So in our DestinationPage.aspx.cs code-behind we can easily access two TextBox
controls on SourcePage.aspx and show them in two label controls like this:
protected void Page_Load(object sender, EventArgs e)
{
// first check if we had a cross page postback
if ( (PreviousPage != null) && (PreviousPage.IsCrossPagePostBack) )
167
168
Ans: The difference between application exception and system exception is that system
exceptions are thrown by CLR and application exceptions are thrown by applications.
What is the difference between authorization and authentication?
Ans: Authorization is a process of allowing or denying resources to particular user or
record
Declaration of authorization is
<authorization>
<allow users=Suresh, Sanjay/>
<deny users=Ramana, Rakesh>
</authorization>
Sometimes authorization allows the unauthorized persons at that time we will use
<deny users=?/>
Authentication means
169
170
What is Collation?
Ans: Collation refers to a set of rules that determine how the data is sorted and
compared.
What is the difference between Primary key and unique key?
Ans: Primary key does not allow the null values but unique key allows one null value.
Primary key will create clustered index on column but unique key will create nonclustered index by default.
How many web.config files are there in 1 project?
Ans: There might be multiple web.config files for a single project depending on the
hierarchy of folders inside the root folder of the project, so for each folder we can use
one web.config file
What is the difference between throw and throw ex?
What is the difference between view state and hidden field?
Ans: viewstate is secured hidden field is insecure
Viewstate will store large amount of data but hidden filed will store small amount of
data.
What is the difference between binary serialization and xml serialization?
What is the Difference between read only and constant variables?
Ans: Read only can assign the values at runtime only.
Constant will assign the values at compile time only.
We cannot modify the both variable values.
What is static keyword in .Net?
Ans: Static is same as constant variable but we can change the value of static variable
and we can access the variables without creating any instances
What is the use of business logic layer in 3-tier architecture in .net?
Ans: Though a web site could talk to the data access layer directly, it usually goes
through another layer called the business layer. The business layer is vital in that it
validates the input conditions before calling a method from the data layer. This ensures
the data input is correct before proceeding, and can often ensure that the outputs are
correct as well. This validation of input is called business rules, meaning the rules that
the business layer uses to make judgments about the data.
However, business rules dont only apply to data validation; these rules apply to any
calculations or any other action that takes place in the business layer. Normally, its best
to put as much logic as possible in the business layer, which makes this logic reusable
across applications.
171
One of the best reasons for reusing logic is that applications that start off small usually
grow in functionality. For instance, a company begins to develop a web site, and as they
realize their business needs, they later decide to add a smart client application and
windows service to supplement the web site. The business layer helps move logic to a
central layer for maximum reusability.
Reference types: This type doesnt hold the data directly. They hold the address
on which the actual data present. They stored in heap memory, Can have default
values.
We can make and work with null reference type.
6. Boxing and Unboxing: Terminology, Advantages and Disadvantages.
A. Converting the value type data type in to the Reference type is called as
Boxing. Converting the Reference type data type and keep its value to stack is
called as the reference type.
byte b= 45;
Object o = b.Tostring();
The Advantage of boxing and unboxing is that we can convert the type of the
object in to another type. The disadvantage is that it requires lot of memory and
CPU cycles to convert from one type to another type.
Object o=10;
Int i= Convert.ToInt32(o.ToString());
Now it will have the unique name. This assembly when placed in the GAC, it will
treat as the unique with its version number and other details. 2 assemblies with
the same name can exist in the GAC but both will have different version. The
CLR takes the latest version assembly while running the application.
9. What are Extensions, modules and handlers?
A. HttpModule and HttpHandler are the utilities which are used in the
HttpPipeline under the ASP.Net page life cycle. When the request received to
HttpPipeline, the HttpModule checks for the Authentication of the request and
then it route the request to the respective handler. After that HttpHandler takes
that request and process it. After Processing the request again the HttpModule
takes the response and send it back to the worker process and finally to the
user.
10. What is worker process?
A. Worker process (w3wp.exe) is an executable which is also called as the
Application Factory. This is used for the execution of the request and handling of
the request for the current web page.
11. CLR and DLR?
A. CLR (Common Language Runtime) is the utility in the .Net framework to run
the application. It is the run-time engine which actually executes the application
with many responsibilities like taking care of memory management, versioning,
CasPol etc.
DLR is new with .Net 4.0 which is the Dynamic Language Runtime and used to
run the application on the fly wherever required. CLR runs as statically while DLR
runs dynamically.
173
12. In case more than one version of an installable is installed, which version is
invoked by default?
A. By default the CLR will take and invoke the latest version of the dll and
execute it accordingly. There could be the same name assemblies exists in the
GAC but they will have different versions altogether for their uniqueness.
So while running the application, CLR takes the latest version assembly and use
in the application.
13. What are Globalization and localization? How to implement them?
A. Globalization is the concept of developing the application in more than one
language while the Localization is used for a particular language. Like if we
develop the application in more than one language we need to create the
resource files (.resx) by using System. Globalization and when we open the
application in a particular language, then the localizations used to convert that
application to the selected language.
14. What is assembly, GAC? Where they are physically located?
A. Assembly is the collection of classes, namespaces, methods, properties which
may be developed in different language but packed as a dll. So we can say that
dll is the assembly.
There are 3 types of assemblies- Private Assembly, Shared Assembly, and
Satellite Assembly.
GAC (Global Assembly Cache)- When the assembly is required for more than
one project or application, we need to make the assembly with strong name and
keep it in GAC or in Assembly folder by installing the assembly with the GACUtil
command.
To make the assembly with strong name:
SN -k MyDll.dll
In the Out-proc session state, the session data is stored in the separate servermay be state server or in sql server.
17. When the View state is saved, and when is it loaded? How to enable/ disable
View states?
A. View State data is stored in the current page in base64 encoded format. It
gets loaded with the page and displays the values to the controls after the
decoded. Internally it actually saves the check-sum of all the control data where
the view state is enabled.so that when the page gets loaded due to any post
back, it again finds the check-sum and then decodes the Base64 encoded string
and gets back the same data to the controls. We can see the view state base 64
encoded string in View Source of the page. It will be
like _VIEWETATE="DSDSDF8DGDGDFGFD5FDGGDJFF23BNN457M9UJOG" this.
View state won't take the client or server memory to keep the view state data.
18. Difference between GET and POST. Which one is more secure?
A. GET and POST methods are used for the data transfer between the web
pages. GET mainly used for small data which is not secure because in case of
GET method, the data which we are passing will be visible in the url so we can't
keep the secure data which will be visible in the url. There is also limited data
which can be passed in case of GET method (max 255 character).
POST is used for transferring the huge data between the pages where we can
keep the secure data and can transfer it. In case of using the POST method, the
data which is transferring between the pages will not be visible so it is more
secure than the GET method. Also there is no limit for POST method to post the
data to the next page.
POST is more secure.
19. What are Razor engines? How is it diff from ASP Engines?
A. RAZOR engine is the new concept in the MVC 3 which is mainly used to create
the views in the MVC applications. It created the cshtml pages for the MVC
application and cshtml pages can be generated automatically by using the Razor
engine.ASP engine create the aspx pages while Razor engine creates the pages.
20. Pros and cons of JavaScript and AJAX.
A. JavaScript is a scripting language and mainly used for client side validation.
We can validate the client side data before sending to the server. So by this we
can improve the performance of the application.
Ajax is Synchronous JavaScript and XML which is used for the Asynchronous
calls from the server. It uses internally the JavaScript for making the call and use
XML for the Data Transfer. It basically uses the XmlHttpRequest for the
asynchronous calls to the server and communicates with the XML data which is
platform independent. So Ajax can be used with any technology.
21. In how many different ways can JavaScript be used/called in an application?
A. JavaScript can be used for Client Side validation, can also be used for calling
of server side methods and functions, can be used for calling the web services
etc.
22. What needs to be done to call a JavaScript function from code behind?
A. If we want to call the JavaScript function from the code behind, we need to
attach the JavaScript to the events in the page_load event as:
175
Here ValidateData is the JavaScript function which can be used to validate the
page data and if validation fails, it will return and will not execute the server side
btnSave_click event.
23. Difference between Server Controls and User controls?
A. User controls are used for the re-usability for the controls in the application.
By using the user control, we can use the same control in the various pages.
User controls can be created by combining more than one control. To use the
user controls, first we need to register them in the web page where we want to
use that control. A separate copy is need in each page where we want to use the
user control. User controls can't be included in to the toolbox.
Server controls are those controls which can be found in the toolbox and can be
directly drag to the application like textbox, button etc. For the server control,
only 1 copy of the control is needed irrespective of the number of web pages. If
we want 10 text-boxes to be added in our web page, we need only 1 copy of the
textbox in the toolbox and can be dragged 10 times.
24. Difference between Var, object and Dynamic types.
A. var is the keyword introduced with .net 3.5 and used to store any kind of data
like data-set, data table, int, float, char etc. We can keep any kind of data in the
var variable.
var myVar = new String[] {"hello", "world!!"} ;
Here the myVar is the var type variable which is used to store the string array.
Like this we can store any type of data into the var.
Object is the type which is used to store the objects of any kind. These objects
need to be type caste when required.
Like object mybject = "Hello"
Here the myObject variable of object type is used to keep the string variable.
Now when we want this variable value, we need to typecast it like
string strvar= (string) myobject;
Dynamic- Its a keyword introduces with the .net 4.0 and used to keep the data
similar to the var keyword. The difference between the var and dynamic is that
the dynamic variable uses the same memory location to store the object and not
changes throughout the application.
25. Difference between Functions and methods.
A. in.Net terminology, both are same. in general, we use method in .net but in
scripting language we use function like JavaScript function.
Here the difference can be Function always returns a value which method may or
may not. It depends upon the return type of the method.
26. Difference between Abstract classes and Interface. Explain with scenario
where to implement one?
A. Collection of the Abstract (Incomplete) and Concrete (complete) methods is
called as the Abstract class. If there is at least one abstract method in a class,
the class must be abstract class.
When there is the similar behavior, we can use the abstract class.
e.g. We want to calculate the area of few component. As this is not generic to
the application. We have only few component- like Circle, Ellipse, parabola,
176
Now in the child class, lets say i have a circle class and want to calculate the
area of the circle:
public class Cicle: MyAbstractClass
{
public override void Area()
{
// calculate the area of the circle
}
}
Now as this is the generic functionality and can be implemented in any of the
page so we have taken it as interface. Now we can implement this functionality
in to any page like:
class MyClass:Inf
{
public void print
{
// write details about the print
}
// Here we can implement any kind of print-like print to excel, xml, word all depends on
the our decision.
}
177
}
}
Public class MyChildClass: MyBaseClass
{
public override void Show(string message)
{
Console.WriteLine(Your new message is : + message);
}
}
When the run-time (CLR) find the behavior of class members at the compilation
of the program, it is called as the Classical polymorphism or Overloading.in this
the method name is same but there prototypes (parameters) are different and it
is implemented in the same class.
e.g.
public class MyClass
{
Public int Add(int a, int b)
{
Return a+b;
}
Public int Add(int a, int b, int c)
{
Return a+b+c;
}
}
Abstraction is the behavior to get the required functionality in the child class. So
we dont matter whatever is written in the base class. We only need to force the
child class to implement my required functionality.
Abstract keyword is used to get the abstraction behavior.
28. What are Delegates and Events?
A. A Delegate is an object, which points to another method in the application.
Delegate holds, name of the method, arguments of the method (if any) and the
return type of the method.
See the below points regarding the Delegate:
delegate keyword is sealed type in System. Multicast namespace.
Delegate hides the actual information which is written inside the method
definition.
Addition and subtraction are allowed for the delegates but NOT
multiplication and division. It means, we can add delegates, subtract delegates
etc.
e.g. To create a single cast delegate, first we can create a class with a method
as:
public class DelegateDemo
{
public void Show(string msg)
{
178
Console.WriteLine(msg);
}
}
Now we can call the method Show using the delegate as:
public delegate void MyDelegate(string message); //declare delegate
now we need to create the object of the delegate with the address of the method
as:
DelegateDemo obj = new DelegateDemo();//class object
MyDelegate md= new MyDelegate(obj.Show(Hello World!!));
md(); // call the delegate
We can create the events and event handler by using delegate with the below
syntax:
public delegate void textChangedEventHandler(Object sender, TextEventArgs e);
This event handler will be used to handle the textbox text changed event.
We can get more details about the delegate and events from the below link:
http://msdn.microsoft.com/en-in/library/orm-9780596521066-01-17.aspx
179
In order to extract the matched row from both the tables and unmatched row
from the second table, right Outer join is used. The syntax for right outer join
condition is:
T.Col1 = *T2.Col1
In order to extract the matched row from both the tables and unmatched row
from the first table and then unmatched row from the second table, full join is
used. The syntax for full join condition is:
T.Col1* = *T2.Col1
b. Temp tables are only visible to the current sessions of the sql server instance.
When the session end, these table data automatically drops.
c. We cant join the temp tables as they dont allow the foreign key constraints.
d. Temp tables are created in TempDB database.
e. We can use the same temp table name for the different user sessions.
f. Mostly used in stored procedure to handle the intermediate data.
41. What does @ and @@ suffixed by property names specify?
A. @- This is used for the variable declaration
e.g. @name varchar2(50)
@@- This is used for the Global variable declaration
e.g. @@Error=0
42. Self-join queries.
A. Self-Join is a type of join which is used to join the same table by creating the
second instance of the same table. So we join 2 instances of the same table in
case of self-join. This type of join is used when there is the requirement to get
the referenced data which is available in the same table.
e.g. A table contains EmpId, Ename and ManagerId
As the manager id is also an employee id. Now if we want that who is the
manager of which employee. In this situation, we need to create the instance of
the same table and get the required data as:
SELECT EMPID, ENAME, ENAME AS [MANAGER NAME]
FROM EMP E1, EMP E2
WHERE E1.EMPID= E2.MANAGERID
Candidate key- the key other than primary key to make the rows as unique is
called as candidate key. In candidate key, we take the columns which are not in
the primary key and make the key for uniqueness of the row.
45. What is the default value for Date type. What are Min and Max values for
Date in 2008.
A. The default value of Date is CURRENT_TIMESTAMP
Below are the new date and time values in Sql Server 2008:
In SQL Server 2008:
1. DateTime2
Min Value: 0001-01-01 00:00:00.0000000
Max Value: 9999-12-31 23:59:59.9999999
2. Date
Min Value: 0001-01-01
Max Value: 9999-12-31
You can go through the below link for couple of work around:
http://dhaneenja.blogspot.in/2008/06/minimum-year-value-in-sql-server.html
WCF
46. What is WCF also known as?
A. WCF (Windows Communication Foundation) is also know an Indigo by its
code name.
47. Difference between WCF and Web Services?
A. Below are the main differences between the WCF and Web Service:
Web Service:
a. Can be hosted in IIS only
b. Only two types of operations affects- One-Way, Request-Response
c.
To serialize the data use System.Xml.Serialization
d. To encode the data use- XML 1.0, MTOM, DIME, Custom
WCF service:
a. Can be hosted in IIS, Self Hosting, WAS, Windows Services etc
b. Three types of operations affects- One-Way, Request-Response and Duplex
c.
To serialize the data use System.Runtimel.Serialization
d. To encode the data use- XML 1.0, MTOM,Binary, Custom
e. WCF Service can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P
etc.
48. What are Endpoints?
A. The collection of Address, Binding and Contract is called as End Point. In Sort,
EndPoint = A+B+C
Address (Where)- it means where the service is hosted. URL of the service
shows the address.
Binding (How)- How to connect to the service, is defined by the Binding. It
basically has the definition of the communication channel to communicate to the
WCF service
Contract (what)- It means what the service contains for the client. What all the
methods are implemented in the WCF service is implemented in the Contract.
49. What are Behavior and Bindings?
A. Binding mainly describes about the communication of the client and service.
183
For this, there are protocols corresponding to the binding behavior which will
take care of the communication channel. There are different protocols which we
use for the different types of bindings. E.g. HTTP, TCP, MSMQ, Named Pipes etc.
Behavior is used for the common configurations that could be for endpoints.
When we use the common behavior, they affect to all the end points. Adding the
service behavior affect the service related stuff while the endpoint related
behavior affects the end points. Also operations level behavior affects the
operations.
50. What are different types of Contracts supported?
A. There are mainly 5 type of contracts used in WCF service:
a. Service Contract
b. Operation Contract
c. Data Contract
d. Message Contract
e. Fault Contract
51. What is the difference between Transport and Message Security mode?
A. WCF supports 2 types of security- Transport Level Security and Message Level
Security
Transport Level Security- In this type of security, we make the transport channel
as secure so that the data flows in that channel will be automatically secured.
For HTTP channel, we use the client certificate for the security of the web
address. SSL is used for the HTTP channel security. As we dont need to secure
each of the messages which are floating between the client and the service, the
speed is faster as direct message is going to the client from the service.
Message level security- This type of security in WCF is used where we dont have
the fixed transport medium and we need to secure each message which is
floating between the server and the client. In this type of security we use certain
algorithms for making the message as secure message. We use some extra bits
and send with the message. We also use some encryption techniques like SHA1
or MD5 which make the proper security for our message. As each message
needs to be secured, this type of security makes some delay in the process of
sending and receiving the messages.
52. How to configure WCF security to support Windows authentication?
A. To support the WCF security in Windows Authentication, we need to add the
ClientCredetialType attribute to Windows under the security tab element:
transport clientCredentialType="Windows"
53. How to use Fault Contract?
A. Fault Contract is mainly used for viewing and displaying the errors which
occurred in the service. So it basically documents the error and the error
message can be shown to the user in the understandable way. We cant use here
the try.catch block for the error handling because the trycatch is the
technology specific (.Net Technology). So we use the Fault contract for the error
handling.
e.g. To use the Fault contract, we can simply write like the below:
public int Add(int number1,int number2)
{
// write some implementation
throw new FaultException (Error while adding data..);
}
184
Here the fault Exception method is the inbuilt method which will throw the
exception and display the message . We can use the custom class so that the
message can be customized and the customized message can be sent to the
client.
So we can creeat a clss like:
Public Class CustomException()
{
public int ID{get;set;}
public string Message{get;set;}
public string Type{get;set;}
}
Now this custom type we ca use with the Operation Contract as:
[ServiceContract]
Public interface IMyInterface
{
[OperationContract]
[FaultContract(typeOf(CustomException))]
Int Add(int num1,int num2);
}
Now while implementation of the Add method, we can assign the class
properties.
WPF
54. Diff between XML and XAML.
A. XAML is the declarative XML based language which is used to define the
objects and properties. XAML document is loaded by XAML parser. So XAML
Parser initiates the objects and set those properties. XAML is mainly used in
creating the objects in WPF and Silverlight applications.
For more detailed explanation, you can go through the below link:
http://www.differencebetween.net/technology/software-technology/differencebetween-xml-and-xaml/
55. Stack Panel and Wrap Panel.
A. StackPanel is one of layout control in WPF. We can place the child controls
inside the stack panel either horizontally or vertically. So it provides two types of
orientations- Horizontal Orientation and Vertical orientation.
You can go through the below link for more detailed explanation and the code
snippet:
http://wpftutorial.net/StackPanel.html
Wrap panel is another layout control which is similar to the StackPanel. Wrap
panel not only keep the control in horizontal and vertical orientation but also
wrap them in to new line if there is no space. Here also the orientation can be
set as Horizontal or Vertical. Its main use is to arrange the tabs in the tab
control, menu control or in toolbar items.
You can go through the below link for more details:
http://wpftutorial.net/WrapPanel.html
57. Virtualization.
A. This is the feature in WPF which increases the efficiency of the programs
when there are the large data objects. If the WPF ItemsControl is bound with the
large collection data source object and we enabled the virtualization, then the
controls will show only the data which is in the visual container for those items
which are visible currently. This visual data is only the small part of the large
data object. Now when the user will scroll down or up, the rest of the data will
be visible and previous data will be hidden again. So this is increase the
efficiency of the program from the UI prospective.
58. Events and Routed Events.
A. Routed event is special type of event which can invoke and handle multiple
events from different objects rather than the event which is coming from one
object. So it generally handles the object from the element tree. So whatever
the elements inside the element tree and if they generate the event-may be
multiple events, the routed event is capable of handling those events.
The routed event can be invoked in both the directions but in general it comes
from the source element and then bubbled up in the element tree until the root
element.
59. Bubbling and Tunneling.
A. Bubbling: When the events are raised form the innermost element in the
visual tree and comes up towards the root element, is called as bubbling.
Tunneling: It is the opposite process of Bubbling where the events fired by the
root element goes down towards the last child element control.
Please go through the below link for more details:
http://www.dotnetspider.com/forum/130497-event-bubbling-event-tunneling.aspx
EventAggregator : It is the utility service which contains the events and allows
the decouple the publisher and subscriber so that they can be buildup
independently. Decouple is primarily useful when a new module needs to be
added or removed or modified. The new module can be added as per the event
fired and defined in the shell.
For more details about the Event Aggregator, you can follow the below link:
http://msdn.microsoft.com/en-us/library/ff921122(v=pandp.20).aspx
http://msdn.microsoft.com/en-us/library/ff921139(v=pandp.20).aspx
Region and Region Managers: This is concept of Prism framework. We define the
region through XAML code and once a region is defined, automatically it will be
registered with the RegionManager. Actually the Bootstrapper registers a service
called the RegionManager at run time. RegionManager is a dictionary where the
key is name of the region. The value of the key is the reference of the IRegion
interface. RegionAdapter is used to create the instance reference of the IRegion
interface.
You can go through the below link for more details about the Region and Region
Manager:
http://msdn.microsoft.com/en-us/magazine/cc785479.aspx#id0090091
http://msdn.microsoft.com/en-us/library/dd460648.aspx
65. How to navigate to another page?
A. There is a class NavigationService which can be used for navigation of the
187
WPF window:
this.NavigationService.GoForward();
//or
this.NavigationService.Navigate("MysecondPage.xaml")
1.
2.
3.
4.
Init
Raised after all the controls have been initialized with their default values
and any skin settings have been applied.
1.
1.
In this event page processes postback data included in the request object
pass it to the respective controls.
PreLoad
3.
188
Used only if want to inject logic before actual page load starts.
Load
Used normally to perform tasks which are common to all requests, such
as setting up a database query.
Control events
1.
Use the event to make final changes to the contents of the page or its
controls before the values are stored into the viewstate and the rendering stage
begins.
1.
All the control values that support viewstate are encoded and stored into
the viewstate.
RenderGenerates output (HTML) to be rendered at the client side.
We can add custom HTML to the output if we want here.
Unload
Fired for individual controls first and then for page.
2. Used to perform cleanup work like closing open files and database
connections.
1.
189
2.
The basic and main difference between cookie and session is that cookies are
stored in the user's browser but sessions can't store in user's browser. This
specifies which is best used for.
A cookie can keep all the information in the client's browser until deleted. If a
person has a login and password, this can be set as a cookie in their browser so
they do not have to re-login to your website every time they visit. You can store
almost anything in a browser cookie.
Sessions are not reliant on the user allowing a cookie. They work like a token
in the browser which allowing access and passing information while the user has
opened his browser. The problem in sessions is when you close the browser the
session will automatically lost. So, if you had a site requiring a login, this
couldn't be saved as a session but it can be saved as a cookie, and the user has
to re-login every time they visit.
cookies are nothing but a small piece of information on the client machine.
before we create a cookies we should check whether the cookies are allowed at
the browser side. They are limited in a size 4k.(they are 2 types of cookies
peristant cookie , and session cookies)
Sessions cookies are stored in a server memory during the client browser
session.When the browser is closed the session cookies are lost.
4.) Advantages and disadvantages of Session?
Following are the basic advantages and disadvantages of using session. I have
describe in details with each type of session at later point of time.
Advantages:
It helps maintain user state and data all over the application.
Disadvantages:
12). Can you describe all the property set in web.config under session
state?
Ans:
Code:
<configuration>
<sessionstate
mode="inproc"
cookieless="false"
timeout="20"
192
Mode: The mode setting supports three options: inproc, sqlserver, and
stateserver. As stated earlier, ASP.NET supports two modes: in process and out
of process. There are also two options for out-of-process state management:
memory based (stateserver), and SQL Server based (sqlserver). We'll discuss
implementing these options shortly.
Cookieless: The cookieless option for ASP.NET is configured with this simple
Boolean setting.
Timeout: This option controls the length of time a session is considered valid.
The session timeout is a sliding value; on each request the timeout period is set
to the current time plus the timeout value
Sqlconnectionstring: The sqlconnectionstring identifies the database connection
string that names the database used for mode sqlserver.
Server: In the out-of-process mode stateserver, it names the server that is
running the required Windows NT service: ASPState.
Port: The port setting, which accompanies the server setting, identifies the port
number that corresponds to the server setting for mode stateserver.
13). What are Session Events?
Ans: There are two types of session events available in ASP.NET:
Session_Start
Session_End
You can handle both these events in the global.asax file of your web application.
When a new session initiates, the session_start event is raised, and the
Session_End event raised when a session is abandoned or expires.
14). How you can disable session?
Ans: If we set session Mode="off" in web.config, session will be disabled in the
application. For this, we need to configure web.config the following way:
Code:
<configuration>
<sessionstate Mode="off"/>
</configuration>
15). If I have more than one version of one assemblies, then how will I
use old version (how/where to specify version number?) in my
application?
Ans.The version number is stored in the following format: . The assembly
manifest can then contain a reference to which version number we want to use.
193
16). How do you create threading in.NET? What is the namespace for
that?
Ans.
System.Threading;
//create new thread using the thread classs constructor
Thread myThread = new Thread(new ThreadStart (someFunction));
17). What do you mean by Serialize and MarshalByRef?
Serialization is the act of saving the state of an object so that it can be recreated
(i.e deserialized) at a later date.
The MarshalByRef class is part of the System.Runtime.Remoting namespace and
enables us to access and use objects that reside in different application
domains. It is the base class for objects that need to communicate across
application domains. MarshalByRef objects are accessed directly within their
own
application domain by using a proxy to communicate. With MarshalByValue the a
copy of the entire object is passed across the application domain
18). What is the difference between Array and LinkedList?
An array is a collection of the same type. The size of the array is fixed in
its declaration.
A linked list is similar to an array but it doesnt have a limited size.
19). What is Asynchronous call and how it can be implemented using
delegates?
A synchronous call will wait for a method to complete before program flow is
resumed. With an asynchronous call the program flow continues whilst the
method executes.
//create object
SomeFunction objFunc = new SomeFunction();
//create delegate
SomeDelegate objDel = new SomeDelegate(objFunc.FunctionA);
//invoke the method asynchronously (use interface IAsyncResult)
IAsyncResult asynchCall = SomeDelegate.Invoke();
20). How to create events for a control? What is custom events? How to
create it?
Ans.
An event is a mechanism used in a class that can be used to provide a
notification when something interesting happens. (typical evens in a windows
application
include: change text in textbox, double click or click a button, select an item in
dropdown box).
194
A custom event is an event created by the user that other developers can use.
For example assuming that we have a CashTransaction class and we have a
bank
balance property in that class. We may want to set-up an event that provides a
notification when the bank balance drops below a certain amount. In order to
produce an event the process would be roughly as follows:
Create the class for the event derived from EventArgs.
Create a delegate with a return type of void.
Create a class containing the method that will activate the event.
Create a class with methods to handle the event.
21). If you want to write your own dot net language, what steps you
will you take care?
We will need to ensure that the high level code is compiled to MSIL (Microsoft
intermediate language) so that it can be interpreted by the CLR.
22). Describe the diffeerence between inline and code behind - which is
best in a loosely coupled solution?
The term code behind refers to application code that is not embedded within
the ASPX page and is separated out into a separate file which is then referenced
from the ASPX page. Inline code is the traditional ASP architectural model where
business logic code was embedded within the ASP page. Separating the
business
logic code from the presentation layer offers several advantages:
1) It allows graphic designers and web developers to work on the presentation
layer whilst the application developers concentrate on the business logic.
2) The codebehind file is compiled as a single dll increasing the efficiency of the
application,
3) The codebehind model offers a true OO development platform,
4) It speeds up development time as it allows developers to fully maximise the
features of the .NET framework such as Cahing, ViewState, Session, Smart
Navigation etc.
5) Code is much easier to maintain and susceptible for change.
6) The compiler and VS.NET provides much better support for error checking,
intellisense and debugging when using the code behind model.
23). How dot net compiled code will become platform independent?
The raison detre for .NET was to cater for multiples languages on a single
windows platform whereas the aim of Java was to be a single language on
multiple
platforms. The only way that .NET can be platform independent is if there is a
version of the .NET framework installed on the target machine.
24). Without modifying source code if we compile again, will it be
generated MSIL again?
Ans.No.
195
25). How does you handle this COM components developed in other
programming languages in.NET?
Ans.
use TlbImp.exe to import the COM types into your .NET project. If no type
library for the COM component then use System.Runtime.InteropServices
use RegAsm.exe to call a .NET developed component in a COM application.
26). How CCW (Com Callable Wrapper) and RCW (Runtime Callable
Wrappers) works?
CCW:
proxy
RCW:
proxy
When a COM application calls a NET object the CLR creates the CCW as a
since the COM application is unable to directly access the .NET object.
When a .NET application calls a COM object the CLR creates the RCW as a
since the .NET application is unable to directly access the .COM object.
27). What are the new thee features of COM+ services, which are not
there in COM (MTS)?
Role based security.
Neutral apartment threading.
New environment called context which defines the execution environment
28). What are the differences between COM architecture and.NET
architecture?
.Net architecture has superseded the old COM architecture providing a flexible
rapid application development environment which can be used to create
windows,
web and console applications and web services. .NET provides a powerful
development environment that can be used to create objects in any .NET
compliant language.
.NET addresses the previous problems of dll hell with COM by providing strongly
named assemblies and side-by-side execution where two assemblies with the
same name can run on the same box.
29). Can we copy a COM dll to GAC folder?
Ans.
No. It only stores .NET assemblies.
30). What is Shared and Repeatable Inheritance?
Shared Inheritance-: Shared Inheritance-: ITt is multiple times using same
class. The mechanism of deriving a new class from an existing class is called
inheritance. Shared inheritance introduces a new opportunity of ambiguity and
additional implementation complexity. Assume D inherits from B and C, both of
which inherits from A. Here A in shared. Single copy made from both derived
classes is called shared inheritance.
196
31). Can you explain what inheritance is and an example of when you
might use it?
Ans.
Inheritance is a fundamental feature of any OO language. It allows us to inherit
the members and attributes from a base class to a new derived class. This
leads to increased code reusability and also makes applications easier to
develop, maintain and extend as the new derived class can contain new features
not
available in the base class whilst at the same time preserving the attributes
inherited from the base class.
32). How can you write a class to restrict that only one object of this
class can be created (Singleton class)?
Ans.
Use the singleton design pattern.
public sealed class Singleton
{
static readonly Singleton Instance=new Singleton();
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return Instance;
}
}
}
33). What are virtual destructures?
A constructor can not be virtual but a destructor may. Use virtual destructors
when you want to implement polymorphic tearing down of an object.
34). What is close method? How its different from Finalize and
Dispose?
finalise is the process that allows the garbage collector to clean up any
unmanaged resources before it is destroyed.
The finalise method can not be called directly; it is automatically called by the
CLR. In order to allow more control over the release of unmanaged resources
197
the .NET framework provides a dispose method which unlike finalise can be
called directly by code.
Close method is same as dispose. It was added as a convenience.
35). What is Boxing and UnBoxing?
Ans.
Boxing is the process of converting a value type to a reference type. More
specifically it involves encapsulating a copy of the object and moving it from
stack to heap. Unboxing is the reverse process.
36). What is check/uncheck?
Ans.
checked: used to enable overflow checking for arithmetic and conversion
functions.
unchecked: used to disable overflow checking for arithmetic and conversion
functions
37). What is the use of base keyword? Tell me a practical example for
base keywords usage?
Ans.
The base keyword is used to access members of the base class from within a
derived class:
* Call a method on the base class that has been overridden by another method.
* Specify which base-class constructor should be called when creating instances
of the derived class.
A base class access is permitted only in a constructor, an instance method, or an
instance property accessor.
It is an error to use the base keyword from within a static method.
Example:In this example, both the base class, Person, and the derived class,
Employee, have a method named Getinfo. By using the base keyword,
it is possible to call the Getinfo method on the base class, from within the
derived class.
// keywords_base.cs
// Accessing base class members
using System;
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";
public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
198
}
}
class Employee: Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}
class TestClass {
public static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
Session
cookies is a text file stored on client machine when we surf ant thing on
internet by the server automatically we dont have to create it
query string is used to transfer data from 1 page to anothe but this is not safe
s it shows in url what data we r sending
pen any site and see url after question mark tht is url
Cookies: - Cookies are little pieces of information that a server stores on a
browser. They are of two types
1. Temporary cookie
2. Persistent cookie
Temporary cookie: - They are also known as session cookies. These are volatile
in nature. When the browser is shutdown they are erased.
Persistent cookie:- These may be called as permanent cookies. These are
especially saved in files. It may remain for a month or year.
Properties of cookies
Some properties of cookie
Name: - represent the name of cookie.
Name value: - represent a collection of key values of cookie
Domain: - represent the domain associated with a specific cookie.
Path: - the path associated with a cookie.
Expires: - expired time of cookie.
Hashkey: - identifies whether the cookie is a cookie dictionary.
Secure: - specifies whether the cookie is to be sent in an encrypted connection
or not
Query string is the limited way to pass information to the web server while
Transferring from one page to another page. This information is passed in url of
the request. see below the code sample
Code Sample
//Retrieving values from query string
String name;
//Retrieving from query string
name = Request.Param["umar"].ToString();
But remember that many browsers impose a limit of 255 characters in query
strings. You need to use HTTP-Get method to post a page to server otherwise
query string values will not be available.
In-Process
2.
Out-of-Process.
201
2 yr experinced interview
i would like to share my experience of interview conducted on last week.It may
help others who are looking for job change.
The interview was technical face to face interview.
Duration:45 mins
Here are the questions.
* what are the technologies you have used ?
* what is grid view?
* write a code to bind dropdownlist in grid view?
* Are you good in writing stored procedures in sql server?
* what are the differences b/w stored procedures and function?
* what are the data types available in sql server?
* what are the differences b/w char,var char and nvarchar?
* Explain transaction management in sql ?
* Can u write an example for commiting an transaction and rollback of a
transaction.?
* How to generate reports?
* How to generate reports in c#?
* Explain rdlc?
* Explain Master Page?
* Explain the Projects u have worked?
202
in WCF
1. How to consume WCFservice in our application?
2. How to get json data using WCF service ?
3. Different contracts in wcf
4. What is ABC?
5. What is mexhttp bindng?
6. Binding types in WCF?
7. Modes in WCF?
8. How many types of Hosting in WCF service ?
9. What is SOAP ?
10.Which namespace is used for XML Serialization ?
then next Round is Project Manager Round. in this round the interviewer
focused not only on projects but also some real time questions . it took nearly
(1:20 min Manager round only)
These are first two questions in project manager round
1. What are the technologies you are used ?
204
2 .How many projects you have worked on with client names on which
technology and explain any two projects briefly ?
in Manager Round the interview asked these questions..
1. I have one WCF service with 5 methods ? how to give 2 methods to client
1 and remaining three to client 2 . How to restrict access the remaining 3
methods to client 1 and same as client 2 the remaining 2 methods ?
2. When we use Message Contract ?
3. How to use Shared assembly ?
4. How to show second 100 records to client ?
5. How to get data from web.config
6. Diff between web.confing and app.config ?
7. I have wrote one method with try catch block. in try block i have write int
a = 100 / 0 ; , but there is no "dividebyzero exception" in catch block. how
to throw that exception to catch block ?
8. what is Collections ? diff between List and IEnumarable ?
MICROSOFT INTERVIEW QUESTIONS .NET 3+ YEARS EXPERIENCED
Hi friends,
I attened interview(06/09/2014) recently to microsoft in Bangalore,India. It was so good to
shortlist my resume why because they shortlisted only 10-15 members on that day but only
few pepole came for interview..I'm happly gone for the interview..About my experience in that
interview i'm sharing some of the questions as what they asked me. Most of the they are
asking logically(how internally working) and practical things.
In First round of interview has prescreening test and it's around 30Mins.
Second Round Of interview has Technical discussion and it's around 2 Hr 30 Mins..
1)
2)
A)
3)
Tel me about yourself briefly and what your have done in between 3 years of your carrier?
Which domain will you prefer if we give business opportunity? Why should we take about it?
Windows Azure.
Why you prefer windows azure and there are so many languages and is there any special
about it?
4) Have you worked any design pattern ?
A) MVC Design pattern I worked
5) Do you know the types of design patterns?
A) Yes I know and I told about Abstract and Singleton and MVC and so on
6) What is singleton pattern ?
7) Have you worked on Azile methodologies ? No
8) What is the CLR ? How it works ?
9) What is CLR and Base Class Libraries?
10) What is IL ?
11) What is Managed Code and unmanaged code?
12) Suppose if develop one application in .net and after compilation which format is coming?
A) .exe
13) .exe how it produces any techniques are there?
14) Once building the application in mean time JIT or CLR unexpectedly stopped whether its
MSIL or Binary format?
205
15)
16)
17)
18)
19)
20)
21)
22)
23)
24)
25)
26)
54)
55)
56)
57)
58)
59)
60)
61)
62)
63)
64) What is Unit Testing and System Testing and who will do both testing ?
207