29 June, 2009

XML related Interview Questions

What Is XML?
XML stands for Extensible Markup Language, and it is used to describe documents and data in a standardized, text-based format that can be easily transported via standard Internet protocols. XML, like HTML, is based on, Standard Generalized Markup Language (SGML).

What are Well-formed XML documents?
XML
, is very strict about a small core of format requirements that make the difference between a text document containing a bunch of tags and an actual XML document. XML documents that meet W3C XML document formatting recommendations are described as being well-formed XML documents. Well-formed XML documents can contain elements, attributes, and text.

What is an empty XML element?
Elements with no attributes or text are called as empty XML element. Empty XML elements can be represented in an XML document as shown below:


What is meant by XML document declaration?
Most XML documents start with an element at the top of the page. This is called an XML document declaration. An XML document declaration is an optional element that is useful to determine the version of XML and the encoding type of the source data. It is not a required element for an XML document to be well formed. Most common XML document declaration is shown below:


What does UTF stands for?
UTF stands for Universal Character Set Transformation Format.

Should every XML document have a root element?
Yes.

Can an XML document contain multiple root level elements?
No, an XML document can contain only one root level element.

What is the use of XML attributes?
XML attributes are used for adding more information and descriptions to the values of elements,and the text associated with elements.

Is XML case sensitive?
Yes

How do you comment lines in XML?
You can comment lines in XML as shown below.


What are XML namespaces?
Namespaces are a method for separating and identifying duplicate XML element names in an XML document. Namespaces can also be used as identifiers to describe data types and other information. Namespace declarations can be compared to defining a short variable name for a long variable (such as pi=3.14159....) in programming languages. In XML, the variable assignment is defined by an attribute declaration. The variable name is the attribute name, and the variable value is the attribute value. In order to identify namespace declarations versus other types of attribute declarations, a reserved xmlns: prefix is used when declaring a namespace name and value. The attribute name after the xmlns: prefix identifies the name for the defined namespace. The value of the attribute provides the unique identifier for the namespace. Once the namespace is declared, the namespace name can be used as a prefix in element names.

Why is it a good idea to use a URL as the XML namespace value?
Although the namespace declaration value does not need to be a URL or resolve to an actual URL destination, it is a good idea to use a URL anyway, and to choose a URL that could resolve to an actual destination, just in case developers want to add documentation for the namespace to the URL in the future.

When to use namespaces?
Namespaces are optional components of basic XML documents. However, namespace declarations are recommended if your XML documents have any current or future potential of being shared with other XML documents that may share the same element names. Also, newer XML-based technologies such as XML Schemas,SOAP, and WSDL make heavy use of XML namespaces to identify data encoding types and important elements of their structure.

XML Interview Questions - Validating XML documents

What determines the validity of an XML document?
Document Type Definition(DTD) or an XML Schema determines the validity of an XML document.

What is a valid XML document?
XML documents are compared to rules that are specified in a DTD or schema. A well-formed XML document that meets all of the requirements of one or more specifications is called a valid XML Document.

What are the 2 types of XML parsers?
Nonvalidating Parsers - Parsers that don’t support validation
Validating Parsers - Parsers that support validation

Can you combine both Schema and DTD references in a single XML document?
Yes

Are DTD's well-formed XML documents?
No, DTDs are not well-formed XML documents. This is because they follow DTD syntax rules rather than XML document syntax.

Are XML schema's well-formed XML documents?
Yes.

What is the difference between an XML schema and a DTD?
The XML Schema is the officially sanctioned Schema definition. Unlike DTDs, the format of XML Schemas follows the rules of well-formed XML documents. The Schema also allows for much more granular control over the data that is being described. Because of the XML format and the detailed format controls, Schemas tend to be very complex and often much longer than the XML documents that they are describing. Schemas are often much more easy for developers to read and follow,due to the less cryptic nature of the references in Schemas versus DTDs.

How do you define references to schemas in an XML document?
References to schemas are defined by creating an instance of the XMLSchemainstance namespace. An example is shown below.


The namespace declaration reference to http://www.w3.org/2001/XMLSchemainstance resolves to an actual document at that location, which is a brief description of the way that the W3C Schema should be referenced. The noNamespaceSchemaLocation value tells us that there is no predefined namespace for the Schema. This means that all of the elements in the XML document should be validated against the schema specified. The location of the Schema is schemafile.xsd. Because there is no path defined, the file containing the schema should be located in the same directory as the XML file to be validated by the Schema.

You can also define the schema location, and map it to a specific namespace by using the schemaLocation attribute declaration instead of noNamespace SchemaLocation. If you do so, you have to declare a namespace that matches the schemaLocation attribute value. The declaration must be made before you reference the schema in a schemaLocation attribute assignment.

C# Interview Questions - Arrays

What is the difference between arrays in C# and arrays in other programming languages?
Arrays in C# work similarly to how arrays work in most other popular languages There are, however, a few differences as listed below

1. When declaring an array in C#, the square brackets ([]) must come after the type, not the identifier. Placing the brackets after the identifier is not legal syntax in C#.

int[] IntegerArray; // not int IntegerArray[];

2. Another difference is that the size of the array is not part of its type as it is in the C language. This allows you to declare an array and assign any array of int objects to it, regardless of the array's length.

int[] IntegerArray; // declare IntegerArray as an int array of any size
IntegerArray = new int[10]; // IntegerArray is a 10 element array
IntegerArray = new int[50]; // now IntegerArray is a 50 element array

What are the 3 different types of arrays that we have in C#?
1. Single Dimensional Arrays
2. Multi Dimensional Arrays also called as rectangular arrays
3. Array Of Arrays also called as jagged arrays

Are arrays in C# value types or reference types?
Reference types.

What is the base class for all arrays in C#?
System.Array

How do you sort an array in C#?
The Sort static method of the Array class can be used to sort array items.

Give an example to print the numbers in the array in descending order?
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
//Print the numbers in the array without sorting
Console.WriteLine("Printing the numbers in the array without sorting");
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Sort and then print the numbers in the array
Console.WriteLine("Printing the numbers in the array after sorting");
Array.Sort(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
//Print the numbers in the array in desceding order
Console.WriteLine("Printing the numbers in the array in desceding order");
Array.Reverse(Numbers);
foreach (int i in Numbers)
{
Console.WriteLine(i);
}
}
}
}

What property of an array object can be used to get the total number of elements in an array?
Length property of array object gives you the total number of elements in an array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
Console.WriteLine("Total number of elements = " +Numbers.Length);
}
}
}

Give an example to show how to copy one array into another array?
We can use CopyTo() method to copy one array into another array. An example is shown below.
using System;
namespace ConsoleApplication
{
class Program
{
static void Main()
{
int[] Numbers = { 2, 5, 3, 1, 4 };
int[] CopyOfNumbers=new int[5];
Numbers.CopyTo(CopyOfNumbers,0);
foreach (int i in CopyOfNumbers)
{
Console.WriteLine(i);
}
}
}
}

