Tricky Questions
1.
If I’m developing an application that must accommodate multiple security levels
though secure login and my ASP.NET web application is spanned across three
web-servers (using round-robin load balancing) what would be the best approach to maintain login-in state
for the users?
Answer:
You can use the security state maintained using a database. (Use Authentication
mode as database)
2. What’s the difference between
Code behind=”MyCode.aspx.cs” and src=”MyCode.aspx.cs” mce_src=”MyCode.aspx.cs”?
Answer:
Visual Studio uses the Code behind attribute to distinguish the page source or
programming logic from the design. Also the src attribute will make the page
compile on every request. That is the page will not be compiled in advance and
stored in the bin as a dll instead it will be compiled at run time.
3.
Suppose you want a certain
ASP.NET function executed on Mouse Over over a certain button or textbox. Where
do you add an event handler?
Answer:
Every web control has an ability to add the attributes on client side which
will execute on client side and run a client side script like a JavaScript
function.
btnSubmit.Attributes.Add
(“onMouseOver”,”someClientCode () ;”) //For on mouse over of a button
TextBox1.Attributes.Add(“onFocus”,“ClearText();”)
//For on focus of a text box
4.
Explain what a diffgram is and
a good use for one?
Answer:
The DiffGram is one of the two XML formats that you can use to render Dataset
object contents to XML. For reading database data to an XML file to be sent to
a Web Service.
5.
What base class do all Web
Forms inherit from?
Answer:
The Page class.
6. Name two properties common
in every validation control?
Answer:
ControlToValidate and Text property.
7. What tags do you need to
add within the Data grid tags to bind columns manually?
Answer:
Set AutoGenerateColumns Property to false on the Data grid tag
8. What tag do you use to add
a hyperlink column to the Data Grid?
Answer:
asp: HyperLinkColumn
9. What is the transport
protocol you use to call a Web service?
Answer:
SOAP (Simple
Object Access Protocol) is the preferred protocol.
10. Where on the Internet
would you look for Web services?
Answer:
http://www.uddi.org
11. Which control would you
use if you needed to make sure the values in two different controls matched?
Answer:
CompareValidator Control
12. What are the assembly
entry points? An Assembly can have how many entry points at a time?
Answer:
An assembly can have only one entry point from DllMain, Win Main or Main.
13. What does an assembly
contain?
Answer:
•
Manifest – The metadata describing the information below.
•
Assembly name – Aids in versioning and visibility scope.
•
Version information – The version number is integrated into the assembly’s
identity.
•
Types – Boundaries and scopes of methods, classes, properties, events,
attributes.
•
Locale – Information describing language/culture.
•
Cryptographic Hash – Public key encoded hash acting as version/security check.
•
Security Permissions – The permissions within the assembly determine the
permissions that can be granted for all aspects of the assembly contents.
14. What does an assembly
manifest contains?
Answer:
It contains assembly name, version number (major.minor.build.revision) and
culture Information. It also specifies the strong name information, which is
useful for shared assemblies, and list of files, an assembly contains. It also
provides information for type references in an assembly and other referenced
assemblies.
15. which tool is used to
deploy an assembly, so as the assembly is available to all the application?
Answer:
The GacUtil.exe is the tool, which allows us to add any assembly to the windows
GAC.
16. How many catch statements
can be associated with single try statement?
Answer:
There can be a zero or more catch statement for each try statement. So it has
not limit to the number of catch statement per try statement.
17. What is Console and System
a Class/a Data Member/a routine/a namespace or a type?
Answer:
Console is a class and System is namespace.
18. How many values can be
returned from a method in C#?
Answer:
Only one value can be returned from method, however you can use ref or out variable to change more than one value in
called method.
19. How to declare a variable
named this in C#, with data type string?
Answer:
string @this;
20. Can we change the
dimension of Array at run time like Array [3, 4]?
Answer:
Yes, We can change only the first position of array dimension.
21. What keyword is used to
accept a variable number of parameter in a method?
Answer:
“params” keyword is used as to accept variable number of parameters.
22. What is a Namespace? What
is the use of a namespace?
Answer:
Namespaces are logical grouping of classes and other types in hierarchical
structure. Namespaces are useful to avoid collision or ambiguity among the
classes and type names. Another use of the namespace is to arrange a group of
classes for a specific purpose.
23. What does a keyword using
works for?
Answer:
Using is just a convention or a short-cut method which allows us to access the
classes in a namespace by referencing it once. So whenever we want use the
classes or methods in them, we can avoid typing the entire namespace hierarchy.
However it is not a good practice when there are likely chances to have name
ambiguity or collision of class names.
24. What is Enums
in C#?
Answer: Enums or Enumerators are used to declare a set of related
constants (default start with 0); they are only available with primitive data
types like int and short etc.
25. What is Delegates?
Answer: Delegates are a type-safe, object-oriented implementation of
function pointers and are used in many situations where a component needs to
call back to the component that is using it. Delegates are generally used as
basis of events, which allow any delegate to easily be registered for as event.
26. Which are the
namespaces that are imported automatically by Visual Studio in ASP.Net?
Answer:
There are 7 namespaces which are imported automatically.
1. System
2. System. Collections
3. System.IO
4. System.web
5. System.web.UI
6. System.web.UI.HTMLControls
7. System.web.UI.WebControls
27. Which namespaces are used
for data access?
1. System. Data
2. System.Data.OleDB
3. System.Data.SQLClient
28.
What do you mean by boxing and un-boxing?
Answer:
C# provides us with Value types and Reference Types. Value Types are stored on
the stack and Reference types are stored on the heap. The conversion of value type to reference
type is known as boxing and converting reference type back to the value type is known
as un-boxing.
e.g.
int
x = 10;
object
o = x ; // Implicit boxing
object
o = (object) x; // Explicit Boxing
x
= o; // Implicit Un-Boxing
x
= (int)o; // Explicit Un-Boxing
29. What are the different
methods available under sqlcommand class to access the data?
1. ExecuteReader –Used where one
or more records are returned – SELECT Query.
2. ExecuteNonQuery
–
Used where it affects a state of the table and no data is being queried –
INSERT, UPDATE, DELETE, CREATE and SET queries.
3. ExecuteScalar – Used where it
returns a single record(a single value normally) – SQL Functions like MIN(),
NAX()
30. What are the different
types of Session state management options available with ASP.NET?
Answer:
ASP.NET provides In-Process & Out-of-Process state management,
Also
known as “In-Proc” and “Out-Proc”. In-Proc stores the session in memory of the
web server, that is on the same server the ASP.Net page is.
On
the other hand Out-Proc session state management stores the session data on
external data source, which can be a SQL Server or Server State Service.
Out-of-Process state management requires the objects stored in session, must be
serializable.
31. What is Remoting? Give
Example.
Answer:
Remoting is a means by which one operating system process, or program, can
communicate with another process. The two processes can exist on the same
computer or on two computers connected by a LAN or the Internet. Web services
are probably the best known type of remoting, but they are not the only option.
32. What is Marshalling?
Answer:
Marshaling is a process of making an object in one process (the server)
available to another process (the client). There are two ways to achieve the
marshalling.
i. Marshal by value: the
server creates a copy of the object passes the copy to the client. When a
client makes a call to an object marshaled by value (MBV), the server creates
an exact copy and sends that copy to the client. The client can then use the
object’s data and executable functionality directly within its own process or
application domain without making additional calls to the server. Objects that
the application accesses frequently are best remoted using MBV.
ii. Marshal by reference: the
client creates a proxy for the object and then uses the proxy to access the
object. When a client makes a call to an object marshaled by reference (MBR),
the .NET framework creates a proxy in the client’s application domain and the
client uses that proxy to access the original object on the server. Large
objects that the application accesses relatively infrequently are good
candidates for MBR.
33. What is a Static class?
What are its features?
Answer:
Static class is a class which can be used or accessed without creating an
instance of the class.
Important
Features:
1. Static class only contains
static members and a private constructor.
2. Static class cannot be
instantiated.
3. Static classes are sealed by
default and therefore cannot be inherited.
34. What is sealed class?
What are its features?
Answer:
Sealed classes are those classes which can not be inherited and thus any sealed
class member can not be derived in any other class. A sealed class cannot also
be an abstract class.
In
C# structs are implicitly sealed; therefore, they cannot be inherited.
35. Can we declare a method
as sealed?
Answer:
In C# a method can’t be declared as sealed. However when we override a method
in a derived class, we can declare the overridden method as sealed. By
declaring it as sealed, we can avoid further overriding of this method.
E.g.
Using
System;
Class
MyClass1
{
Public
int x;
Public
int y;
Public
virtual void Method () {
Console.WriteLine
(“virtual method”) ;}
}
Class
My Class: MyClass1
{
Public
override sealed void Method () {
Console.WriteLine
(“sealed method”) ;}
}
Class
Main Class
{Public
static void Main () {
MyClass1
mC = new My Class ();
mC.x
= 110;
mC.y
= 150;
Console.WriteLine
(“x = {0}, y = {1}”, mC.x, mC.y);
mC.Method
() ;}
}
36. What is a Dataset?
Answer:
A Dataset is an in memory representation of data loaded from any data source.
37. What is a Data Table?
Answer:
A Data Table is a class in .NET Framework and in simple words a Data Table
object represents a table from a database.
38. If you want to view an
Assembly how to you go about it? What is ILDASM?
Answer:
You can use the MSIL Disassembler (Ildasm.exe) to view Microsoft intermediate
language (MSIL) information in a file. If the file being examined is an
assembly, this information can include the assembly’s attributes, as well as
references to other modules and assemblies. This information can be helpful in
determining whether a file is an assembly or part of an assembly, and whether
the file has references to other modules or assemblies.
39. Where is version
information stored of an assembly?
Answer:
The version number is stored in the assembly manifest along with other identity
information, including the assembly name and public key, as well as information
on relationships and identities of other assemblies connected with the
application.
40. Is versioning applicable
to private assemblies?
Answer:
No
41. How to create a shared
assembly or add an assembly to GAC?
Answer:
There are several ways an assembly can be added to GAC.
1. Use .msi installer designed
to work with the global assembly cache.
2. Use GACUtil.exe provided by
the .NET Framework SDK.
3. Use Windows Explorer to drag
assemblies into the cache.
43. What is reflection?
Answer:
All .NET compilers produce metadata about the types defined in the modules they
produce. This metadata is packaged along with the module (modules in turn are
packaged together in assemblies), and can be accessed by a mechanism called
reflection. The System. Reflection namespace contains classes that can be used
to interrogate the types for a module/assembly. Reflection is ability to find
information about types contained in an assembly at run time.
44. How can I produce an
assembly?
Answer:
Simply compile your class/module with the following command.
C#.Net
– CSC /t: library yourclassname.cs
VB.Net
– VBC /t: library yourmodulename.vb
45. What is an Application
Domain? How they get created?
Answer:
An Application Domain can be thought of as a lightweight processes controlled
by the .Net runtime. Application Domains are usually created by hosts like
Windows Shell, ASP.NET and IE. When you run a .NET application from the
command-line, the host is the Shell. The Shell creates a new Application Domain
for every application.
46. Do I have any control
over the garbage collection algorithm?
Answer:
Yes, we have a limited control over the GC algorithm, For example, the System.GC
class exposes a Collect method – this forces the garbage collector to collect
all unreferenced objects immediately.
47. What is a life
span of a static variable?
Answer: A
static variable’s life span is till the class is in memory.
48. What is a
Page Life Cycle of an ASP.Net page?
Answer: There
are various stages described as under.
1. Init
2. LoadViewState
3. LoadPostBackData
4. Load
5. RaisePostBackDataChangedEvent
6. RaisePostBackEvents
7. Pre-Render
8. SaveViewState
9. Render
10. Unload
49. Can the action attribute
of a server-side <form>tag be set to a value and if not how can you
possibly pass data from a form to a subsequent Page?
Answer:
No, Assigning value will not work because will be overwritten at the time of
rendering. We can assign value to it by register a startup script which will
set the action value of form on client-side. On other hand we can use
Server.Transfer or Response. Redirect.
50. How do you turn off
cookies in one page of your asp.net application?
Answer:
We may not use them at the max, However to allow the cookies or not, is client
side functionality.
51. Which method do you use
to redirect to user to another page without performing a round trip to Client?
Answer:
Server. Transfer (“AnotherPage.aspx”).
53. Should Validation occur
on Client/Server Side for Date Input?
Answer:
Both. Client-side reduces extra round-trip. Server-Side ensures prevention
against hacking and failure against automated requests.
54. What are the web form
events?
Answer:
1. The first event that occurs
in the life of a Web Form is the Init event. This is raised so that we can have
initialization code for the page. The controls on the page are not yet created
at this point. This event is raised once for each user of the page.
2. The Load event follows the
Init event. Subsequently, it is raised each time the page is requested. When
this event is raised, all child controls of the Web Form are loaded and
accessible. You should be able to retrieve data and populate the controls so
that they can render themselves on the page when sent back to the client.
3. The PreRender event happens
just before the page is rendered and sent back to the client. We don’t often
handle this event; however, it depends on the situation.
4. The last event in the life of
a Web Form is the Unload event. This happens when the page is unloaded from
memory. Final cleanup should be done here.
Difference between ASP.NET 3.5 and
ASP.NET 4.0
1.
Whether Client data can be directly accessed?
In ASP.NET 3.5, the data from the client
side cannot be directly accessed. The client side data can only be accessed using script manager’s Page methods,
Interface named ICallbackEventHandler or by using the component XMLHttpHandler.
2.
Whether we can set MetaTags (Keywords,Description) in the Page Directive?
In ASP.NET 3.5, two meta tags can be used,
one with name as keywords and other with name as description to record the
keywords and description for SEO purpose.
<Meta name="keywords" content="These, are,
my, keywords" />
<Meta name="description" content="This is
the description of my page" />
3.
Whether ViewState can be applied at the Control level?
ASP.NET 3.5 EnableViewState
property cannot be used to apply ViewState
at the Control level. It is mainly used at the page level. Its default
value is True and its acceptable values ae True and False.
4.
How ASP.NET 3.5 identifies ClientID?
In ASP.NET 3.5, ClientId property has to be
used to find the dynamically generated client id.
5. Whether
permanent redirection is possible or not ?
There is no RedirectPermanent() method
available in ASP.NET 3.5.
Redirect method is less useful than the
RedirectPermanent method. It will cause search engine results to be less
current, and this can also impact performance because visitors will not be
accessing the best URL. Redirect may be most useful for login pages or more
complex situations.
6.
Output Caching Enhancement:
OutPut Cache in ASP.Net 3.5 has a
limitation - generated content always has to be stored in memory, and on
servers that are experiencing heavy traffic, the memory consumed by output
caching can compete with memory demands from other portions of a Web application.
7.
QueryExtender Control for filtering the data returned by EntityDataSource and
LinqDataSource controls:
There is no QueryExtender control available in
ASP.NET 3.5 to filter the data returned by DataSource Controls(
EntityDataSource and LinqDataSource). It has to explicitly use 'Where clause'
in the data source.
ASP.NET 4.0:
1. Whether Client data can be
directly accessed?
In ASP.NET 4, the data from the client side
can be directly accessed using client data view and client data context objects.
Following methods are available in ASP.NET
4.0 to access Client data directly,
1) Client data controls
2) Client templates
3) Client data context
2.
Whether we can set MetaTags (Keywords, Description) in the Page Directive?
The meta keywords and meta
description is really useful for SEO
optimization of the web page. In
ASP.NET 4, the keywords and
description can be included as part of page
directive itself.
< %@ Page Language="C#"
CodeFile="Default.aspx.cs" Inherits="_Default"
Keywords="Keyword1,Key2,Key3,etc" Description="description" %>
3. Whether
ViewState can be applied at the Control level?
In ASP.NET 4, ViewState mechanism is
improved to set ViewState at the Contol level besides at the page level set by
EnableViewState property in ASP.NET 3.5 .Its default value is Inherit and
acceptable values are Enabled,Disabled and Inherit.
4.
How ASP.NET 4.0 identifies ClientID ?
In ASP.NET 4, a property called
ClientIDMode is newly introduced to
identify and record the ClientId easily.
ClientIDMode has following values.
AutoID
– Same as ASP.NET 3.5
Static – There won’t be any separate clientid generated at run time
Predictable-These are used particularly in datacontrols. Format is like
clientIDrowsuffix with the clientid vlaue
Inherit- This value specifies that a control’s ID generation is the same as
its parent.
The default value of ClientIDMode for a
page is Predictable. The default value of ClientIDMode for a control is
Inherit. Because the default for controls is Inherit, the default generation
mode is Predictable.
5.
Whether permanent redirection is possible or not ?
ASP.Net 4.0 introduced a new URL
redirection method RedirectPermanent() which avoids round trips.
We can implement this as shown below:
RedirectPermanent("/newpath/newpage.aspx");
RedirectPermanent returns a 301 HTTP
response—it redirects permanently to another location. Search engines such as
Google and Bing will change their indexes to point to the new page directly. To
call RedirectPermanent we will need to get the Response object from the HttpContext.
Then, we can call RedirectPermanent: if you
pass false as the second parameter, we can perform further actions and avoid an
exception.
6.
Output Caching Enhancement:
ASP.NET 4 adds an extensibility point to
output caching that enables you to configure one or more custom output-cache
providers. Output-cache providers can use any storage mechanism to persist HTML
content. This makes it possible to create custom output-cache providers for
diverse persistence mechanisms,
which can include local or remote disks, cloud storage, and
distributed cache engines.
In order to know how to implement Custom
Output Caching, please refer to the following URL,
http://www.technologymaterial.com/QAndAD...pe=aspnet4
7.
QueryExtender Control for filtering the data returned by EntityDataSource and
LinqDataSource controls:
QueryExtender Control is an add-on to the
DataSource Controls: EntityDataSource and LinqDataSource. QueryExtender is used
to filter the data returned by these controls. As the QueryExtender control relies
on LINQ, the filter is applied on the database server before the data is sent
to the page, which results in very efficient operations.
i.e., QueryExtender Control is intended to
be used to create filters for data that is retrieved from a data source,
without using an explicit Where clause in the data source. The control can be
used to filter data in the markup of a Web page by using declarative syntax.
<asp:LinqDataSource
ID="dataSource" runat="server"
TableName="Products">
</asp:LinqDataSource>
<asp:QueryExtender
TargetControlID="dataSource" runat="server">
<asp:SearchExpression
DataFields="ProductName, Supplier.CompanyName"
SearchType="StartsWith">
<asp:ControlParameter
ControlID="TextBoxSearch" />
</asp:SearchExpression>
</asp:QueryExtender>
50 Important
Silverlight Question/Answers
1. What is Microsoft Silverlight?
• Silverlight
is a web based technology, launched by Microsoft in April 2007. Silverlight is
considered as a competitor to Adobe's Flash.
• Silverlight
is Microsoft's implementation of a cross-browser, cross-platform client
framework that allows designers and developers to deliver Rich Internet
Applications (RIA) embedded in Web pages.
• Silverlight
is a browser plug-in approximately 6MB in size; it is client-side free
software, with an easy and fast (less than 10 sec) one time installation
available for any client side browser.
• It
supports advanced data integration, multithreading, HD video using IIS Smooth
Streaming, and built-in content protection. Silverlight enables online and
offline applications for a broad range of business and consumer scenarios.
• One
of the design goals of the Silverlight technology is to fill the gap between
Windows applications and Web applications in terms of creating Graphical User
Interfaces (GUI).
• Silverlight
applications are run as client-side applications without the need to refresh
the browser to update the UI. However, because of the built-in .NET framework,
Silverlight applications can easily integrate with server-side controls and
services. Using Silverlight's implementation of the .NET framework, developers
can easily integrate existing libraries and code into Silverlight applications.
2. Why use Silverlight?
• Support
for the .NET Framework – if you are already a .NET developer, it is easy to
start programming on Silverlight.
• Support
for managed code – you can write programs in your favorite language which .NET
CLR supports like C#, VB.NET, dynamic languages (IronPython, IronRuby).
• Better
development tools -Visual Studio 2010, Expression Blend.
• Large
community- More learning resources available compared to Flash.
• Integration
with Enterprise based technologies like WPF, LINQ etc…
• Silverlight
integrates the XAML declarative language with the .NET framework.
• It
is a cross-browser, cross-platform technology which provides a consistent user
experience everywhere it runs.
• The
Silverlight plug-in installs in seconds, and leaves a very small footprint.
• After
you install the plug-in, users no longer need to install anything on their
workstations to run Silverlight applications. The applications are available to
them from whatever browser they are accessing.
• It
runs a client-side application that can read data and update the UI without
interrupting the user by refreshing the whole page.
• It
can run asynchronous communications with the server, allowing the UI to
continue to function while waiting for the server response.
• It
delivers rich video, audio, and graphics.
3. Which platforms does Silverlight
support?
• Mac
OS
• Windows
Vista
• Windows
XP SP2
• Windows
2000
• Windows
Server 2003
• Linux
(Moonlight)
4. Which browsers does Silverlight support?
• Microsoft
- Internet Explorer 6, 7, 8
• Mozilla
- Firefox 2 and 3
• Apple
- Safari 3 and 4
• Google
- Chrome
5. What are the system requirements for
Silverlight?
The system requirements for Microsoft
Silverlight and associated technologies are listed below.
Windows
• Operating
System: Windows 7, Windows Vista, Windows XP Service Pack 2
• Intel®
Pentium® III 450MHz or faster processor (or equivalent)
• 128MB
of RAM
Mac OS
• Operating
System: Apple Mac OS X 10.4.8 or above
• Intel
Core™ Duo 1.83GHz or faster processor
• 128MB
of RAM
Linux
• Moonlight
6. What is Moonlight?
Moonlight is an Open Source implementation
of Silverlight, primarily for Linux and other Unix/X11 based Operating Systems.
In September of 2007, Microsoft and Novell announced a technical collaboration
that includes access to Microsoft's test suites for Silverlight and the
distribution of a Media Pack for Linux users that will contain licensed media
codecs for video and audio.
Moonlight 2 was released December 17, 2009
7. What are the goals of Moonlight?
• To
run Silverlight applications on Linux.
• To
provide a Linux SDK to build Silverlight applications.
• To
reuse the Silverlight engine built for desktop applications.
8. Is Silverlight free?
Yes, Microsoft has made the Silverlight
browser plug-in freely available for all supported platforms and browsers.
9. What is the difference between
Silverlight 1.0 and 2?
• Silverlight
1 is purely AJAX and JavaScript based. All the code has to be written in
JavaScript and XAML.
• Silverlight
2 supports managed code. When the Silverlight 2 runtime is installed, it
installs a limited version of the .NET runtime on the client machine. This
allows .NET programmers to write managed code to be executed on the client PC,
and provides a better user experience to users. Of course, there is security
restrictions built in to it so that the code has limited access to the client
computer.
• The
biggest change is the implementation of the .NET Framework. If you are familiar
with Silverlight 1.0, then you will be used to coding the application
functionality in JavaScript. You can still implement functionality using
JavaScript; however, you can now also implement functionality using C#, Visual
Basic, Python, Ruby, and managed JavaScript.
• Another
major change is the introduction of the XAP package. In Silverlight 1.0, the
XAML code was referenced directly by the Silverlight object embedded in the
browser. In Silverlight 2, however, the embedded object references an XAP
package that contains the XAP file, assemblies, and resources necessary to run
the Silverlight application.
10. What is the Silverlight plug-in?
• The
Silverlight plug-in is a very lightweight component that is necessary for users
to access Silverlight applications. The plug-in download and install takes only
a few moments, and do not take up much hard drive space.
• The
Silverlight plug-in is responsible for accessing the Silverlight object in the
Web page, downloading and accessing the XAP package, setting up the program
environment, and beginning execution of the application.
• When
a Web page containing a Silverlight application is displayed, the user should
be given a link to download the plug-in from Microsoft if the plug-in is not
already installed.
11. What is Silverlight Runtime?
Silverlight Runtime is a browser plug-in to
support Silverlight enabled applications. If the Silverlight runtime is not
installed, browsers will not be able to run Silverlight elements in the
browser. You can set up your Silverlight tags in such a way that your browser
will automatically prompt the user to download and install the Silverlight
plug-in when your application is launched in the browser.
Installing the run time is a onetime
operation on the client. Once installed, it will be automatically launched when
any Silverlight application is loaded in the browser.
Note: Silverlight plug-in and the runtime,
both are the same; however, I am giving two definitions here.
12. What is Silverlight SDK?
Silverlight SDK is a set of tools,
documentation, samples, and templates for web developers to enable them to
easily develop Silverlight enabled applications. The SDK is not really
mandatory to develop Silverlight applications; however, the SDK will make
development much easier.
13. What are the tools required to develop
Silverlight applications?
To run Silverlight applications in a web
browser, you need to have the Silverlight runtime installed on the client
browser as a plug-in. This is a light-weight version of the .NET runtime.
However, to develop a Silverlight
application, you need something more.
Silverlight SDK: This includes a set of
tools required to compile and build Silverlight controls.
If you are comfortable writing HTML using
Notepad and compiling .NET applications from console tools, then you just need
the Silverlight SDK to develop Silverlight applications.
However, most people use some kind of IDE
to develop applications faster.
Microsoft offers two separate tools to
develop Silverlight applications:
• Microsoft
Expression Studio - This tool is meant for web designers to create rich visual
elements for Silverlight applications. Expression Studio is recommended for web
designers who create rich internet applications with enhanced visual content
and graphics. There are several features provided for creating enhanced
graphics elements, with lot of options to pick color, font, etc.
• Microsoft
Visual Studio - This is the integrated development environment from Microsoft
to develop .NET applications. Programmers can use Visual Studio to develop
Silverlight applications which require programming. Visual Studio allows
programmers to develop sophisticated Silverlight applications in any .NET
language (like C#, VB.NET etc).
Here are some other tools that you can use:
• Install
Deep Zoom Composer - This tool allows you to prepare your images for use with
the Deep Zoom feature in Silverlight 3.
• Download
Silverlight Toolkit - This toolkit is a Microsoft project containing
Silverlight controls, components, and utilities that can be downloaded and used
in your Silverlight applications. It includes full source code, samples, and
tests.
• Download
.NET RIA Services - Microsoft .NET RIA Services simplifies the traditional
n-tier application pattern by bringing together the ASP.NET and Silverlight
platforms. RIA Services provides a pattern to write application logic that runs
on the mid-tier and controls access to data for queries, changes, and custom
operations.
14. Which tool to use - Expression Studio
or Visual Studio?
If your Silverlight application includes
just graphics and visual elements, then you can use Expression Studio. However,
if you are a programmer and if your Silverlight application includes
programming logic, then you might want to choose Visual Studio.
15. What are the Silverlight versions
available so far?
• Silverlight
1.0: Silverlight 1.0, which was developed under the codename Windows
Presentation Foundation/Everywhere (WPF/E), consists of the core presentation
framework which is responsible for the user interface (UI), interactivity, and
user input, basic UI controls, graphics and animation, media playback, Digital
Restrictions Management (DRM), and DOM integration
• Silverlight
2: Silverlight 2 (previously referred to as version 1.1) includes a version of
the .NET Framework, implementing the same full Common Language Runtime (CLR)
version as .NET Framework 3.0. The XAML markup as well as the code is compiled
into .NET assemblies which are then compressed using Zip and stored in a .xap
file.
• Silverlight
3: Silverlight version 3 was released in July 9, 2009, which is an extension to
Silverlight 2.0, and mainly provides improvements in graphics capabilities,
media management, application development areas (additional controls, enhanced
binding support, and out-of-browser functionality), and integration in the
designers' Expression Blend 3 tools.
• Silverlight
4: Silverlight version 4 was released on April 15, 2010 (along with Silverlight
4 tools for developers).
16. What is a .xap file?
A .xap file is a Silverlight-based
application package (.xap) that is generated when the Silverlight project is
built. A .xap file is the compressed output file for a Silverlight application.
The .xap file includes AppManifest.xaml, the compiled output assembly of the Silverlight
project (.dll), and the resource files referred to by the Silverlight
application:
• Web
pages like .aspx files and .html files use Silverlight components by loading
.xap files using the tag in HTML or by using the tag in ASP.NET pages.
• ".xap"
files (pronounced "zap") use the standard Zip compression algorithm
to minimize client download size. Rename this file to SilverlightTest.zip and
open it using any decompression tool. You can see that this is just like any
other zip file, and it includes the project's output DLL and another file
called "AppManifest.xaml".
17. How does XAP work?
Once you have created the .xap file , the
Silverlight 2 plug-in downloads the file and runs it in a separate work space.
18. How do I use a .xap file?
A .xap file is used to contain and transfer
the assemblies and resources of a managed code application. This managed code
application must be run within the Silverlight 2 browser plug-in.
19. Can we add a reference to a Class
Library project in a Silverlight application project?
No, you can't add a reference to a Class
Library project to a Silverlight application project. You can only add the
reference of another Silverlight application project inside a Silverlight
application project. However, you can add a reference to a Web Service or WCF
Service.
20. What is a Silverlight.js file?
Silverlight.js is a helper file which
enables websites to create advanced Silverlight installation and instantiation
experiences. You can call the createObject and createObjectEx functions defined
in this file to embed the Silverlight plug-in in a web page.
21. What is the use of the ClientBin
folder?
The ClientBin folder is used to place the
.xap file of a Silverlight application. You can keep it anywhere in your web
application, but this is the default location used by Silverlight.
22. How to change the default page of a
Silverlight application?
To change the default page of a Silverlight
application, you need to set the RootVisual property inside the
Application_Startup event of the App.xaml file. Collapse private void
Application_Startup(object sender, StartupEventArgs e) { this.RootVisual = new
MainPage(); }
23. What is XAML?
XAML stands for eXtended Application Markup
Language. XAML contains XML that is used to declaratively specify the user
interface for Silverlight or WPF applications. For example, if you need to
display a rectangle, this is the XAML you need to use.
XAML stands for eXtensible Application
Markup Language, and is a declarative markup language that follows the XML rule
and is used for developing User Interfaces in WPF and Silverlight technology.
XAML files are XML files that generally have the .xaml extension, and separates
the UI definition from the run-time logic by using code-behind files, joined to
the markup through partial class definitions. XAML has a set of rules that map
object elements into classes or structures, attributes into properties or
events, and XML namespaces to CLR namespaces. XAML elements map to Microsoft
.NET types as defined in referenced assemblies, and the attributes map to
members of those types.
24. What is the AppManifest.xml file?
First, let’s look at an example
AppManifest.xaml file: Collapse The first element in AppManifest.xaml is a
Deployment node. This node defines the application, and contains the child
AssemblyPart nodes. As you can see the AssemblyPart nodes define what
assemblies (DLLs) are contained within the .xap file, and give each of them a
name. Now, if you look back up to the top, you'll see the Deployment node has
the EntryPointAssembly and EntryPointType attributes. The EntryPointAssembly
attribute defines which assembly defined below (as a child AssemblyPart node)
is the main assembly (DLL) for the application. And, the EntryPointType
attribute specifies the class contained within the assembly (DLL), defined in
the EntryPointAssembly attribute, is the main class that will be instantiated
to start the application. The Deployment node also has a RuntimeVersion
attribute that defines the version of Silverlight the application is built for.
25. What files are contained within the .xap
file?
The .xap file contains an application
manifest (AppManifest.xaml) file and all the necessary DLLs that are required
by the application. The first DLL contained is the compiled version of your
application and has the same name of your application. In my test, I created an
application named "SilverlightApplication1", so the DLL is named
"SilverlightApplication1.dll". The rest of the DLLs are the
dependencies the application requires.
26. What is app.xaml?
App.xaml is a file used by Silverlight applications
to declare shared resources like brushes, various style objects, templates etc.
Also, the code-behind file of app.xaml.cs is used to handle global application
level events like Application_Startup, Application_Exit, and
Application_UnhandledException (similar to the Global.asax file for ASP.NET
applications). When Visual Studio creates the app.xaml file automatically, it
creates a few event handlers with some default code. You can change the code
appropriately. Collapse private void Application_Startup(object sender,
StartupEventArgs e) { } private void Application_Exit(object sender, EventArgs
e) { } private void Application_UnhandledException(object sender,
ApplicationUnhandledExceptionEventArgs e) { } For ASP.NET developers, the above
code will look familiar. This is similar to the application level event
handlers in Global.asax.
27. What is the Silverlight official name?
Silverlight was formerly code-named
"WPF/E".
28. What are the main features and benefits
of Silverlight?
• Compelling
cross-platform user experiences.
• Flexible
programming model with collaboration tools.
• High-quality
media, low-cost delivery.
• Connected
to data, servers, and services.
29. What is MainPage.xaml?
When you create a Silverlight project using
Visual Studio, it creates a default XAML file called "MainPage.xaml".
This is just a dummy start page created by Visual Studio, and it does not
contain any visible UI elements. The default contents of the MainPage.xaml file
looks like this: Collapse
30. Which language is Silverlight developed
in?
It was developed using a combination of C#
and C++.
31. Can I consume WCF and ASP.NET Web
Services in Silverlight?
Yes, you can.
32. What are Deep Zoom and Deep Zoom
Composer?
Deep Zoom provides the ability to
interactively view high-resolution images in Silverlight. You can zoom in and
out of images rapidly without affecting the performance of your application.
Deep Zoom provides smooth in-place zooming and panning. DeepZoom Composer
allows you to create high resolution image compositions which are built for
smooth zooming and panning. DeepZoom Composer is absolutely free, and is simple
to use - just loads in all your high resolution images and makes your composition
on screen. Deep Zoom Composer is a tool that allows preparing of images for use
with the Deep Zoom feature in Silverlight 3.
33. What is the difference between WPF and
Silverlight?
Silverlight and Windows Presentation
Foundation (WPF) are two different products from Microsoft, but have lot of
overlap. Silverlight is a subset of WPF in terms of features and functionality.
Silverlight is a Microsoft technology, competing with Adobe's Flash, and is
meant for developing rich browser based internet applications. WPF is a
Microsoft technology meant for developing enhanced graphics applications for
the desktop platform. In addition, WPF applications can be hosted on web
browsers which offer rich graphics features for web applications. Web Browser
Applications (WBA) developed on the WPF technology uses XAML to host user
interfaces for browser applications. XAML stands for eXtended Application
Markup Language, which is a new declarative programming model from Microsoft.
XAML files are hosted as discrete files in the Web server, but are downloaded
to the browsers and converted to a user interface by the .NET runtime in the
client browsers. WPF runs on the .NET runtime, and developers can take
advantage of the rich .NET Framework and WPF libraries to build really cool
Windows applications. WPF supports 3-D graphics, complex animations, hardware
acceleration etc. Silverlight uses a particular implementation of a XAML
parser, with that parser being part of the Silverlight core installation. In
some cases, the parsing behavior differs from the parsing behavior in Windows
Presentation Foundation (WPF), which also has a particular implementation. In
table format: Silverlight WPF
Definition Silverlight is Microsoft’s latest development platform for building
next-generation Web client applications. Windows
Presentation Foundation (WPF) is Microsoft’s latest development platform for
building next-generation Windows client applications. Subset of Silverlight is generally considered
to be a subset of WPF, and is a XAML-based technology that runs within the
sandbox of a browser plug-in. WPF
is generally considered to be a subset of .NET Framework, and is a XAML based
technology. GUI Silverlight will be used in the development of Rich Internet
Applications (RIA) for web client users. WPF
will be used in the development of Rich Windows Graphical User Interfaces (GUI)
for Windows client users. Support Cross
OS, cross browser, cross device. Windows
only. Software Required Silverlight
is the add-on mechanism available for most browsers; in order to run
Silverlight applications at client machines, we need to install Silverlight
software on the client machine once. WPF,
on the other hand, does not support any plug-in mechanism; instead, we need to
install a completed WPF client application in order to use the WPF application
at the client place. Framework support Silverlight
has a very small, its own rich base class library to make the plug-in as small
as possible. It is highly optimized for size, and is a small subset of the full
.NET Framework, to be embedded within an application. WPF, on the other hand, has full access to the main
.NET Framework and all its associated assemblies. Deployment Silverlight
applications are hosted within a web server and a web page. To minimize client
download size, Silverlight uses a XAP archive. A XAP archive is a
zip-compressed archive of the Silverlight application, plus a manifest file
describing the content. Visual Studio automatically generates the XAP archive
when using the Silverlight project template. WPF
applications can be deployed as standalone applications, ClickOnce
applications, or XAML browser applications.
34. What is the difference between
Silverlight and Flash?
Adobe Flash is the most popular competitor
to Silverlight, supporting browser plug-ins and enabling the execution of rich
content for the Web. Flash is not a new technology, and already has had a long
life span as compared to Silverlight. But it does not have a huge community as
expected; it may be because of the limited development tools which are not
known to most developers. Flash uses ActionScript as the programming language
and Flex as the programming environment, and most developers are far from these
technologies. For ASP.NET developers, to extend their websites using Flash content
is not so simple. They need to learn a development environment like
ActionScript and Flex. Apart from that, there is no way to generate Flash
content using server-side .NET code, which means it’s difficult to integrate
ASP.NET content and Flash content. Silverlight aims to give .NET developers a
better option for creating rich web content. Silverlight provides a browser
plug-in with many similar features to Flash, but one that’s designed from the
ground up for .NET. Silverlight natively supports the C# language, and uses a
range of .NET concepts. As a result, developers can write client-side code for
Silverlight in the same language they use for server-side code (such as C# and
VB), and use many of the same abstractions (including streams, controls, collections,
generics, and LINQ).
35. What is the difference between
Silverlight and ASP.NET AJAX?
Microsoft ASP.NET AJAX, a set of JavaScript
libraries built into ASP.NET 3.5, is available as a separate download for
ASP.NET 2.0. Being an integral part of ASP.NET 3.5 and the AJAX Controls
Toolkit for ASP.NET 3.5, now ASP.NET AJAX client-and server-side libraries are
more integrated with Visual Studio 2008. The client-side library allows you to
implement client-level processing such as processing and validating information
entered by the end user, refreshing a portion of the web page, and developing
rich, interactive user interfaces. You can also efficiently integrate the
client-side library components with the server-side ASP.NET controls library in
asynchronous mode. The key technology driver of ASP.NET AJAX is scripting. In
general, script-based web applications face several challenges due to different
browser settings (e.g., JavaScript is not enabled by default) on PCs and mobile
devices. As a result, scripting is often not always the best strategy for
enterprises to use to develop secure and scalable RIAs. ASP.NET AJAX supports
limited features of RIAs, and does not support effective multimedia
integration, managed code-behind integration, or metadata and information
management. Microsoft ASP.NET AJAX is a widely accepted model for building
RIAs, but it is very likely that, having Silverlight as an option, .NET
developers will migrate ASP.NET AJAX applications to Silverlight RIAs. Visit
http://www.asp.net/ajax/ if you want to learn more about Microsoft ASP.NET
AJAX.
36. What are the different Layout controls
available in Silverlight?
There are three different types of Layout
controls provided by Silverlight:
• Canvas
- Position child elements absolutely in x, y space.
• StackPanel
- Position child elements relative to one another in horizontal or vertical
stacks.
• Grid
- Position child elements in rows and columns. You have to add a layout panel
to every XAML page you create. All other UI elements must be added inside one
of the layout panels. Each page can have exactly one layout panel control.
37. Are XAML files compiled or built at
runtime?
XAML files are usually compiled rather than
parsed at runtime. But it also supports parsing during runtime. When we build a
XAML based project, you will see it creates a g.cs extension in the obi\Debug
folder. Therefore, for every XAML file, you will find a g.cs file. For
instance, a MainPage.XAML will have a MainPage.g.cs file in the obi\Debug
folder. In short, at run time, you actually do not see the XAML file. But if
you want to do runtime parsing of the XAML file, it also allows that to be
done.
38. What is the long-term goal or vision
for Silverlight?
• Microsoft
Silverlight is a cross-browser, cross-platform, and cross-device plug-in for
delivering the next generation of .NET based media experiences and rich
interactive applications for the Web.
• Silverlight
offers a flexible programming model that supports AJAX, VB, C#, IronPython, and
IronRuby, and integrates with existing Web applications.
• By
using Expression Studio and Visual Studio, designers and developers can
collaborate more effectively using the skills they have today to light up the
Web of tomorrow.
• By
leveraging Silverlight's support for .NET, High Definition video,
cost-effective advanced streaming, unparalleled high-resolution interactivity
with Deep Zoom technology, and controls, businesses can reach out to new
markets across the Web, desktop, and devices.
39. Do I need to have the .NET Framework
installed in order to use Silverlight?
The answer to this is no - a cross platform
version of the .NET Framework is included in the 6 MB Silverlight 4 download,
which means you do not need to have anything extra installed on the client in
order to access Silverlight applications in the browser. The Silverlight
version of the .NET framework includes the same CLR engine (same GC, type-system,
JIT engine) that ships with the full .NET Framework, and a subset of the .NET
Framework namespace libraries. You can see the full list of all
classes/namespaces that are included by opening up the Object Browser when you
create a new Silverlight application using Visual Studio.
40. What are the other RIA technologies
besides Silverlight?
Adobe Flex, Java FX, Adobe Flash are some
of the other RIA technologies besides Silverlight.
41. What is meant by RIA?
RIA stands for Rich Internet Applications, which
are Web applications with rich user interfaces including media elements such as
audio, video etc. You can think of them as being similar to powerful and rich
desktop applications, except that RIA applications are Web based.
42. What is .NET RIA Services?
Microsoft .NET RIA Services helps to
simplify the n-tier application pattern by combining the ASP.NET and
Silverlight platforms. RIA Services provides a pattern using which you can
write application logic that can run on the mid-tier and controls access to
data for queries, changes, and custom operations. It also provides support for
data validation, authentication, and roles by integrating with Silverlight
components on the client and ASP.NET on the middle tier.
43. What are the design files and the
code-behind files in Silverlight?
The user interface elements of Silverlight
applications are defined in XAML files. The logic and functionality of
Silverlight applications is implemented using managed NET code-behind files
that share the same class with the XAML file.
44. Who is using Silverlight?
Yahoo! Japan, NBC, Continental Airlines,
NASA, Indian Premier League, and National Instruments are some of the
organizations currently using Silverlight to enhance their businesses.
45. What features are missing from
Silverlight presentation markup that will be supported in WPF?
Some high-end Windows specific features of
WPF, such as real 3D, hardware-based video acceleration, and full document
support, will not be supported in Silverlight. This is by design in order to
serve Silverlight’s cross-browser, cross-platform reach scenario that demands a
light weight plug-in. That being said, Silverlight will offer a uniform runtime
that can render identical experiences across browsers on both Mac OS and Windows.
46. Will I need more memory, a faster
processor, or a better Graphics Processing Unit (GPU)?
Microsoft designed Silverlight with the
ability to deliver high-fidelity experiences on the broadest set of system
configurations. Some features, such as HD video, may benefit from the power
contained in newer personal computers.
47. How does Silverlight make the Microsoft
development system better?
Silverlight is a cross-browser,
cross-platform plug-in for delivering the next generation of media experiences
and rich interactive applications (RIAs) for the Web. Examples include:
• For
ASP.NET-based Web applications, Silverlight provides a rich UI front-end that,
with a consistent programming model, adds support for richer interactivity,
media, and audio.
• For
Microsoft SharePoint–based content, Silverlight offers the ability to create
rich Web Parts.
• For
Windows Live services, Silverlight offers the ability to consume services and
APIs more effectively.
48. What is the relationship and difference
between Silverlight and ASP.NET?
Technically, Silverlight and ASP.NET are
completely different. The major differences are listed below:
• Silverlight
runs completely on the client, while ASP.NET mainly runs on the server, but
also has a few parts running on the client.
• When
an event fires, Silverlight handles the event on the client, but in ASP.NET, the
browser will make an HTTP POST to the server, and after the server handles the
request, it sends a new HTML page to the client.
• A
Silverlight application sends rendering commands to the Silverlight rendering
engine by either writing XAML or code, and the Silverlight rendering engine
will handle the rendering task. On the other hand, ASP.NET doesn’t have a
rendering engine. It generates an HTML file on the server, sends it to the
client, and allows the browser to parse the HTML file and render the content.
• Silverlight
can’t work with a database directly; instead, it consumes data from Web
Services, while ASP.NET has strong support for working with databases directly.
The most important thing to note is what runs on the client and what runs on
the server, since this will affect almost every part of your system.
Silverlight runs on the client, and ASP.NET runs on the server. They can work
together and are compatible with each other, but this requires some time and
effort.
49. When to use Silverlight, ASP.NET, or
both?
This depends on different scenarios. Below
are some common approaches:
• Pure
Silverlight One approach is to completely remove ASP.NET. This solution works
best if you’re working on a new development. You only need to work on
Silverlight, without any worry about integration problems. If you need to
communicate with the server, you write Web Services, such as WCF. It will also
help you when you need to port part or whole of your system to another hosting
or even another platform, since the client and the server are completely
separate.
• Major
ASP.NET, plus a Silverlight island This approach is generally used when the
Silverlight content and the ASP.NET content have little relationship. For
example, an ASP.NET blog engine with a Silverlight media player in a blog post.
This approach is very easy to implement, and allows you to reach the broadest
audience. For example, if a user hasn’t installed Silverlight, he can still
read the blog posts, but he can’t watch the videos.
• Use
ASP.NET AJAX instead of Silverlight ASP.NET AJAX is designed to work with
ASP.NET. It is mainly an extension to ASP.NET. While AJAX can’t provide you the
advanced user experience that Silverlight can, for many scenarios, it should be
sufficient. This approach also helps if you have strong ASP.NET experience, but
are still quite new to Silverlight. Within this approach, there are two
branches. One is to mix the client and server code by using the UpdatePanel,
AJAX Control Toolkit, and etc. The other method is to take the pure AJAX
approach, where you write HTML and JavaScript instead of using server controls,
and call Web Services to communicate with the server. The former branch is
easier to implement, especially if you have strong ASP.NET experience but lack
JavaScript knowledge. The latter branch proves to be better in an architecture
when you want to port an AJAX application to other technologies such as
Silverlight, especially since you only need to rewrite the client side code,
and can keep the Web Services as they are. The programming model for the latter
branch is similar to Silverlight. Therefore, this approach is rarely taken if
you’re experienced in Silverlight.
• Mix
Silverlight with ASP.NET More often, you may want to port an existing ASP.NET
application to Silverlight, but you don’t want to completely rewrite the entire
application. This is the most difficult approach since you’re mixing client
side and server side technologies. Before going with this approach, please
consider if the above approaches can solve your problem.
Ask yourself the following questions:
1. Do
you really need a rich interactive user experience? This is normally a
requirement for consumer oriented applications, but for most business
applications, you only need a “good” user experience, which AJAX is sufficient
to provide.
2. Can
you add Silverlight islands to your existing ASP.NET application instead of
mixing the contents? This should work for most scenarios. For example, Windows
Live Mail is built in ASP.NET, with a few Silverlight islands, such as a
slideshow program that allows you to view photo attachments with enhanced
experience (actually, most Microsoft created web applications take this
approach).
3. Will
this be a good chance to revise your architecture? Most traditional ASP.NET
applications use the B/S or three tire architecture in which the application
works with a database either directly or through a business logic layer. When
porting applications to other platforms, these architectures will introduce
many problems. When investigating Silverlight, it is also a good chance to
adopt SOA. Add a service facade layer on top of the business logic layer, and
you can work with the services from almost any client, such as an ASP.NET
application and a Silverlight application. If you are already on SOA, it should
be trivial to port to Silverlight, since you only need to rewrite a client
application. With SOA, the ASP.NET AJAX approach and the Silverlight island
approach will also be much easier to implement. If none of the above approaches
is suitable, you may have to mix Silverlight content with ASP.NET. When using
this approach, keep in mind that Silverlight can’t call ASP.NET server-side
event handlers, and each post back (either partial or complete) will cause the
Silverlight application to reload.
50. What are the new features of
Silverlight 4?
• Support
for Google's Chrome browser.
• Web
cam and microphone support.
• Printing
support.
• Full
keyboard access while running in full-screen mode.
• Programmatic
access to a user's local document folder.
• Improved
mouse support, including right button support and mouse wheel support.
• Elevated
trust and support for local Component Object Model (COM) objects.
• New
notification support to display messages to end users.
• New
and enhanced controls such as a RichTextBox and an enhanced DataGrid control.
• New
support for implicit theming of controls.
• New
hosted browser support for rendering HTML inside Silverlight.
• WCF
data layer enhancements.
• Localization
enhancements with bi-directional text.
• Support
for Managed Extensibility Framework.
• Enhanced
data binding support.
• Enhanced
animation effects.
• Clipboard
and drag and drop support.
• Deep
Zoom performance enhancements.
• WCF
Rich Internet Application (RIA) Services.
• Content
protection for H.264, and support for playing offline DRM protected media.
ASP.NET interview Question
1.Describe
the role of inetinfo.exe, aspnet_isapi.dll and aspnet_wp.exe in the page
loading process.
inetinfo.exe is the Microsoft IIS server running, handling ASP.NET requests
among other things. When an ASP.NET request is received (usually a file with
.aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing
the request to the actual worker process aspnet_wp.exe.
2.What’s
the difference between Response.Write() and Response.Output.Write()?
The latter one allows you to write
formatted output.
3.
What methods are fired during the page load?
Init() - when the page is instantiated,
Load() - when the page is loaded into server memory,
PreRender() - the brief moment before the page is displayed to the user as
HTML,
Unload() - when page finishes loading.
4. Where
does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page
5. Where
do you store the information about the user’s locale?
System.Web.UI.Page.Culture
6.What’s
the difference between Codebehind="MyCode.aspx.cs" and
Src="MyCode.aspx.cs"? CodeBehind is
relevant to Visual Studio.NET only.
7.What’s
a bubbled event?
When you have a complex control, like
DataGrid, writing an event processing routine for each object (cell, button,
row, etc.) is quite tedious. The controls can bubble up their event handlers,
allowing the main DataGrid event handler to take care of its constituents.
8.
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 inside that property. So btnSubmit.Attributes.Add("onMouseOver","someClientCode();")
9.
What data type does the RangeValidator control support?
Integer, String and Date.
10. Explain
the differences between Server-side and Client-side code?
Server-side code runs on the server.
Client-side code runs in the clients’ browser.
11. What
type of code (server or client) is found in a Code-Behind class?
Server-side code.
12. Should
validation (did the user enter a real date) occur server-side or client-side?
Why?
Client-side. This reduces an additional request
to the server to validate the users input.
13. What
does the "EnableViewState" property do? Why would I want it on or
off?
It enables the viewstate on the page. It
allows the page to save the users input on a form.
14. What is the difference between Server.Transfer and
Response.Redirect? Why would I choose one over the other?
Server.Transfer
is used to post a form to another page. Response.Redirect
is used to redirect the user to another page or site.
15. Can
you explain the difference between an ADO.NET Dataset and an ADO Recordset?
•A DataSet can represent an entire
relational database in memory, complete with tables, relations, and views.
•A DataSet is designed to work without any
continuing connection to the original data source.
•Data in a DataSet is bulk-loaded, rather
than being loaded on demand.
•There's no concept of cursor types in a
DataSet.
•DataSets have no current record pointer
You can use For Each loops to move through the data.
•You can store many edits in a DataSet, and
write them to the original data source in a single operation.
•Though the DataSet is universal, other
objects in ADO.NET come in different versions for different data sources.
16. Can
you give an example of what might be best suited to place in the
Application_Start and Session_Start subroutines?
This is where you can set the specific
variables for the Application and Session objects.
17. If
I’m developing an application that must accommodate multiple security levels
though secure login and my ASP.NET web application is spanned across three
web-servers (using round-robin load balancing) what would be the best approach
to maintain login-in state for the users?
Maintain the login state security through a
database.
18. Can
you explain what inheritance is and an example of when you might use it?
When you want to inherit (use the
functionality of) another class. Base Class Employee. A Manager class could be
derived from the Employee base class.
19. Whats
an assembly?
Assemblies are the building blocks of the
.NET framework. Overview of assemblies from MSDN
20. Describe
the difference between inline and code behind.
Inline code written along side the html in
a page. Code-behind is code written in a separate file and referenced by the
.aspx page.
21.Explain
what a diffgram is, and a good use for one?
The DiffGram is one of the two XML formats
that you can use to render DataSet object contents to XML. For reading database
data to an XML file to be sent to a Web Service.
22. Whats
MSIL, and why should my developers need an appreciation of it if at all?
MSIL is the Microsoft Intermediate
Language. All .NET compatible languages will get converted to MSIL.
23. Which
method do you invoke on the DataAdapter control to load your generated dataset
with data?
The .Fill() method
24. Can
you edit data in the Repeater control?
No, it just reads the information from its
data source
25. Which
template must you provide, in order to display data in a Repeater control?
ItemTemplate
26. How
can you provide an alternating color scheme in a Repeater control?
Use the AlternatingItemTemplate
27. What
property must you set, and what method must you call in your code, in order to
bind the data from some data source to the Repeater control?
You must set the DataSource property and
call the DataBind method.
28. What
base class do all Web Forms inherit from?
The Page class.
29. Name
two properties common in every validation control?
ControlToValidate property and Text
property.
30. What
tags do you need to add within the asp:datagrid tags to bind columns manually?
Set AutoGenerateColumns Property to false
on the datagrid tag
31. What
tag do you use to add a hyperlink column to the DataGrid?
<asp:HyperLinkColumn>
32. What
is the transport protocol you use to call a Web service?
SOAP is the preferred protocol.
33. True
or False: A Web service can only be written in .NET?
False
34. What
does WSDL stand for?
(Web Services Description Language)
35. Where
on the Internet would you look for Web services?
(http://www.uddi.org)
36. Which
property on a Combo Box do you set with a column name, prior to setting the
DataSource, to display data in the combo box?
DataTextField property
37. Which
control would you use if you needed to make sure the values in two different
controls matched?
CompareValidator Control
38. True
or False: To test a Web service you must create a windows application or Web
application to consume this service?
False, the webservice comes with a test
page and it provides HTTP-GET method to test.
39. How
many classes can a single .NET DLL contain?
It can contain many classes.
Life
cycle of an ASP .NET page.
Stage Events/Method
Page Initialization Page_Init
View State Loading LoadViewState
Postback data processin LoadPostData
Page Loading Page_Load
PostBack Change Notification RaisePostDataChangedEvent
PostBack Event Handling RaisePostBackEvent
Page Pre Rendering Phase Page_PreRender
View State Saving SaveViewState
Page Rendering Page_Render
Page Unloading Page_UnLoad
1)
Explain the .NET architecture.
a) All .Net
supported Languages
b) Common
Language specification
c) Windows forms
/ web pages
d) ADO.Net / web
services
e) Base class
library
f) Common
language runtime
g) Operating
system.
2) How does u create multiple inheritances
in c# and .net?
Multiple inheritances are created by using
interfaces.
3)
When web.config is called?
Web.config is an xml configuration file. this
never gets called directly unless we need to retrieve the configuration
setting.
4)
How many web.configs a application can have
one.
5)
How does u set language in web.config
a) Set the ‘defaultlanguage’ attribute.
6)
What does connection string consists of
a) connection string consist of : server
name, userid , password , database name.
7)
Where do u store connection string
a) connection string can stored in
web.config file under configuration / connection string tab.
8) What is abstract
class?
Abstract class is a
class which cannot be instantiated but inherited by derived classes. This class
contains abstract as well as non-abstract methods and members.
9)
What is diff b/w interface inheritance and class inheritance
A class can have multiple interface inheritance,
but only one.
In
interface inheritance: Inherited class must
implement all the methods define in that interface.
Class
inheritance: inherited class may or may not
implement all methods of that base class.
10)
What are the collection classes?
1) Array list 2) Hash table 3) stack
4) Dictionary 5) Queue
11)
What inheritance support vb.net?
a) Single class inheritance and multiple
interface inheritance.
12)
What is runtime host?
a) Runtime host is local environment where
CLR is running.
13)
OOPS CONCEPTS
1)
Encapsulation : Hiding internal implementation of
the objects and provide global interface access to object.
2)
Inheritance : The ability of a class to reuse the
members and member functions of its base class.
3)
Polymorphism : The ability of the objects to be
represented in multiple forms. This is possible with overriding and
overloading.
4)
Abstraction : Describing an object with its unique
and relevant characteristics according to specific need.
Object-Oriented concepts?
Class: The formal definition of an object. The class acts as the template
from which an instance of an object is created at run time. The class defines
the properties of the object and the methods used to control the object’s
behaviour.
Object: An object is an instance of a class.
Encapsulation: hides detailed internal specification of an object, and publishes
only its external interfaces. Thus, users of an object only need to adhere to
these interfaces. By encapsulation, the internal data and methods of an object
can be changed without changing the way of how to use the object.
Inheritance: A class that derives from another class - known as the base class
- inherits the same methods and properties. This promotes reuse and
maintainability.
Abstraction: the describing of objects by defining their unique and relevant
characteristics (properties). Whilst an object may have 100s of properties
normally only those properties of importance to the situation are described.
(eg life policies premiums are normally important; whereas the time of day a
policy was purchased is not usually of value).
Polymorphism: Allows objects to be represented in multiple forms. Even though
classes are derived or inherited from the same parent class, each derived class
will have its own behavior. (Overriding and hiding methods)
14)
optimization technique description
1) Avoid unnecessary use of view state
which lowers the performance.
2) Avoid the round trips to server.
3) Use connection pooling.
4) Use stored procedures.
15)
Diff b/w application and session
a) Application object maintains state on
application basis whereas session object maintain the state of the client
visited to the application.
16) What is web
application virtual directory?
a) Virtual directory is a physical location
where actually application folder is situated.
17)
Diff b/w Active.exe and Dll
1) Exe has an entry point.
2) If Dll is getting destroyed, exe also
destroyed.
18) If cookies are disabled
in client browser will session work
a) No. Identities of client gets destroy.
19)
The following code executes successfully
Response. Write (“value of i=â€+i) ;
a) Yes.
20)
What are a Process, Session and Cookie?
1) Process
: Is a running thread of application.
2) Session
: state used to maintain user state in application.
3) cookie
: used to store user identification data on client machine.
21)
How is Polymorphism supports in .net?
Polymorphism supports to objects to be
represent in different forms.
22)
What r the 2 types of polymorphism support in .net?
Overriding and overloading
23) ASP.NET OBJECTS?
Request, Response, Server,
Session, application,
24)
What is side by side execution?
Asynchronous execution in which application
keeps on running instead of waiting for the result of previous stage execution.
25) What serialization?
Serialization is a process of conversion an
objects into stream of bytes so that they can transfer through the channels.
26)
About a class access specifiers and method access specifiers
1) Public : available throughout
application.
2) Private : available for class and its
inherited class.
3) Protected : restricted to that class
only.
4) Internal : available throughout that
assembly.
27)
What diff b/w overloading and overriding? How can this be .net
Overriding : derived classes follow the same base class method signatures.
Overloading : Derived classes may have different method signature with
different parameters.
28)
About virtual function and its use
Virtual function is that which is get
override by the derived class to implement polymorphism.
How
do u implement inheritance in .net?
In c# : we use :
29) if
I want to override a method 1 of class A and this class B then how do u
declared
answer
:
public virtual void method1(){ } ..In class
A. public override void method1(){}…………..In class B.
30)
About friend and protected friend
Friend
/ internal : provides access throughout that
particular assembly.
Protected
friend : provides access for that particular class
and to its child classes.
31) About multiple and multilevel
Inheritance how to achieve in .net?
Multiple
Inheritance: ex. Public void Employee : Persons,
Iemployee. Means a class can be inherited by more than one interface OR
inherited by one class and more than one interfaces.
Multi
level inheritance: ex. Public void Person () {},
Public void Customer : person {} , Public void employee : customer{}.
32) What is isPostback
property?
Is postback is a property of page to check
weather the page is loaded first time or in response to the client callback.
1 :: What is view state and use of it?
The current property settings of an ASP.NET page and those of any ASP.NET server controls contained within the page. ASP.NET can detect when a form is requested for the first time versus when the form is posted (sent to the server), which allows you to program accordingly.
2 :: What are user controls and custom controls?
Custom controls:
A control authored by a user or a third-party software vendor that does not belong to the .NET Framework class library. This is a generic term that includes user controls. A custom server control is used in Web Forms (ASP.NET pages). A custom client control is used in Windows Forms applications.
User Controls:
In ASP.NET: A user-authored server control that enables an ASP.NET page to be re-used as a server control. An ASP.NET user control is authored declaratively and persisted as a text file with an .ascx extension. The ASP.NET page framework compiles a user control on the fly to a class that derives from the System.Web.UI.UserControl class.
3 :: What are the validation controls?
A set of server controls included with ASP.NET that test user input in HTML and Web server controls for programmer-defined requirements. Validation controls perform input checking in server code. If the user is working with a browser that supports DHTML, the validation controls can also perform validation using client script.
4 :: What is the difference between Response.Write() and Response.Output.Write()?
The latter one allows you to write formatted output.
5 :: What methods are fired during the page load?
The current property settings of an ASP.NET page and those of any ASP.NET server controls contained within the page. ASP.NET can detect when a form is requested for the first time versus when the form is posted (sent to the server), which allows you to program accordingly.
2 :: What are user controls and custom controls?
Custom controls:
A control authored by a user or a third-party software vendor that does not belong to the .NET Framework class library. This is a generic term that includes user controls. A custom server control is used in Web Forms (ASP.NET pages). A custom client control is used in Windows Forms applications.
User Controls:
In ASP.NET: A user-authored server control that enables an ASP.NET page to be re-used as a server control. An ASP.NET user control is authored declaratively and persisted as a text file with an .ascx extension. The ASP.NET page framework compiles a user control on the fly to a class that derives from the System.Web.UI.UserControl class.
3 :: What are the validation controls?
A set of server controls included with ASP.NET that test user input in HTML and Web server controls for programmer-defined requirements. Validation controls perform input checking in server code. If the user is working with a browser that supports DHTML, the validation controls can also perform validation using client script.
4 :: What is the difference between Response.Write() and Response.Output.Write()?
The latter one allows you to write formatted output.
5 :: What methods are fired during the page load?
Init() When
the page is instantiated,
Load()
- when the page is loaded into server memory,
PreRender
() - the brief moment before the page is displayed to the
user as HTML,
Unload()
- when page finishes loading.
6 :: Where does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page
7 :: What is the difference between Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"?
CodeBehind is relevant to Visual Studio.NET only.
8 :: What is a bubbled event?
When you have a complex control, likeDataGrid, writing an event processing routine for each object (cell, button,row, etc.) is quite tedious. The controls can bubble up their eventhandlers, 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.
9 :: What data type does the RangeValidator control support?
Integer,String and Date.
10 :: What are the different types of caching?
Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In context of web application, caching is used to retain the pages or data across HTTP requests and reuse them without the expense of recreating them.ASP.NET has 3 kinds of caching strategiesOutput, CachingFragment, 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 whole 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;
11 :: 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.
12 :: What are different types of directives in .NET?
6 :: Where does the Web page belong in the .NET Framework class hierarchy?
System.Web.UI.Page
7 :: What is the difference between Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"?
CodeBehind is relevant to Visual Studio.NET only.
8 :: What is a bubbled event?
When you have a complex control, likeDataGrid, writing an event processing routine for each object (cell, button,row, etc.) is quite tedious. The controls can bubble up their eventhandlers, 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.
9 :: What data type does the RangeValidator control support?
Integer,String and Date.
10 :: What are the different types of caching?
Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In context of web application, caching is used to retain the pages or data across HTTP requests and reuse them without the expense of recreating them.ASP.NET has 3 kinds of caching strategiesOutput, CachingFragment, 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 whole 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;
11 :: 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.
12 :: What are different 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" 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" %>
13 :: Can a user browsing my Web site read my Web.config or Global.asax files?
No. The 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 an section in a local Web.config file.
14 :: How do I debug an ASP.NET application that was not written with Visual Studio.NET and that does not 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,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 tell ASP.NET to build debug executables by placing a
<%@ Page Debug="true" %> statement at the top of an ASPX file or a statement in a Web.config file.
15 :: What is 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-script not packaged in functions-in other words, code that's to execute when the page is loaded. The latter positions script blocks near the end of the document so elements on the page that the script interacts are loaded before the script runs.<%@ Reference Control="MyControl.ascx" %>
16 :: Is it necessary to lock application state before accessing it?
Only if you're performing a multistep update and want the update to be treated as an atomic operation. Here's an example:
@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" %>
13 :: Can a user browsing my Web site read my Web.config or Global.asax files?
No. The 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 an section in a local Web.config file.
14 :: How do I debug an ASP.NET application that was not written with Visual Studio.NET and that does not 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,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 tell ASP.NET to build debug executables by placing a
<%@ Page Debug="true" %> statement at the top of an ASPX file or a statement in a Web.config file.
15 :: What is 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-script not packaged in functions-in other words, code that's to execute when the page is loaded. The latter positions script blocks near the end of the document so elements on the page that the script interacts are loaded before the script runs.<%@ Reference Control="MyControl.ascx" %>
16 :: Is it necessary to lock application state before accessing it?
Only if you're performing a multistep update and want the update to be treated as an atomic operation. Here's an example:
Code:
Application.Lock ();
Application["ItemsSold"] = (int) Application["ItemsSold"] + 1;
Application["ItemsLeft"] = (int) Application["ItemsLeft"] - 1;
Application.UnLock ();
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, 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, 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.
17 :: How do I send e-mail from an ASP.NET application?
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, 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.
17 :: How do I send e-mail from an ASP.NET application?
Code:
MailMessage message = new MailMessage ();
message.From = ;
message.To = ;
message.Subject = "Scheduled Power Outage";
message.Body = "Our servers will be down tonight.";
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send (message);
message.From = ;
message.To = ;
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.
18 :: 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 elements:
xmlns="urn:schemas-dynamicdiscovery:disco.2009-03-17">
19 :: 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 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.
20 :: 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:
Code:
<%@ Page Language="C#" %>
<%
Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
%>
<%
Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
%>
SetNoStore works by returning a Cache-Control: private, no-store header in the HTTP response. In this example, it prevents caching of a Web page that shows the current time.
21 :: 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 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" %>
22 :: Should validation (did the user enter a real date) occur server-side 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.
23 :: 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 give 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, e.g. HTML. If you use Microsoft Visual Studio .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application.
24 :: 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, 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 additional headaches. 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.
25 :: How can you provide an alternating color scheme in a Repeater control?
AlternatingItemTemplate Like the ItemTemplate element, but rendered for every other row (alternating items) in the Repeater control. You can specify a different appearance for the AlternatingItemTemplate element by setting its style properties.
26 :: Which template must you provide, in order to display data in a Repeater control?
ItemTemplate
27 :: What event handlers can I include in Global.asax?
Application_Start,Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed, Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute,
Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache, Session_Start,Session_End
You can optionally include "On" in any of method names. For example, you can name a BeginRequest event handler.Application_BeginRequest or Application_OnBeginRequest.You can also include event handlers in Global.asax for events fired by custom HTTP modules.Note that not all of the event handlers make sense for Web Services (they're designed for ASP.NET applications in general, whereas .NET XML Web Services are specialized instances of an ASP.NET app). For example, the Application_AuthenticateRequest and Application_AuthorizeRequest events are designed to be used with ASP.NET Forms authentication.
C
Sharp Interview Questions/Answers Part-1
What are the new features introduced in c#
4.0?
This question is basically asked to check,
if you are passionate about catching up with latest technological advancements.
The list below shows a few of the new features introduced in c# 4.0. If you are
aware of any other new features, please submit those using the from at the end
of this post.
1. Optional and Named Parameters
2. COM Interoperability Enhancements
3. Covariance and Contra-variance
4. Dynamic Type Introduction
What's the difference between
IEnumerable<T> and List<T> ?
1. IEnumerable is an interface, where as
List is one specific implementation of IEnumerable. List is a class.
2. FOR-EACH loop is the only possible way
to iterate through a collection of IEnumerable, where as List can be iterated
using several ways. List can also be indexed by an int index, element can be
added to and removed from and have items inserted at a particular index.
3. IEnumerable doesn't allow random access,
where as List does allow random access using integral index.
4. In general from a performance
standpoint, iterating thru IEnumerable is much faster than iterating thru a
List.
What
are the difference between interfaces and abstract classes?
1. Abstract classes can have
implementations for some of its members, but the interface can't have
implementation for any of its members.
2. Interfaces cannot have fields where as
an abstract class can have fields.
3. An interface can inherit from another
interface only and cannot inherit from an abstract class, where as an abstract
class can inherit from another abstract class or another interface.
4. A class can inherit from multiple
interfaces at the same time, where as a class cannot inherit from multiple
classes at the same time.
5. Abstract class members can have access
modifiers where as interface members cannot have access modifiers.
What
is a delegate?
A delegate is a type safe function pointer.
Using delegates you can pass methods as parameters. To pass a method as a
parameter, to a delegate, the signature of the method must match the signature
of the delegate. This is why, delegates are called type safe function pointers.
What
is the main use of delegates in C#?
Delegates are mainly used to define call back methods.
What
do you mean by chaining delegates? Or What is a multicast delegate?
The capability of calling multiple methods
on a single event is called as chaining delegates. Let me give you an example
to understand this further.
1. Create a new asp.net web application
2. Drag and drop a button control and leave
the ID as Button1.
3. On the code behind file, add the code
shown below.
[Image: Delegates.png]
When you click the Button now, both Method1
and Method2 will be executed. So, this capability of calling multiple methods
on a single event is called as chaining delegates. In the example, we are using
EventHandler delegate, to hook up Method1 and Method2 to the click event of the
button control. Since, the EventHandler delegate is now pointing to multiple
methods, it is also called as multicast delegate.
What
are the advantages of using interfaces?
Interfaces are very powerful. If properly
used, interfaces provide all the advantages as listed below.
1. Interfaces allow us to implement
polymorphic behaviour. Ofcourse, abstract classes can also be used to implement
polymorphic behaviour.
2. Interfaces allow us to develop very
loosely coupled systems.
3. Interfaces enable mocking for better unit
testing.
4. Interfaces enables us to implement
multiple class inheritance in C#.
5. Interfaces are great for implementing
Inverson of Control or Dependancy Injection.
6. Interfaces enable parallel application
development.
What
are the advantages and disadvantages of using arrays?
Advantages
of using arrays:
1. Arrays are strongly typed, meaning you
can only have one type of elements in the array. The strongly typed nature of
arrays gives us
2 advantages. One, the performance will be
much better because boxing and unboxing will not happen. Second, run time
errors can be prevented because of type mis matches. Type mis matches and
runtime errors are most commonly seen with collection classes like ArrayList,
Queue, Stack etc, that are present in System.Collections
namespace.
Disadvantages of using arrays:
1. Arrays are fixed in size and cannot grow
over time, where ArrayList in System.Collections namespace can grow
dynamically.
2. Arrays are zero index based, and hence a
little difficult to work with. The only way to store or retrieve elements from
arrays, is to use integral index. Arrays donot provide convinient methods like
Add(), Remove() etc provided by collection classes found in System.Collections or System.Collections.Generics
namespaces, which are very easy to work with.
Explain what is an Interface in C#?
An Interface in C# is created using the
interface keyword. An example is shown below.
Code:
using System;
namespace Interfaces
{
interface IBankCustomer
{
void DepositMoney();
void WithdrawMoney();
}
public class Demo : IBankCustomer
{
public void DepositMoney()
{
Console.WriteLine("Deposit
Money");
}
public void WithdrawMoney()
{
Console.WriteLine("Withdraw
Money");
}
public static void Main()
{
Demo DemoObject = new Demo();
DemoObject.DepositMoney();
DemoObject.WithdrawMoney();
}
}
}
Can an Interface contain fields?
No, an Interface cannot contain fields.
Can
an interface inherit from another interface?
Yes, an interface can inherit from another
interface. It is possible for a class to inherit an interface multiple times,
through base classes or interfaces it inherits. In this case, the class can
only implement the interface one time, if it is declared as part of the new
class. If the inherited interface is not declared as part of the new class, its
implementation is provided by the base class that declared it. It is possible
for a base class to implement interface members using virtual members; in that
case, the class inheriting the interface can change the interface behavior by
overriding the virtual members.
Can
you create an instance of an interface?
No, you cannot create an instance of an
interface.
What
is a partial class. Give an example?
A partial class
is a class whose definition is present in 2 or more files. Each source file
contains a section of the class, and all parts are combined when the
application is compiled. To split a class definition, use the partial keyword
as shown in the example below. Student class is split into 2 parts. The first
part defines the study() method and the second part defines the Play() method.
When we compile this program both the parts will be combined and compiled. Note
that both the parts uses partial keyword and public access modifier.
Code:
using System;
namespace PartialClass
{
public partial class Student
{
public void Study()
{
Console.WriteLine("I am studying");
}
}
public partial class Student
{
public void Play()
{
Console.WriteLine("I am Playing");
}
}
public class Demo
{
public static void Main()
{
Student StudentObject = new Student();
StudentObject.Study();
StudentObject.Play();
}
}
}
It is very important to keep the following
points in mind when creating partial classes.
1. All the parts must use the partial
keyword.
2. All the parts must be available at
compile time to form the final class.
3. All the parts must have the same access
modifiers - public, private, protected etc.
4. Any class members declared in a partial
definition are available to all the other parts.
5. The final class is the combination of
all the parts at compile time.
What
are the advantages of using partial classes?
1. When working on large projects,
spreading a class over separate files enables multiple programmers to work on
it at the same time.
2. When working with automatically
generated source, code can be added to the class without having to recreate the
source file. Visual Studio uses this approach when it creates Windows Forms,
Web service wrapper code, and so on. You can create code that uses these
classes without having to modify the file created by Visual Studio.
Is
it possible to create partial structs, interfaces and methods?
Yes, it is possible to create partial
structs, interfaces and methods. We can create partial structs, interfaces and
methods the same way as we create partial classes.
Can
you create partial delegates and enumerations?
No, you cannot create partial delegates and
enumerations.
Can
different parts of a partial class inherit from different interfaces?
Yes, different parts of a partial class can
inherit from different interfaces.
Can
you specify nested classes as partial classes?
Yes, nested classes can be specified as
partial classes even if the containing class is not partial. An example is
shown below.
Code:
class ContainerClass
{
public partial class Nested
{
void Test1() { }
}
public partial class Nested
{
void Test2() { }
}
}
How do you create partial methods?
To create a partial method we create the
declaration of the method in one part of the partial class and implementation
in the other part of the partial class. The implementation is optional. If the
implementation is not provided, then the method and all the calls to the method
are removed at compile time. Therefore, any code in the partial class can
freely use a partial method, even if the implementation is not supplied. No
compile-time or run-time errors will result if the method is called but not
implemented. In summary a partial method declaration consists of two parts. The
definition, and the implementation. These may be in separate parts of a partial
class, or in the same part. If there is no implementation declaration, then the
compiler optimizes away both the defining declaration and all calls to the
method.
The
following are the points to keep in mind when creating partial methods.
1.
Partial method declarations must begin partial keyword.
2. The
return type of a partial method must be void.
3.
Partial methods can have ref but not out parameters.
4.
Partial methods are implicitly private, and therefore they cannot be virtual.
5.
Partial methods cannot be extern, because the presence of the body determines
whether they are defining or implementing.
What is the use of partial methods?
Partial methods can be used to customize
generated code. They allow for a method name and signature to be reserved, so
that generated code can call the method but the developer can decide whether to
implement the method. Much like partial classes, partial methods enable code
created by a code generator and code created by a human developer to work
together without run-time costs.
What is a nested type. Give an example?
A type(class or a struct) defined inside
another class or struct is called a nested type. An example is shown below.
InnerClass is inside ContainerClass, Hence InnerClass is called as nested
class.
Code:
using System;
namespace Nested
{
class ContainerClass
{
class InnerClass
{
public string str = "A string variable in nested class";
}
public static void Main()
{
InnerClass nestedClassObj = new InnerClass();
Console.WriteLine(nestedClassObj.str);
}
}
}
What is a Destructor?
A Destructor has the same name as the class
with a tilde character and is used to destroy an instance of a class.
Can a class have more than 1 destructor?
No, a class can have only 1 destructor.
Can structs in C# have destructors?
No, structs can have constructors but not
destructors, only classes can have destructors.
Can you pass parameters to destructors?
No, you cannot pass parameters to
destructors. Hence, you cannot overload destructors.
Can you explicitly call a destructor?
No, you cannot explicitly call a destructor.
Destructors are invoked automatically by the garbage collector.
Why is it not a good idea to use Empty
destructors?
When a class contains a destructor, an
entry is created in the Finalize queue. When the destructor is called, the
garbage collector is invoked to process the queue. If the destructor is empty,
this just causes a needless loss of performance.
Is
it possible to force garbage collector to run?
Yes, it possible to force garbage collector
to run by calling the Collect() method, but this is not considered a good
practice because this might create a performance over head. Usually the
programmer has no control over when the garbage collector runs. The garbage
collector checks for objects that are no longer being used by the application.
If it considers an object eligible for destruction, it calls the destructor(if
there is one) and reclaims the memory used to store the object.
Usually in .NET, the CLR takes care of
memory management. Is there any need for a programmer to explicitly release memory
and resources? If yes, why and how?
If the application is using expensive
external resource, it is recommend to explicitly release the resource before
the garbage collector runs and frees the object. We can do this by implementing
the Dispose method from the IDisposable interface that performs the necessary
cleanup for the object. This can considerably improve the performance of the
application.
When do we generally use destructors to
release resources?
If the application uses unmanaged resources
such as windows, files, and network connections, we use destructors to release
resources.
What
is a constructor in C#?
Constructor is a class method that is
executed when an object of a class is created. Constructor has the same name as
the class, and usually used to initialize the data members of the new object.
In
C#, What will happen if you do not explicitly provide a constructor for a
class?
If you do not provide a constructor
explicitly for your class, C# will create one by default that instantiates the
object and sets all the member variables to their default values.
Structs
are not reference types. Can structs have constructors?
Yes, even though Structs are not reference
types, structs can have constructors.
We cannot create instances of static
classes. Can we have constructors for static classes?
Yes, static classes can also have
constructors.
Can
you prevent a class from being instantiated?
Yes, a class can be prevented from being
instantiated by using a private constructor as shown in the example below.
Code:
using System;
namespace TestConsole
{
class Program
{
public static void Main()
{
//Error cannot create instance of a class with private constructor
SampleClass SC = new SampleClass();
}
}
class SampleClass
{
double PI = 3.141;
private SampleClass()
{
}
}
}
Can
a class or a struct have multiple constructors?
Yes, a class or a struct can have multiple
constructors. Constructors in csharp can be overloaded.
Can
a child class call the constructor of a base class?
Yes, a child class can call the constructor
of a base class by using the base keyword as shown in the example below.
Code:
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass(string str)
{
Console.WriteLine(str);
}
}
class ChildClass : BaseClass
{
public ChildClass(string str): base(str)
{
}
public static void Main()
{
ChildClass CC = new ChildClass("Calling base class constructor from
child class");
}
}
}
If a child class instance is created, which
class constructor is called first - base class or child class?
When an instance of a child class is
created, the base class constructor is called before the child class
constructor. An example is shown below.
Code:
using System;
namespace TestConsole
{
class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class constructor");
}
}
class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class constructor");
}
public static void Main()
{
ChildClass CC = new ChildClass();
}
}
}
Can
a class have static constructor?
Yes, a class can have static constructor.
Static constructors are called automatically, immediately before any static
fields are accessed, and are generally used to initialize static class members.
It is called automatically before the first instance is created or any static
members are referenced. Static constructors are called before instance
constructors. An example is shown below.
Code:
using System;
namespace TestConsole
{
class Program
{
static int I;
static Program()
{
I = 100;
Console.WriteLine("Static Constructor called");
}
public Program()
{
Console.WriteLine("Instance Constructor called");
}
public static void Main()
{
Program P = new Program();
}
}
}
Can you mark static constructor with access
modifiers?
No, we cannot use access modifiers on
static constructor.
Can you have parameters for static
constructors?
No, static constructors cannot have
parameters.
What happens if a static constructor throws
an exception?
If a static constructor throws an
exception, the runtime will not invoke it a second time, and the type will
remain uninitialized for the lifetime of the application domain in which your
program is running.
Give 2 scenarios where static constructors
can be used?
1. A typical use of static constructors is
when the class is using a log file and the constructor is used to write entries
to this file.
2. Static constructors are also useful when
creating wrapper classes for unmanaged code, when the constructor can call the
LoadLibrary method.
Does C# provide copy constructor?
No, C# does not provide copy constructor.
C Sharp Interview Questions/Answers
Part-2
What is .NET Remoting?
.NET Remoting allows objects to interact
with one another across application domains.
What are the 2 message encoding formats
supported by .NET Remoting and when do you choose one over the other?
Message Encoding Formats:
1. Binary encoding.
2. XML encoding.
Applications can use binary encoding where
performance is critical, or XML encoding where interoperability with other
remoting frameworks is essential.
What are the two types
of .NET remote objects?
1. Client-activated
objects - Client-activated objects are under the control of a lease-based
lifetime manager that ensures that the object is garbage collected when its
lease expires.
2. Server-activated
objects - In the case of server-activated objects, developers
have a choice of selecting either a "single call" or
"singleton" model. The lifetime of singletons are also controlled by
lease-based lifetime.
What is considered as Remote Object?
Any object outside the application domain
of the calling appication is considered remote object, even if the objects are
executing on the same machine.
Can you treat every object as a remote object?
Objects that cannot be serialized cannot be
passed to a different application domain and are therefore nonremotable.
What are the ways in which an object can be
serialized?
1. Mark your class with serializable
attribute.
2. Make your class implement ISerializable
interface.
How can you change an object into a remote
object?
Any object can be changed into a remote
object by deriving it from MarshalByRefObject.
What happens when a client activates a
remote object?
When a client activates a remote object, it
receives a proxy to the remote object. All operations on this proxy are
appropriately indirected to enable the remoting infrastructure to intercept and
forward the calls appropriately.
What are proxy objects and what is the use
of these proxy objects?
Proxy objects are created when a client
activates a remote object. The proxy object acts as a representative of the
remote object and ensures that all calls made on the proxy are forwarded to the
correct remote object instance.
What is the difference between method
parameters and method arguments. Give an example?
In the example below FirstNumber and
SecondNumber are method parameters where as FN and LN are method arguments. The
method definition specifies the names and types of any parameters that are
required. When calling code calls the method, it provides concrete values
called arguments for each parameter. The arguments must be compatible with the
parameter type but the argument name (if any) used in the calling code does not
have to be the same as the parameter named defined in the method.
Code:
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int FN = 10;
int SN = 20;
//FN and LN are method arguments
int Total = Sum(FN, SN);
Console.WriteLine(Total);
}
//FirstNumber and SecondNumber are method parameters
public static int Sum(int FirstNumber, int SecondNumber)
{
int Result = FirstNumber + SecondNumber;
return Result;
}
}
}
Can you pass value types by reference to a
method?
Yes, we can pass value types by by
reference to a method. An example is shown below.
Code:
using System;
namespace Demo
{
class Program
{
public static void Main()
{
int I = 10;
Console.WriteLine("Value of I before passing to the method = "
+ I);
Function(ref I);
Console.WriteLine("Value of I after passing to the method by
reference= " + I);
}
public static void Function(ref int Number)
{
Number = Number + 5;
}
}
}
What is the difference between static class
and class with static methods? In which case I should use either of them?
If your class has only static members you
never need an instance of that class so you should make the class itself static
but if your class has instance members (non static) then you have to make your
class an instance class to access its instance members via instances of your
class.
If a method's return type is void, can you
use a return keyword in the method?
Yes, Even though a method's return type is
void, you can use the return keyword to stop the execution of the method as
shown in the example below.
Code:
using System;
namespace Demo
{
class Program
{
public static void Main()
{
SayHi();
}
public static void SayHi()
{
Console.WriteLine("Hi");
return;
Console.WriteLine("This statement will never be executed");
}
}
}
How do you create empty strings in C#?
Using string.empty as shown in the example
below.
string EmptyString = string.empty;
What is the difference between
System.Text.StringBuilder and System.String?
1. Objects of type StringBuilder are
mutable where as objects of type System.String are immutable.
2. As StringBuilder objects are mutable,
they offer better performance than string objects of type System.String.
3. StringBuilder class is present in
System.Text namespace where String class is present in System namespace.
What is the difference between int.Parse
and int.TryParse methods?
Parse method throws an exception if the
string you are trying to parse is not a valid number where as TryParse returns
false and does not throw an exception if parsing fails. Hence TryParse is more
efficient than Parse.
What
is the difference between string keyword and System.String class?
string keyword is an alias for Syste.String
class. Therefore, System.String and string keyword are the same, and you can
use whichever naming convention you prefer. The String class provides many
methods for safely creating, manipulating, and comparing strings.
Are
string objects mutable or immutable?
String objects are immutable.
What
do you mean by String objects are immutable?
String objects are immutable means, they
cannot be changed after they have been created. All of the String methods and
C# operators that appear to modify a string actually return the results in a
new string object. In the following example, when the contents of s1 and s2 are
concatenated to form a single string, the two original strings are unmodified.
The += operator creates a new string that contains the combined contents. That
new object is assigned to the variable s1, and the original object that was
assigned to s1 is released for garbage collection because no other variable
holds a reference to it.
Code:
string s1 = "First String ";
string s2 = "Second String";
// Concatenate s1 and s2. This actually
creates a new
// string object and stores it in s1,
releasing the
// reference to the original object.
s1 += s2;
System.Console.WriteLine(s1);
// Output: First String Second String
What
is an array?
An array is a data structure that contains
several variables of the same type.
What
are the 3 different types of arrays?
1. Single-Dimensional
2. Multidimensional
3. Jagged
What
is Jagged Array?
A jagged array is an array of arrays.
Are
arrays value types or reference types?
Arrays are reference types.
What
is the base class for Array types?
System.Array
Can you use foreach iteration on arrays in
C#?
Yes,Since array type implements
IEnumerable, you can use foreach iteration on all arrays in C#.
What is Boxing and Unboxing?
Boxing - Converting a value type to reference type is called boxing. An
example is shown below.
Code:
int i = 101;
object obj = (object)i; // Boxing
Unboxing - Converting a reference type to a
value typpe is called unboxing. An example is shown below.
Code:
obj = 101;
i = (int)obj; // Unboxing
Is
boxing an implicit conversion?
Yes, boxing happens implicitly.
Is
unboxing an implicit conversion?
No, unboxing is an explicit conversion.
What
happens during the process of boxing?
Boxing is used to store value types in the
garbage-collected heap. Boxing is an implicit conversion of a value type to the
type object or to any interface type implemented by this value type. Boxing a
value type allocates an object instance on the heap and copies the value into
the new object. Due to this boxing and unboxing can have performance impact.
What
are the 4 pillars of any object oriented programming language?
1. Abstraction
2. Inheritance
3. Encapsulation
4. Polymorphism
Do
structs support inheritance?
No, structs do not support inheritance, but
they can implement interfaces.
What
is the main advantage of using inheritance?
Code reuse
Does
C# support multiple class inheritance?
No, C# supports single class inheritance
only. However classes can implement multiple interfaces at the same time.
What
is an abstract class?
An abstract class is an incomplete class
and must be implemented in a derived class.
Can
you create an instance of an abstract class?
No, abstract classes are incomplete and you
cannot create an instance of an abstract class.
What
is a sealed class?
A sealed class is a class that cannot be
inherited from. This means, If you have a class called Customer that is marked
as sealed. No other class can inherit from Customer class. For example, the
below code generates a compile time error "MainClass cannot derive from
sealed type Customer.
Code:
using System;
public sealed class Customer
{
}
public class MainClass : Customer
{
public static void Main()
{
}
}
What
are abstract methods?
Abstract methods are methods that only the
declaration of the method and no implementation.
Can
a sealed class be used as a base class?
No, sealed class cannot be used as a base
class. A compile time error will be generated.
Explain
polymorphism in C# with a simple example?
Polymorphism allows you to invoke derived
class methods through a base class reference during run-time. An example is
shown below.
Code:
using
System;
public
class DrawingObject
{
public
virtual void Draw()
{
Console.WriteLine("I
am a drawing object.");
}
}
public
class Triangle : DrawingObject
{
public
override void Draw()
{
Console.WriteLine("I
am a Triangle.");
}
}
public
class Circle : DrawingObject
{
public
override void Draw()
{
Console.WriteLine("I
am a Circle.");
}
}
public
class Rectangle : DrawingObject
{
public
override void Draw()
{
Console.WriteLine("I
am a Rectangle.");
}
}
public
class DrawDemo
{
public
static void Main()
{
DrawingObject[]
DrawObj = new DrawingObject[4];
DrawObj[0]
= new Triangle();
DrawObj[1]
= new Circle();
DrawObj[2]
= new Rectangle();
DrawObj[3]
= new DrawingObject();
foreach
(DrawingObject drawObj in DrawObj)
{
drawObj.Draw();
}
}
}
When
can a derived class override a base class member?
A derived class can override a base class
member only if the base class member is declared as virtual or abstract.
What
is the difference between a virtual method and an abstract method?
A virtual method must have a body where as
an abstract method should not have a body.
Can fields inside a class be virtual?
No, Fields inside a class cannot be virtua.
Only methods, properties, events and indexers can be virtual.
What
are Access Modifiers in C#?
In C# there are 5 different types of Access
Modifiers.
Public
The public type or member can be accessed
by any other code in the same assembly or another assembly that references it.
Private
The type or member can only be accessed by
code in the same class or struct.
Protected
The type or member can only be accessed by
code in the same class or struct, or in a derived class.
Internal
The type or member can be accessed by any
code in the same assembly, but not from another assembly.
Protected Internal
The type or member can be accessed by any
code in the same assembly, or by any derived class in another assembly.
What
are Access Modifiers used for?
Access Modifiers are used to control the
accessibilty of types and members with in the types.
Can you use all access modifiers for all
types?
No, Not all access modifiers can be used by
all types or members in all contexts, and in some cases the accessibility of a
type member is constrained by the accessibility of its containing type.
Can
derived classes have greater accessibility than their base types?
No, Derived classes cannot have greater
accessibility than their base types. For example the following code is illegal.
Code:
using
System;
internal
class InternalBaseClass
{
public void Print()
{
Console.WriteLine("I am a Base Class
Method");
}
}
public
class PublicDerivedClass : InternalBaseClass
{
public static void Main()
{
Console.WriteLine("I am a Public
Derived Class Method");
}
}
When you compile the above code an error
will be generated stating "Inconsistent accessibility: base class
InternalBaseClass is less accessible than class PublicDerivedClass".To
make this simple, you cannot have a public class B that derives from an
internal class A. If this were allowed, it would have the effect of making A
public, because all protected or internal members of A are accessible from the
derived class.
Can
you declare struct members as protected?
No, struct members cannot be declared
protected. This is because structs do not support inheritance.
Can
the accessibility of a type member be greater than the accessibility of its
containing type?
No, the accessibility of a type member can
never be greater than the accessibility of its containing type. For example, a
public method declared in an internal class has only internal accessibility.
Can
destructors have access modifiers?
No, destructors cannot have access
modifiers.
What
does protected internal access modifier mean?
The protected internal access means
protected OR internal, not protected AND internal. In simple terms, a protected
internal member is accessible from any class in the same assembly, including
derived classes. To limit accessibility to only derived classes in the same
assembly, declare the class itself internal, and declare its members as
protected.
What
is the default access modifier for a class,struct and an interface declared
directly with a namespace?
internal
Can you specify an access modifier for an
enumeration?
Enumeration members are always public, and
no access modifiers can be specified.
No comments:
Post a Comment