ASP.NET Interview Questions on Globalization

What is Globalization?
Globalization is the process of creating an application that meets the needs of users from multiple cultures. This process involves translating the user interface elements of an application multiple languages, using the correct currency, date and time format, calendar, writing direction, sorting rules, and other issues. Accommodating these cultural differences in an application is called localization.

The Microsoft .NET Framework simplifies localization tasks substantially by making its formatting, date/time, sorting, and other classes culturally aware. Using classes from the System.Globalization namespace, you can set the application’s current culture, and much of the work is done automatically!

What are the 3 different ways to globalize web applications?

Detect and redirect approach :
In this approach we create a separate Web application for each supported culture, and then detect the user’s culture and redirect the request to the appropriate application. This approach is best for applications with lots of text content that requires translation and few executable components.

Run-time adjustment approach : In this approach we create a single Web application that detects the user’s culture and adjusts output at run time using format specifiers and other tools. This approach is best for simple applications that present limited amounts of content.

Satellite assemblies approach : In this approach we create a single Web application that stores culture-dependent strings in resource files that are compiled into satellite assemblies. At run time, detect the user’s culture and load strings from the appropriate assembly. This approach is best for applications that generate content at run time or that have large executable components.

In ASP.NET, how do you detect the user's language preference on his/her computer?
Use the Request object’s UserLanguages property to return a list of the user’s language preferences. The first element of the array returned by UserLanguages is the user’s current language on his/her computer.

What are the steps to follow to get user's culture at run time?
To get the user’s culture at run time, follow these steps:
1. Get the Request object’s UserLanguages property.
2. Use the returned value with the CultureInfo class to create an object representing the user’s current culture.

For example, the following code gets the user’s culture and displays the English name and the abbreviated name of the culture in a label the first time the page is displayed:
private void Page_Load(object sender, System.EventArgs e)
{
// Run the first time the page is displayed
if (!IsPostBack)
{
// Get the user's preferred language.
string sLang = Request.UserLanguages[0];
// Create a CultureInfo object from it.
CultureInfo CurrentCulture = new CultureInfo(sLang);
lblCulture.Text = CurrentCulture.EnglishName + ": " +
CurrentCulture.Name;
}
}

What are the advantages of using detect and redirect approach to globalizing web applications?
1. Content is maintained separately, so this approach allows the different applications to present very different information, if needed.
2. Users can be automatically directed to sites that are likely to be geographically close, and so can better meet their needs.
3. Content files (Web forms and HTML pages, for example) can be authored in the appropriate natural language without the complexity of including resource strings.

What are the disadvantages of using detect and redirect approach to globalizing web applications?
1. Using this approach requires that the executable portion of the Web application be compiled and deployed separately to each culture-specific website
2. This approach requires more effort to maintain consistency and to debug problems across Web sites.

What is the use of culture attribute of the globalization element in web.config?
The Web.config file’s globalization element is used to create a culture-specific Web application. The culture attribute of the globalization element specifies how the Web application deals with various culture-dependent issues, such as dates, currency, and number formatting.

Web.config globalization settings in subordinate folders override the globalization settings in the application’s root Web.config file. You can store content for various cultures in subfolders within your application, add Web.config files with the globalization settings for each culture, then direct users to the appropriate folder based on the user’s CurrentCulture.

The text on the webform is usually written from left to right. How do you change the writing direction to "right to left"?
The wrting direction of a webform can be changed using the HTML dir attribute as shown below.


You can use the dir attribute individually in panels, text boxes, or other controls as well. Setting the dir attribute on the body element applies right-to-left formatting to the entire page.

What do you mean by neutral cultures?
Neutral cultures represent general languages, such as English or Spanish, rather than a specific language and region. When you set the culture attribute for a Web application in Web.config, ASP.NET assigns that culture to all the threads running for that Web application. Threads are the basic unit to which the server allocates processor time. ASP.NET maintains multiple threads for a Web application within the aspnet_wp.exe worker process.

What are advantages of setting the culture dynamically at the thread level over creating separate Web applications for each culture?
1. All cultures share the same application code, so the application doesn’t have to be compiled and deployed for each culture.
2. The application resides at a single Web address, you don’t need to redirect users to other Web applications.
3. The user can choose from a full array of available cultures.

For what type of web applications setting the culture dynamically is best suited?
Setting the culture dynamically is best suited for simple Web applications that don’t contain large amounts of text that must be translated into different languages.

ASP.NET Interview Questions on DataSet

What is a DataSet?
DataSet is an in-memory cache of data.

In which namespace is the DataSet class present?
System.Data

Can you add more than one table to a dataset?
Yes

Can you enforce constarints and relations on tables inside a DataSet?
Yes, the DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. You can also enforce data integrity in the DataSet by using the UniqueConstraint and ForeignKeyConstraint objects.

What happens when you invoke AcceptChanges() method on a DataSet?
Invoking AcceptChanges() method on the DataSet causes AcceptChanges() method to be called on each table within the DataSet.

Both the DataRow and DataTable classes also have AcceptChanges() methods. Calling AcceptChanges() at the DataTable level causes the AcceptChanges method for each DataRow to be called.

When you call AcceptChanges on the DataSet, any DataRow objects still in edit-mode end their edits successfully. The RowState property of each DataRow also changes. Added and Modified rows become Unchanged, and Deleted rows are removed.

If the DataSet contains ForeignKeyConstraint objects, invoking the AcceptChanges method also causes the AcceptRejectRule to be enforced.

Is there a way to clear all the rows from all the tables in a DataSet at once?
Yes, use the DataSet.Clear() method to clear all the rows from all the tables in a DataSet at once.

What is the difference between DataSet.Copy() and DataSet.Clone()?
DataSet.Clone() copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.

DataSet.Copy() copies both the structure and data.

How do you get a copy of the DataSet containing all changes made to it since it was last loaded?
Use DataSet.GetChanges() method

What is the use of DataSet.HasChanges() Method?
DataSet.HasChanges method returns a boolean true if there are any changes made to the DataSet, including new, deleted, or modified rows. This method can be used to update a DataSource only if there are any changes.

How do you roll back all the changes made to a DataSet since it was created? Invoke the DataSet.RejectChanges() method to undo or roll back all the changes made to a DataSet since it was created.

What happnes when you invoke RejectChanges method, on a DataSet that contains 3 tables in it?
RejectChanges() method will be automatically invoked on all the 3 tables in the dataset and any changes that were done will be rolled back for all the 3 tables.

When the DataTable.RejectChanges method is called, any rows that are still in edit-mode cancel their edits. New rows are removed. Modified and deleted rows return back to their original state. The DataRowState for all the modified and deleted rows will be flipped back to unchanged.

What is the DataSet.CaseSensitive property used for?
When you set the CaseSensitive property of a DataSet to true, string comparisons for all the DataTables within dataset will be case sensitive. By default the CaseSensitive property is false.

ASP.NET Interview Questions on Themes and Skins

What is a "theme" in ASP.NET?
A "theme" is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in a Web application, across an entire Web application, or across all Web applications on a server.

What is the extension for a skin file?
.skin

What are the 2 types of control skins in ASP.NET?
1.
Default skins
2. Named skins

What is the difference between Named skins and Default skins?
A default skin automatically applies to all controls of the same type when a theme is applied to a page. A control skin is a default skin if it does not have a SkinID attribute. For example, if you create a default skin for a Calendar control, the control skin applies to all Calendar controls on pages that use the theme. (Default skins are matched exactly by control type, so that a Button control skin applies to all Button controls, but not to LinkButton controls or to controls that derive from the Button object.)

A named skin is a control skin with a SkinID property set. Named skins do not automatically apply to controls by type. Instead, you explicitly apply a named skin to a control by setting the control's SkinID property. Creating named skins allows you to set different skins for different instances of the same control in an application.

What are the 3 levels at which a theme can be applied for a web application?
1
. At the page level - Use the Theme or StyleSheetTheme attribute of the @ Page directive.

2. At the application level - Can be applied to all pages in an application by setting the element in the application configuration file.

3. At the webserver level - Define the element in machine.config file. This will apply the theme to all the web applications on that web server.

What is the name of the folder that contains the application themes?
App_Themes

What is a global theme?
A global theme is a theme that you can apply to all the website a server. Global themes allow you to define an overall look for your domain when you maintain multiple Web sites on the same server.

What is the difference between themes and CSS?
1. Themes can define many properties of a control or page, not just style properties. For example, using themes, you can specify the graphics for a TreeView control, the template layout of a GridView control, and so on.

2. Themes can include graphics.

3. Themes do not cascade the way style sheets do. By default, any property values defined in a theme referenced by a page's Theme property override the property values declaratively set on a control, unless you explicitly apply the theme using the StyleSheetTheme property.

4. Only one theme can be applied to each page. You cannot apply multiple themes to a page, unlike style sheets where multiple style sheets can be applied.

What are the security concerns to keep in mind when using themes?
Themes can cause security issues when they are used on your Web site. Malicious themes can be used to:

1. Alter a control's behavior so that it does not behave as expected.

2. Inject client-side script, therefore posing a cross-site scripting risk.

3. Expose sensitive information.

4. The mitigations for these common threats are:

5. Protect the global and application theme directories with proper access control settings. Only trusted users should be allowed to write files to the theme directories.

6. Do not use themes from an untrusted source. Always examine any themes from outside your organization for malicious code before using them on you Web site.

7. Do not expose the theme name in query data. Malicious users could use this information to use themes that are unknown to the developer and thereby expose sensitive information.

ASP.NET Interview Questions on HTTP modules and HTTP Handlers

What is an HTTP Handler?
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.

What is HTTP module?
An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

What is the interface that you have to implement if you have to create a Custom HTTP Handler?
Implement IHttpHandler interface to create a synchronous handler.
Implement IHttpAsyncHandler to create an asynchronous handler.

What is the difference between asynchronous and synchronous HTTP Handlers?
A synchronous handler does not return until it finishes processing the HTTP request for which it is called.

An asynchronous handler runs a process independently of sending a response to the user. Asynchronous handlers are useful when you must start an application process that might be lengthy and the user does not have to wait until it finishes before receiving a response from the server.

Which class is responsible for receiving and forwarding a request to the appropriate HTTP handler?
IHttpHandlerFactory Class

Can you create your own custom HTTP handler factory class?
Yes, we can create a custom HTTP handler factory class by creating a class that implements the IHttpHandlerFactory interface.

What is the use of HTTP modules?
HTTP modules are used to implement various application features, such as forms authentication, caching, session state, and client script services.

What is the difference between HTTP modules and HTTP handlers?
An HTTP handler returns a response to a request that is identified by a file name extension or family of file name extensions. In contrast, an HTTP module is invoked for all requests and responses. It subscribes to event notifications in the request pipeline and lets you run code in registered event handlers. The tasks that a module is used for are general to an application and to all requests for resources in the application.

What is the common way to register an HTTP module?
The common way to register an HTTP module is to have an entry in the application's Web.config file.

Much of the functionality of a module can be implemented in a global.asax file. When do you create an HTTP module over using Global.asax File?
You create an HTTP module over using Global.asax file if the following conditions are true

1. You want to re-use the module in other applications.
2. You want to avoid putting complex code in the Global.asax file.
3. The module applies to all requests in the pipeline.

More C# interview questions on strings

Will the following code compile and run?
string str = null;
Console.WriteLine(str.Length);
The above code will compile, but at runtime System.NullReferenceException will be thrown.

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.

How do you determine whether a String represents a numeric value?
To determine whether a String represents a numeric value use TryParse method as shown in the example below. If the string contains nonnumeric characters or the numeric value is too large or too small for the particular type you have specified, TryParse returns false and sets the out parameter to zero. Otherwise, it returns true and sets the out parameter to the numeric value of the string.

string str = "One";
int i = 0;
if(int.TryParse(str,out i))
{
Console.WriteLine("Yes string contains Integer and it is " + i);
}
else
{
Console.WriteLine("string does not contain Integer");
}

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.

Basic C# Interview Questions on strings

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.

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 will be the output of the following code?
string str1 = "Hello ";
string str2 = s1;
str1 = str1 + "C#";
System.Console.WriteLine(s2);

The output of the above code is "Hello" and not "Hello C#". This is bcos, if you create a reference to a string, and then "modify" the original string, the reference will continue to point to the original object instead of the new object that was created when the string was modified.

What is a verbatim string literal and why do we use it?
The "@" symbol is the verbatim string literal. Use verbatim strings for convenience and better readability when the string text contains backslash characters, for example in file paths. Because verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string. The following example shows some common uses for verbatim strings:

string ImagePath = @"C:\Images\Buttons\SaveButton.jpg";
//Output: C:\Images\Buttons\SaveButton.jpg

string MultiLineText = @"This is multiline
Text written to be in
three lines.";
/* Output:
This is multiline
Text written to be in
three lines.
*/

string DoubleQuotesString = @"My Name is ""Vankat.""";
//Output: My Name is "Vankat."

Basic C# Interview Questions on arrays

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#.

C# Interview questions on Boxing and Unboxing

What is Boxing and Unboxing?
Boxing - Converting a value type to reference type is called boxing. An example is shown below.
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.
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.

C# Interview Questions on data type casting

What do you mean by casting a data type?
Converting a variable of one data type to another data type is called casting. This is also called as data type conversion.

What are the 2 kinds of data type conversions in C#?
Implicit conversions:
No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.

Explicit conversions: Explicit conversions require a cast operator. The source and destination variables are compatible, but there is a risk of data loss because the type of the destination variable is a smaller size than (or is a base class of) the source variable.

What is the difference between an implicit conversion and an explicit conversion?
1. Explicit conversions require a cast operator where as an implicit converstion is done automatically.
2. Explicit conversion can lead to data loss where as with implicit conversions there is no data loss.

What type of data type conversion happens when the compiler encounters the following code?
ChildClass CC = new ChildClass();
ParentClass PC = new ParentClass();

Implicit Conversion. For reference types, an implicit conversion always exists from a class to any one of its direct or indirect base classes or interfaces. No special syntax is necessary because a derived class always contains all the members of a base class.

Will the following code compile?
double d = 9999.11;
int i = d;

No, the above code will not compile. Double is a larger data type than integer. An implicit conversion is not done automatically bcos there is a data loss. Hence we have to use explicit conversion as shown below.

double d = 9999.11;
int i = (int)d; //Cast double to int.

If you want to convert a base type to a derived type, what type of conversion do you use?
Explicit conversion as shown below.
//Create a new derived type.
Car C1 = new Car();
// Implicit conversion to base type is safe.
Vehicle V = C1;

// Explicit conversion is required to cast back to derived type. The code below will compile but throw an exception at run time if the right-side object is not a Car object.
Car C2 = (Car) V;

What operators can be used to cast from one reference type to another without the risk of throwing an exception?
The is and as operators can be used to cast from one reference type to another without the risk of throwing an exception.

If casting fails what type of exception is thrown?
InvalidCastException

C# Interview Questions on Data Types

What are the 3 types of comments in C#?
1. Single Line Comments. You define single line comments with // as shown below.
//This is an example for single line comment
2. Multi line comments. You define multi line comments with /* */ as shown below.
/*This is an example for
Multi Line comments*/
3. XML Comments. You define XML comments with /// as shown below.
///This is an example for defining XML comments.

Is C# a strongly-typed language?
Yes

What are the 2 broad classifications of data types available in C#?
1.
Built in data types.
2. User defined data types.

Give some examples for built in datatypes in C#?
1.
int
2. float
3. bool

C# Interview Questions on structs

Will the following code compile?
using System;
public class Example
{
static void Main()
{
TestStruct T = new TestStruct();
Console.WriteLine(T.i);
}
}
public struct TestStruct
{
public int i=10;
//Error: cannot have instance field initializers in structs
}
No, a compile time error will be generated stating "within a struct declaration, fields cannot be initialized unless they are declared as const or static"

Can a struct have a default constructor (a constructor without parameters) or a destructor in C#?
No

Can you instantiate a struct without using a new operator in C#?
Yes, you can instantiate a struct without using a new operator

Can a struct inherit from another struct or class in C#?
No, a struct cannot inherit from another struct or class, and it cannot be the base of a class.

Can a struct inherit from an interface in C#?
Yes

Are structs value types or reference types?
Structs are value types.

What is the base type from which all structs inherit directly?
All structs inherit directly from System.ValueType, which inherits from System.Object.

C# Interview Questions on Inheritance

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

Is the following code legal?
class ChildClass : ParentClassA, ParentClassB
{
}

No, a child class can have only one base class. You cannot specify 2 base classes at the same time. C# supports single class inheritance only. Therefore, you can specify only one base class to inherit from. However, it does allow multiple interface inheritance.

What will be the output of the following code?
using System;
public class BaseClass
{
public BaseClass()
{
Console.WriteLine("I am a base class");
}
}
public class ChildClass : BaseClass
{
public ChildClass()
{
Console.WriteLine("I am a child class");
}
static void Main()
{
ChildClass CC = new ChildClass();
}
}
Output:
I am a base class
I am a child class
This is because base classes are automatically instantiated before derived classes. Notice the output, The BaseClass constructor executed before the ChildClass constructor.

Does C# support multiple class inheritance?
No, C# supports single class inheritance only. However classes can implement multiple interfaces at the same time.

C# Interview Questions on Abstract and Sealed Class Members

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.
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.

Will the following code compile?
using System;
public abstract class Customer
{
public abstract void Test()
{
Console.WriteLine("I am customer");
}
}
public class MainClass
{
public static void Main()
{
}
}
No, abstract methods cannot have body. Hence, the above code will generate a compile time error stating "Customer.Test() cannot declare a body because it is marked abstract"

Is the following code legal?
using System;
public class Customer
{
public abstract void Test();
}
public class MainClass
{
public static void Main()
{
}
}

No, if a class has even a single abstract member, the class has to be marked abstract. Hence the above code will generate a compile time error stating "Customer.Test() is abstract but it is contained in nonabstract class Customer"

How can you force derived classes to provide new method implementations for virtual methods?
Abstract classes can be used to force derived classes to provide new method implementations for virtual methods. An example is shown below.
public class BaseClass
{
public virtual void Method()
{
// Original Implementation.
}
}

public abstract class AbstractClass : BaseClass
{
public abstract override void Method();
}

public class NonAbstractChildClass : AbstractClass
{
public override void Method()
{
// New implementation.
}
}

When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method. In the above example, Method() on class NonAbstractChildClass cannot call Method() on class BaseClass. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.

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.

Will the following code compile?
public abstract sealed class Test
{
public virtual void Method()
{
}
}
No, a class cannot be marked as sealed and abstract at the same time. This is because by definition, a sealed class cannot be a base class and an abstract class can only be a base class.

C# Interview Questions on polymorphism

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.
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.

Give an example to show for hiding base class methods?
Use the new keyword to hide a base class method in the derived class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

public static void Main()
{
DerivedClass DC = new DerivedClass();
DC.Method();
}
}

Can you access a hidden base class method in the derived class?
Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the derived class to an instance of the base class as shown in the example below.
using System;
public class BaseClass
{
public virtual void Method()
{
Console.WriteLine("I am a base class method.");
}
}
public class DerivedClass : BaseClass
{
public new void Method()
{
Console.WriteLine("I am a child class method.");
}

public static void Main()
{
DerivedClass DC = new DerivedClass();
((BaseClass)DC).Method();
}
}

Why should you override the ToString() method

Why should you override the ToString() method?
All types in .Net inherit from system.object directly or indirectly. Because of this inheritance, every type in .Net inherit the ToString() method from System.Object class. Consider the example below.

using System;
public class MainClass
{
public static void Main()
{
int Number = 10;
Console.WriteLine(Number.ToString());
}
}

In the above example Number.ToString() method will correctly give the string representaion of int 10, when you call the ToString() method.

If you have a Customer class as shown in the below example and when you call the ToString() method the output doesnot make any sense. Hence you have to override the ToString() method, that is inherited from the System.Object class.

using System;
public class Customer
{
public string FirstName;
public string LastName;
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}

The code sample below shows how to override the ToString() method in a class, that would give the output you want.


using System;
public class Customer
{
public string FirstName;
public string LastName;

public override string ToString()
{
return LastName + ", " + FirstName;
}
}
public class MainClass
{
public static void Main()
{
Customer C = new Customer();
C.FirstName = "David";
C.LastName = "Boon";
Console.WriteLine(C.ToString());
}
}

Conclusion : If you have a class or a struct, make sure you override the inherited ToString() method.

C# Interview Questions on Access Modifiers

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.
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.


Is the following code legal?

using System;
private class Test
{
public static void Main()
{
}
}


No, a compile time error will be generated stating "Namespace elements cannot be explicitly declared as private, protected, or protected internal"

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

Will the following code compile?

using System;
interface IExampleInterface
{
public void Save();
}

No, you cannot specify access modifer for an interface member. Interface members are always public.

Can you specify an access modifier for an enumeration?
Enumeration members are always public, and no access modifiers can be specified.

C# Interview Questions on Fields

What are the 2 broad classifications of fields in C#?
1. Instance fields
2. Static fields

What are instance fields in C#?
Instance fields are specific to an instance of a type. If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object.

What is a static field?
A static field belongs to the class itself, and is shared among all instances of that class. Changes made from instance A will be visible immediately to instances B and C if they access the field.

Will the following code compile?

using System;
class Area
{
public static double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
Console.WriteLine(A.PI);
}
}
No, a compile time error will be generated stating "Static member 'Area.PI' cannot be accessed with an instance reference; qualify it with a type name instead". This is because PI is a static field. Static fields can only be accessed using the name of the class and not the instance of the class. The above sample program is rewritten as shown below.

using System;
class Area
{
public static double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Area.PI);
}
}

Can you declare a field readonly?
Yes, a field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. An example is shown below.

using System;
class Area
{
public readonly double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
Console.WriteLine(A.PI);
}
}

Will the following code compile?

using System;
class Area
{
public readonly double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Area A = new Area();
A.PI = 3.15;
Console.WriteLine(A.PI);
}
}

No, PI is readonly. You can only read the value of PI in the Main() method. You cannot assign any value to PI.

What is wrong with the sample program below?

using System;
class Area
{
public const double PI = 3.14;
static Area()
{
Area.PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Area.PI);
}
}
You cannot assign a value to the constant PI field.

What is the difference between a constant and a static readonly field?
A static readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time.

C# Interview Questions on Constants

What are constants in C#?
Constants in C# are immutable values which are known at compile time and do not change for the life of the program. Constants are declared using the const keyword. Constants must be initialized as they are declared. You cannot assign a value to a constant after it isdeclared. An example is shown below.

using System;
class Circle
{
public const double PI = 3.14;
public Circle()
{
//Error : You can only assign a value to a constant field at the time of declaration
//PI = 3.15;
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}

Can you declare a class or a struct as constant?
No, User-defined types including classes, structs, and arrays, cannot be const. Only the C# built-in types excluding System.Object may be declared as const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.

Does C# support const methods, properties, or events?
No, C# does not support const methods, properties, or events.

Can you change the value of a constant filed after its declaration?
No, you cannot change the value of a constant filed after its declaration. In the example below, the constant field PI is always 3.14, and it cannot be changed even by the class itself. In fact, when the compiler encounters a constant identifier in C# source code (for example, PI), it substitutes the literal value directly into the intermediate language (IL) code that it produces. Because there is no variable address associated with a constant at run time, const fields cannot be passed by reference.

using System;
class Circle
{
public const double PI = 3.14;
}

How do you access a constant field declared in a class?
Constants are accessed as if they were static fields because the value of the constant is the same for all instances of the type. You do not use the static keyword to declare them. Expressions that are not in the class that defines the constant must use the class name, a period, and the name of the constant to access the constant. In the example below constant field PI can be accessed in the Main method using the class name and not the instance of the class. Trying to access a constant field using a class instance will generate a compile time error.

using System;
class Circle
{
public const double PI = 3.14;
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
Circle C = new Circle();
// Error : PI cannot be accessed using an instance
// Console.WriteLine(C.PI);
}
}

C# Interview Questions on Properties

What are Properties in C#. Explain with an example?
Properties in C# are class members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

In the example below _firstName and _lastName are private string variables which are accessible only inside the Customer class. _firstName and _lastName are exposed using FirstName and LastName public properties respectively. The get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels. The value keyword is used to define the value being assigned by the set accessor. The FullName property computes the full name of the customer. Full Name property is readonly, because it has only the get accessor. Properties that do not implement a set accessor are read only.

The code block for the get accessor is executed when the property is read and the code block for the set accessor is executed when the property is assigned a new value.


using System;
class Customer
{
// Private fileds not accessible outside the class.
private string _firstName = string.Empty;
private string _lastName = string.Empty;
private string _coutry = string.Empty;

// public FirstName property exposes _firstName variable
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
// public LastName property exposes _lastName variable
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName property is readonly and computes customer full name.
public string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
//Country Property is Write Only
public string Country
{
set
{
_coutry = value;
}
}

}
class MainClass
{
public static void Main()
{
Customer CustomerObject = new Customer();
//This line will call the set accessor of FirstName Property
CustomerObject.FirstName = "David";
//This line will call the set accessor of LastName Property
CustomerObject.LastName = "Boon";
//This line will call the get accessor of FullName Property
Console.WriteLine("Customer Full Name is : " + CustomerObject.FullName);
}
}

Explain the 3 types of properties in C# with an example?
1. Read Only Properties: Properties without a set accessor are considered read-only. In the above example FullName is read only property.
2. Write Only Properties: Properties without a get accessor are considered write-only. In the above example Country is write only property.
3. Read Write Properties: Properties with both a get and set accessor are considered read-write properties. In the above example FirstName and LastName are read write properties.

What are the advantages of properties in C#?
1. Properties can validate data before allowing a change.
2. Properties can transparently expose data on a class where that data is actually retrieved from some other source such as a database.
3. Properties can take an action when data is changed, such as raising an event or changing the value of other fields.

What is a static property. Give an example?
A property that is marked with a static keyword is considered as static property. This makes the property available to callers at any time, even if no instance of the class exists. In the example below PI is a static property.

using System;
class Circle
{
private static double _pi = 3.14;
public static double PI
{
get
{
return _pi;
}
}
}
class MainClass
{
public static void Main()
{
Console.WriteLine(Circle.PI);
}
}

What is a virtual property. Give an example?
A property that is marked with virtual keyword is considered virtual property. Virtual properties enable derived classes to override the property behavior by using the override keyword. In the example below FullName is virtual property in the Customer class. BankCustomer class inherits from Customer class and overrides the FullName virtual property. In the output you can see the over riden implementation. A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual.


using System;
class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;

public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName is virtual
public virtual string FullName
{
get
{
return _lastName + ", " + _firstName;
}
}
}
class BankCustomer : Customer
{
// Overiding the FullName virtual property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
}
}

What is an abstract property. Give an example?
A property that is marked with abstract keyword is considered abstract property. An abstract property should not have any implementation in the class. The derived classes must write their own implementation. In the example below FullName property is abstract in the Customer class. BankCustomer class overrides the inherited abstract FullName property with its own implementation.


using System;
abstract class Customer
{
private string _firstName = string.Empty;
private string _lastName = string.Empty;

public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
// FullName is abstract
public abstract string FullName
{
get;
}
}
class BankCustomer : Customer
{
// Overiding the FullName abstract property derived from customer class
public override string FullName
{
get
{
return "Mr. " + FirstName + " " + LastName;
}
}
}
class MainClass
{
public static void Main()
{
BankCustomer BankCustomerObject = new BankCustomer();
BankCustomerObject.FirstName = "David";
BankCustomerObject.LastName = "Boon";
Console.WriteLine("Customer Full Name is : " + BankCustomerObject.FullName);
}
}

Can you use virtual, override or abstract keywords on an accessor of a static property?
No, it is a compile time error to use a virtual, abstract or override keywords on an accessor of a static property.

ASP.NET Interview Questions on Data Access Security

What are the best practices to follow to secure connection strings in an ASP.NET web application?
1. Always store connection strings in the site's Web.config file. Web.config is very secure. Users will not be able to access web.config from the browser.
2. Do not store connection strings as plain text. To help keep the connection to your database server secure, it is recommended that you encrypt connection string information in the configuration file.
3. Never store connection strings in an aspx page.
4. Never set connection strings as declarative properties of the SqlDataSource control or other data source controls.

Why is "Connecting to SQL Server using Integrated Security" considered a best practice?
Connecting to SQL Server using integrated security instead of using an explicit user name and password, helps avoid the possibility of the connection string being compromised and your user ID and password being exposed.

What is the advantage of storing an XML file in the applications App_Data folder? The contents of the App_Data folder will not be returned in response to direct HTTP requests.

What is Script injection?
A script injection attack attempts to send executable script to your application with the intent of having other users run it. A typical script injection attack sends script to a page that stores the script in a database, so that another user who views the data inadvertently runs the code.

What is SQL injection?
A SQL injection attack attempts to compromise your database by creating SQL commands that are executed instead of, or in addition to, the commands that you have built into your application.

What are the best practices to keep in mind when accepting user input on a web application?
1. Always use validation controls whenever possible to limit user input to acceptable values.
2. Always check the IsValid property of the aspx page. Run the server side code only if the IsValid property value is true. A value of false means that one or more validation controls have failed a validation check.
3. Always perform server side validation irrespective of client side validation being performed or not. This will protect your web application even if the client has by passed the client side validation by disabling javascript
in the web browser.
4. Also make sure to re validate user input in the business logic layer of your application.

What are the steps to follow to avoid Script Injection attacks?
1. Encode user input with the HtmlEncode method. This method turns HTML into its text representation.
2. If you are using the GridView control with bound fields, set the BoundField object's HtmlEncode property to true. This causes the GridView control to encode user input when the row is in edit mode.

What are the steps to follow to avoid SQL Injection attacks?
Always use parameterized queries or stored procedures instead of creating SQL commands by concatenating strings together.

Can you encrypt view state data of an aspx page?
Yes, you encrypt view state data of an aspx page by setting the page's ViewStateEncryptionMode property to true.

Steps for Session InProc Mode to Session StateServer

Many articles are discussing about advantages of using Session StateServer or SQLServer over InProc Mode. One basic reason why I choose StateServer Mode is when your website is running on Third Party Hosting than you will notice that Session Timeout can occur anytime depends on load of traffic on your server.


If your website has large number of visitors and session timeout can cause problem, It is better to change Session Mode Session="InProc" to Session="StateServer".

Main Advantage of Session StateServer (Best to choose while hosting on third party server)
1. Session is persistent and reliable.
2. Avoid Session Timeout due to Memory shortage on server (IIS Setting).

Main Disadvantage
1. Poor Performance compare to Session="InProc"
2. Session_End Event would not fire.

28 June, 2009

Asp.Net Interview Questions

What Features Are in Silverlight?

Silverlight combines multiple technologies into a single development platform that enables you to select the right tools and the right programming language for your needs. Silverlight offers you the following features:

WPF and XAML. Silverlight includes Windows Presentation Foundation (WPF) technology, which greatly extends the elements in the browser for creating UI. WPF lets you create immersive graphics, animation, media, and other rich client features, extending browser-based UI beyond what is available with HTML alone. Extensible Application Markup Language (XAML) provides a declarative markup syntax for creating WPF elements.
See Creating User Interfaces with Silverlight for more information.
Extensions to JavaScript. Silverlight provides extensions to the universal browser scripting language that provide powerful control over the browser UI, including the ability to work with WPF elements.
See Silverlight 1.0 - Development with JavaScript for more information.
Cross-browser, cross-platform support. Silverlight runs the same on all popular browsers (on any platform). You can design and develop your application without having to worry about which browser or platform your users have.
See Creating and Deploying Silverlight Applications for more information.
Integration with existing applications. Silverlight integrates seamlessly with your existing JavaScript and ASP.NET AJAX code to complement functionality you have already created.
See Integrating Silverlight with ASP.NET Web Pages for more information.
Access to the .NET Framework programming model and to associated tools. You can create Silverlight-based applications using dynamic languages such as managed JScript and IronPython as well as languages such as C# and Visual Basic. You can use development tools such as Visual Studio to create Silverlight-based applications.
See Common Language Runtime and Base Class Library in Silverlight and Dynamic Languages in Silverlight 2 for more information.
LINQ. Silverlight includes language-integrated query (LINQ), which enables you to program data access using intuitive native syntax and strongly typed objects in .NET Framework languages.
See Parsing XML Data in Silverlight for more information.
If you already use ASP.NET, you can integrate Silverlight with the server and client capabilities of ASP.NET that you are familiar with. You can create server-based resources in ASP.NET and use the AJAX capabilities of ASP.NET to interact with server-based resources without interrupting the user.

Reference by :http://msdn.microsoft.com

What Is Silverlight?

Silverlight enables you to create a state-of-the-art application that has the following features:
It is a cross-browser, cross-platform technology. It runs in all popular Web browsers, including Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari, and on Microsoft Windows and Apple Mac OS X.
It provides a consistent experience no matter where it runs.
It is supported by a very small download that installs in seconds.
It streams video and audio. It scales video quality to everything from mobile devices to desktop browsers to 720p HDTV video modes.
It includes compelling graphics that users can manipulate—drag, turn, zoom—directly in the browser.
It reads data and updates the display, but it doesn't interrupt the user by refreshing the whole page.
Silverlight-based application with rich graphics and user interaction
Web developers and graphics designers can create Silverlight-based applications in a variety of ways. You can use Silverlight markup to create media and graphics, and manipulate them with dynamic languages and managed code. Silverlight also enables you to use professional-quality tools like Visual Studio for coding and Microsoft Expression Blend for layout and graphic design.

Reference by :http://msdn.microsoft.com

SMTP and POP3 Mail server Setting

Yahoo! Mail Settings

Yahoo Incoming Mail Server (POP3) - pop.mail.yahoo.com (port 110)
Yahoo Outgoing Mail Server (SMTP) - smtp.mail.yahoo.com (port 25)

Yahoo Incoming Mail Server (POP3) - plus.pop.mail.yahoo.com (SSL enabled, port 995)
Yahoo Outgoing Mail Server (SMTP) - plus.smtp.mail.yahoo.com (SSL enabled, port 465)

Google GMail Settings

Google Gmail Incoming Mail Server (POP3) - pop.gmail.com (SSL enabled, port 995)
Google Gmail Outgoing Mail Server - use the SMTP mail server address provided by your local ISP or smtp.gmail.com (SSL enabled, port 465)

Lycos Mail Settings

Lycos Mail Incoming Mail Server (POP3) - pop.mail.lycos.com (port 110)
Lycos MailOutgoing Mail Server - smtp.mail.lycos.com or use your local ISP SMTP mail server

AOL Mail Settings

AOL Incoming Mail Server (IMAP) - imap.aol.com (port 143)
AOL Outgoing Mail Server - smtp.aol.com or use your local ISP SMTP mail server

Mail.com Mail Settings

Mail.com Mail Incoming Mail Server (POP3) - pop1.mail.com (port 110)
Outgoing Mail Server - use your local ISP SMTP mail server

Netscape Internet Service Mail Settings

Netscape Internet Service Incoming Mail Server (POP3) - pop.3.isp.netscape.com (port 110)
Netscape Internet Service Outgoing Mail Server - smtp.isp.netscape.com (port 25, using a secure SSL connection)

Tiscali Mail Settings

Tiscali Incoming Mail Server (POP3) - pop.tiscali.com (port 110)
Outgoing Mail Server - use your local ISP SMTP mail server

Freeserve Mail Settings

Freeserve Incoming Mail Server (POP3) - pop.freeserve.com (port 110)
Outgoing Mail Server - use your local ISP SMTP mail server

Supanet Mail Settings

Supanet Incoming Mail Server (POP3) - pop.supanet.com (port 110)
Outgoing Mail Server - use your local ISP SMTP mail server

Using COM components in .NET and How to add a reference to a COM component?

The .NET does not encourage the use of COM component directly inside the managed application! Although, the .NET framework contains utilities that enable COM components to be used inside the .Net applications seamlessly. How it is done? The .NET utilities like TlbImp generates the wrapper .NET assembly for the COM component which provides the same calling interface to the client as exposed by the COM component. Inside the wrapper methods, it calls the actual methods of the COM component and returns the result back to the caller. The generated wrapper .NET assembly is called the ‘Runtime Callable Wrapper’ or RCW.
To use a COM component in your Visual Studio.NET project, you need to add a reference of the COM component in the Reference node of the project node of the solution inside the solution explorer window. The great thing about Visual Studio.Net is that it allows you to add a reference to the COM component in exactly the similar way as you add the reference to the .NET assembly. The Visual Studio.NET automatically creates the runtime callable wrapper assembly for the referenced COM component.
To add a reference to a COM component, right click the ‘Reference’ node under the project node inside the solution explorer and select the ‘Add Reference…’ option. It will show you a user interface screen where you browse for the target COM component. When you have selected the component, press the ‘Select’ button and then press OK. This will add a new reference node in the Reference sub tree of the project. By selecting the added reference node, you can edit its properties from the properties window.
Note: The process of importing a COM component into .NET is called ‘COM interoperability with .NET’

What are XML Doc comments (comments start with three slashes ///)?

The XML Doc comments are special kind of comments that can be recognized by Document utility to automatically generate the documentation of your methods, types and regions.

How true it is that .NET and Java programs are quite in-efficient when compared to C++?

The startup of managed .NET and Java programs is definitely slower than the traditional C++ programs as it involves the hosting of CLR into managed application process in .NET and starting the JVM in a new process in case of Java. The execution also is a bit slower during the initial period of program execution as the intermediate code is translated to the machine code on the fly at runtime. But as the program runs various parts repeatedly, the execution gets pace too. Since, the CLR and JVM optimizes the code more efficiently than the static C++ compilers, the execution speed of the program may actually be faster after sometime of the program startup when most of the code is translated. Hence, in the longer run, the .Net and Java based programs should not be in-efficient when compared to C++. We used ‘should’ here as the actual performance depends on the particular implementation and implementation strategy.

What are the shortcomings of MS.NET platform?

The foremost short coming of .NET platform is that it is still the propriety of Microsoft. It is more coupled with the Microsoft Windows operating system and is implemented only on Microsoft Windows successfully. MS.NET desktop applications can run only on Microsoft Windows, Web based applications and web services can only be deployed on Microsoft Internet Information Server (IIS). Since, dot net framework contains a lot of utilities, components, and framework class libraries, the size of downloadable framework is quite large (25MB compared to 5MB size of JVM). Not all types of applications can be written in .NET managed applications, for example, you can’t write CLR or Operating System in your managed applications. The managed .Net applications are somewhat slower to start and run than the traditional Win32 applications. The compiled code of .Net managed applications is easier to de-compile back to the source code.

Asp.Net Technical Questions

What is the difference WCF and Web services?

Web services can only be invoked by HTTP. While Service or a WCF component can be invoked by any protocol and any transport type. Second web services are not flexible. But Services are flexible. If you make a new version of the service then you need to just expose a new end point. So services are agile and which is a very practical approach looking at the current business trends.

How can we host a service on two different protocols on a single server?

Let’s first understand what this question actually means. Let’s say we have made a service and we want to host this service using HTTP as well as TCP. You must be wondering why to ever host services on two different types of protocol. When we host a service it’s consumed by multiple types of client and it’s very much possible that they have there own protocol of communication. A good service has the capability to downgrade or upgrade its protocol according the client who is consuming him.
Let’s do a small sample in which we will host the ServiceGetCost on TCP and HTTP protocol.

Once we are done the server side coding its time to see make a client by which we can switch between the protocols and see the results. Below is the code snippet of the client side for multi-protocol hosting

What is three major points in WCF?

1) Address --- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.

2)Contract --- Specifies the interface between client and the server.It's a simple interface with some attribute.

3)Binding --- Specifies how the two paries will communicate in term of transport and encoding and protocols.

What is WCF?

Windows Communication Foundation (formerly code-named "Indigo") is a set of .NET technologies for building and running connected systems. It is a new breed of communications infrastructure built around the Web services architecture.

Windows Communication Foundation is Microsoft's unified programming model for building service-oriented applications with managed code. It extends the .NET Framework to enable developers to build secure and reliable transacted Web services that integrate across platforms and interoperate with existing investments. Windows Communication Foundation combines and extends the capabilities of existing Microsoft distributed systems technologies, including Enterprise Services, System.Messaging, Microsoft .NET Remoting, ASMX, and WSE to deliver a unified development experience across multiple axes, including distance (cross-process, cross-machine, cross-subnet, cross-intranet, cross-Internet), topologies (farms, fire-walled, content-routed, dynamic), hosts (ASP.NET, EXE, Windows Presentation Foundation, Windows Forms, NT Service, COM+), protocols (TCP, HTTP, cross-process, custom), and security models (SAML, Kerberos, X509, username/password, custom).

Why are there five tracing levels in System.Diagnostics.TraceSwitcher?

The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.

Where is the output of TextWriterTraceListener redirected?

To the Console or a text file depending on the parameter passed to the constructor.

How do you debug an ASP.NET Web application?

Attach the aspnet_wp.exe process to the DbgClr debugger.

What are three test cases you should go through in unit testing?

1.Positive test cases (correct data, correct output).
2. Negative test cases (broken or missing data, proper handling).
3. Exception test cases (exceptions are thrown and caught properly).

Asp.Net Question Bank

What is the Website Administrative Tool in ASP.NET 2.0 ?

In ASP.NET 2.0, while using Visual Studio 2005 Express Edition or above, the development IDE provides an interface for editing the web.config rather than manually editing the web.config.

In the IDE, click on "Website" and then on "ASP.NET Configuration". This shall open the Website configuration tool. Note that the Web Site Administration Tool is a set of prebuilt ASP.NET 2.0 webpages and resources that are located within the C:\Inetpub\wwwroot\aspnet_webadmin\2_0_40607 directory.

Describe the security authentication flow and process in ASP.NET?

When a user requests a web page, there exists a process of security too, so that every anonymous user is checked for authentication before gaining access to the webpage. The following points are followed in the sequence for authentication when a client attempts a page request:

* A .aspx web page residing on an IIS web server is requested by an end user
* IIS checks for the user's credentials
* Authentication is done by IIS. If authenticated, a token is passed to the ASP.NET worker process along with the request
* Based on the authentication token from IIS, and on the web.config settings for the requested resource, ASP.NET impersonates the end user to the request thread. For impersonation, the web.config impersonate attribute's value is checked.

What are the types of WPF Applications ?

The following four types of WPF applications are available through .NET Framework 3.0 within Visual Studio 2005:

❑ .NET Framework 3.0 Windows Application—The .NET Framework 3.0 Windows Application is essentially the equivalent of a .NET Windows Forms project with all the perks of the WPF API.

❑ .NET Framework 3.0 XAML Browser Application—The .NET Framework 3.0 XAML Browser Application (XBAP) is the WPF version of an ASP.NET web application, with a limited amount of WPF namespaces and functionality available to it, because of the browser’s security access limitations on the client.

❑ .NET Framework 3.0 Service Library Project—The .NET Framework 3.0 Service Library is a Windows Communication Foundation project type and is not held within its sibling WPF platform.

❑ .NET Framework 3.0 Custom Control Library Project—The .NET Framework 3.0 Custom
Control Library is a project designed to output a reusable control that can be redistributed to a .NET application in the form of a dynamic-link library (DLL) .NET assembly.

What is one way operation?

IsOneWay equal to true ensures that the client does not have to wait for the response. So methods marked by IsOneWay to true should always return void. In this the caller does not get anything in return so it is called as one-way communication. In order to understand one way implementation in WCF lets make a code walkthrough of a sample.

Above is the code snippet which describes practically how one way works in WCF. The above given code snippet is numbered. Below is the explanation according to the numbers marked in figure:
1 - This is the code snippet of the server service. We have created a method called as doHugeTask. doHugeTask basically makes the method sleep for 5000 MS and then displays the time when the task is completed.
2 - This code snippet is for client. It creates a proxy object of serviceIsOneWay and calls the doHugeTask method. After calling the doHugeTask the client execution continues ahead. So as a proof we display the time when the method calling was completed.
3 - This screen shot shows the output given by both server and client. The top window displays the server output and the below windows displays the client output.
So run the server program first i.e. ServiceIsOneWay and run the client later. You will see the client runs the doHugeTask and moves ahead. So the client completion time is less than the server. One more thing to understand is that one way does not give any notification back of completion. So it’s like fire and forget.

Before in my VB app I would just load the icons from DLL. How can I load the icons provided by .NET dynamically?

By using System.Drawing.SystemIcons class' for example System.Drawing.SystemIcons.Warning produces an Icon with a warning sign in it.

What,s typical about a Windows process in regards to memory allocation?

Each process is allocated its own block of available RAM space' no process can access another process' code or data. If the process crashes' it dies alone without taking the entire OS or a bunch of other applications down.

What are the various ways of hosting a WCF service?

There are three major ways to host a WCF service:

Self hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of ServiceHost class and the service closes when you call the Close of the ServiceHost class.
Host in application domain or process provided by IIS Server.
Host in Application domain and process provided by WAS (Windows Activation Service) Server.

what are the advantages of hosting WCF Services in IIS as compared to self hosting?

There are two main advantages of using IIS over self hosting:
Automatic activation
IIS provides automatic activation that means the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfills the request. But in case of self hosting the service should always be running.
Process recycling
If IIS finds that a service is not healthy that means if it has memory leaks etc, IIS recycles the process. Ok let us try to understand what is recycling in IIS process. For every browser instance a worker process is spawned and the request is serviced. When the browser disconnects the worker process stops and you loose all information. IIS also restarts the worker process. By default the worker process is recycled at around 120 minutes. So why does IIS recycle. By restarting the worker process it ensures any bad code or memory leak do not cause issue to the whole system.
In case of self hosting both the above features you will need to code yourself. Lot of work right!!. That's why IIS is the best option for hosting services until you are really doing something custom.
Below figure shows where the recycle option is located in IIS. You need to click on the DefaultAppool and then Properties.