Friday, January 21, 2011

.net interview question

What do you mean by virtual property? Give an example?
Posted by: Tripati_tutu
A property declared with virtual keyword is considered as virtual property. These enables derived classes to override the property behavior by using the override keyword. 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;

 using System.Collections.Generic;

 using System.Linq;

 using System.Text;



class Employee

{

    private string fName = string.Empty;

    Private string lName = string.Empty;



    public string FirstName

    {

        get

        {

            return fName;

        }

        set

        {

            fName = value;

        }

    }



    public string LastName

    {

        get

        {

            return lName;

        }

        set

        {

            lName = value;

        }

    }

    // Here take FullName is as a virtual

    public virtual string FullName

    {

        get

        {

            return fName + ", " + lName;

        }

    }

}



class Company : Employee

{

    // Overiding the FullName virtual property derived from employee class

    Public override string FullName

    {

        get

        {

            return "Mr. " + FirstName + " " + LastName;

        }

    }

}



class Main

{

    public static void Main()

    {

        Company CompanyObj = new Company();

        CompanyObj.FirstName = "Satish";

        CompanyObj.LastName = "Reddy";

        Console.WriteLine("Employee Full Name is : " + CompanyObj.FullName);

    }

}


Explain about abstract property. Give an example?
Posted by: Tripati_tutu
A property with abstract keyword is considered as abstract property. An abstract property cannot have any implementation in the class. In derived classes you must have to write their own implementation.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



abstract class Employee

{

    private string fName = string.Empty;

    private string lName = string.Empty;



    public string FirstName

    {

        get   

        {

            return fName;

        }

        set

        {

            fName = value;

        }

    }



    public string LastName

    {

        get

        {

            return lName;

        }

        set

        {

            lName = value;

        }

    }

}



// FullName is abstract



    public abstract string FullName

    {

         get;

    }

}



class Company: Employee

{

    // Overiding the FullName abstract property derived from employee class

    public override string FullName

    {

        get

        {

            return "Mr. " + FirstName + " " + LastName;

        }

    }

}



class Main

{

    public static void Main()

    {

        Company CompanyObj = new Company();

        CompanyObj.FirstName = "Satish";

        CompanyObj.LastName = "Reddy";

        Console.WriteLine("Employee Full Name is : " + CompanyObj.FullName);

    }

}


Is it possible to instantiate a struct without using a new operator and can a struct inherit from another struct or class in C#?
Posted by: Tripati_tutu
Yes, it is possible to instantiate a struct without using a new operator.
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 and what's the type of struct in C#?
Posted by: Tripati_tutu
Yes, the struct can be inherited from an interface and the structs are value types.

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

Mention two cases where static constructors can be used?
Posted by: Tripati_tutu
• When the class is using a log file and the constructor is used to write data and enters into the file then we can use static constructor.

• It is also useful to call the LoadLibrary method by using constructors and when creating wrapper classes for unmanaged code.

Can a class have static constructor?
Posted by: Tripati_tutu
Yes, a class can have static constructor. Static constructors are called before when any static fields are executed. These are used to initialize static class members and called automatically before the first instance is created or any static members are referenced. This is also known as before instance constructor. Below is one example of above described theory.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace SampApp

{

    class Sample

    {

        static int i;

        static Sample()

        {

            i = 10;

            Console.WriteLine("In Static Constructor");

        }

        public Sample()

        {

            Console.WriteLine("In Instance Constructor");

        }

        public static void Main()

        {

            Sample s = new Sample();

        }

    }

}


What’s the C# syntax to catch any possible exception?
Posted by: Mahesh@emdsys.com
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

Write an equivalent of exit() for quitting a C# .NET application?
Posted by: Tripati_tutu
Yes, in case of windows forms application you can exit the application with the help of System.Environment.Exit(datatype exitCode) or Application.Exit().

Where the global assembly cache located on the system?
Posted by: Tripati_tutu
Usually the global assembly cache located at C:\winnt\assembly or C:\windows\assembly.

Where the shared assemblies stored?
Posted by: Tripati_tutu
The shared assemblies are stored in Global assembly cache.

What is properties? What are the different types of properties?
Posted by: Vpramodg
Properties provides the facility to protect a field in a class by reading and writing to it through a feature called properties.

Read / Write Property .
Read - Only Property .
Write - Only Property.
...................................................................
Write the different components of LINQ (Language Integrated Query) and state the purpose of LINQ Providers in LINQ?
Posted by: Tripati_tutu
The three components of LINQ are
• Standard Query Operators
• Language Extensions
• LINQ Providers

The LINQ Providers are set of classes which take a LINQ query and it dynamically generates a method that executes its corresponding query against particular data source.

How can you implement Standard Query Operators in LINQ?
Posted by: Tripati_tutu
These are implemented in LINQ as extension methods in .NET Framework. This can be used to work with any collection of objects that implements the IEnumerable interface. The inherited classes from the IEnumerable interface provide an enumerator for repeating over a collection of a specific type. All most all arrays and generic collection classes implementing IEnumerable interface.

What is the use of Standard Query Operators in LINQ?
Posted by: Tripati_tutu
Basically these are used in LINQ to work with collections for the following...
• To get total count of elements in a collection.
• To order the results of a collection.
• For grouping.
• For computing average.
• To join two collections based on matching keys.
• To filter the results

How you create partial methods?
Posted by: Tripati_tutu
To create a partial method we have to declare two parts that is definition or we can say declaration and the implementation. Here the implementation is optional i.e. when it is not declared then all calls to the method are removed at compile time. So that the code in partial class can freely use partial method even if implementation is not provided. If implementation is not declared then the compiler will define the declaration and will call to the methods.

Following points to keep when creating partial methods…

• The declaration of Partial method must begin with a partial keyword.
• The return type of a partial method must be void.
• Partial methods can have ref parameters but not the out parameters.
• The default type of Partial method is private, and it cannot be virtual.
• Partial methods cannot be extern, because it determines whether they are defining or implementing.

Can you inherit different parts of a partial class from different interfaces and is it possible to create partial delegates and enumerations?
Posted by: Tripati_tutu
Yes, the different parts of a partial class can be inherited from different interfaces and you cannot create any partial delegates and enumerations for a partial class.

Show how you specify nested classes as partial classes with example?
Posted by: Tripati_tutu
The nested classes can be specified as a partial class even if the containing class is not partial. Below is one example.

class ClsContainer

{

     public partial class Nested

     {

         void App1() { }

     }



     public partial class Nested

     {

         void App2() { }

     }

}


Can a nested class access the outer class? Give an example?
Posted by: Tripati_tutu
Yes, the nested class or inner class can access the outer class. Nested types can access private and protected members of the containing type, including inherited private or protected members.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace Nested

{

    class ClsContainer

    {

         string outerClsVariable = "This is outer class variable";



         public class InnerClass

         {

              ClsContainer Obj = new ClsContainer();

              string innerClsVariable = "This is inner class variable";



              public InnerClass()

              {

                   Console.WriteLine(Obj.outerClsVariable);

                   Console.WriteLine(this.innerClsVariable);

              }

         }

    }

  

    class Exec

    {

        public static void Main()

        {

            ClsContainer.InnerClass nestedClsObj = new ClsContainer.InnerClass();

         }

     }

}


What is the difference between method parameters and method arguments? Give an example?
Posted by: Tripati_tutu
The method parameters are passed as an argument for a method but the method arguments are itself having a value. The method definition specifies the name and type of any parameters that are required. The arguments must be compatible with the parameter type but the argument name used in the calling code does not have to be the same as the parameter named defined in the method.
In the below example FNum and SNum are method parameters and N1 and N2 are method arguments.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace Sample

{

    class Program

    {

        public static void Main()

        {

            int N1 = 10;

            int N2 = 20;

            //N1 and N2 are method arguments

            int Total = Sum(N1, N2);

            Console.WriteLine(Total);

        }



        //FNum and SNum are method parameters

        public static int Sum(int FNum, int SNum)

        {

            int Sum = FNum + SNum;

            return Sum;

        }

    }

}


Can you pass value types by reference to a method?
Posted by: Tripati_tutu
Yes, you can pass value types by reference to a method. Below is one sample code snippet to have clear idea.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace Sample

{

    class Program

    {

        public static void Main()

        {

            int a = 10;

            Console.WriteLine("Value of a before passing to the method = " + a);

            Function(ref a);

            Console.WriteLine("Value of a after passing to the method by reference= " + a);

         }

         public static void Function(ref int Num)

         {

             Num = Num + 5;

         }

     }

}


What is the difference between a constant and a static readonly field?
Posted by: Tripati_tutu
A static readonly field is very much similar as constant, but the difference is the C# compiler does not have access to the value of a static readonly field at compile time. It will access only at run time.

What are the advantages of using Properties in C#.Net?
Posted by: Tripati_tutu
The advantages of using properties are:

• Before allowing a change in data, the properties can validate the data.
• Properties can evidently make visible of data on a class from where that data is actually retrieved such as a database.
• Properties can also provide events when data is changed, such as raising an event or changing the value of other fields.

What do you mean by static property? Give an example?
Posted by: Tripati_tutu
A property with a static keyword is considered as static property. This makes the property available to access at any time, even if no instance of the class exists. Below is the example for a static property.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



class Value

{

     private static int i = 3;

     public static int i

     {

         et

         {

             return i;

         }

     }

}



class Main

{

    public static void Main()

    {

        Console.WriteLine(Value.i);

    }

}
...................................................................
When does GarbageCollector runs ?
Posted by: Chvrsri
Garbage Collector runs :

1. When the system has low physical memory
2. Acceptable memory heap is increased.
3. GC.Collect method is called.

When to use Public and Private access modifiers
Posted by: Poster
Using proper access modifiers is the key of writing good Object Oriented Programming.

Below are few of the points that should be taken care while using Public and Private access modifiers

Private
1. A member that are used within a class should be private.
2. If you are refactoring a lengthy method in a class, the re-factored method should be declared as private as you are not intending to reuse that method again.
3. Any member that has some sensitive information or calculations should be controlled by using private and it should be exposed properly through a public member.

Public
1. Frequently used methods should be public.
2. The methods of different layers that are intended to pass data between layers should be declared as public.
3. Generally properties in C# is declared as public as it is intended to use by anyone.
4. Method that gets and sets the value of private data should be public. (For example, Properties)

Define different Access modifiers in C#
Posted by: Poster
The access modifier is the key of Object Oriented Programming, to promote encapsulation, a type in C# should limit its accessibility and this accessibility limit are specified using Access modifiers.

They are - Public, Internal, Protected, Private, Protected Internal

Public:
When used that type (method or variable) can be used by any code throughout the project without any limitation. This is the widest access given to any type and we should use it very judiciously. By default, enumerations and interface has this accessibility.

Internal
When used that type can be used only within the assembly or a friend assembly (provided accessibility is specified using InternalVisibleTo attribute). Here assembly means a .dll.
For example if you have a .dll for a Data Access Layer project and you have declared a method as internal, you will not be able to use that method in the business access layer)
Similarly, if you have a website (not web application) and you have declared internal method in a class file under App_Code then you will not be able to use that method to another class as all classes in website is compiled as a separate .dll when first time it is called).

Internal is more limited than Public.

Protected
When used that type will be visible only within that type or sub type. For example, if you have a aspx page and you want to declare a variable in the code behind and use it in aspx paeg, you will need to declare that variable as at least protected (private will not work) as code behind file is inherited (subclass) by the aspx page.

Protected is more secure than Internal.

Private
When used that type will be visible only within containing type. Default access modifier for methods, variables. For example, if you have declared a variable inside a method, that will be a private variable and may not be accessible outside that method.

Private is the most secure modifiers than any other access modifiers as it is not accessible outside.

Protected Internal
This is not a different type of access modifiers but union of protected and internal. When used this type will be accessible within class or subclass and within the assembly.

What is MultiCast Delegate ?
Posted by: Chvrsri
A single or uni cast delegate can be instantiated by only a single method . when a Delegatee can make use of more than one method then it is said to be Multicast Delegate.

What for using System.Logging namespace is used ?
Posted by: Chvrsri
It is used to track the info about , when the particualt application got errorsome. It helps to redirect to the developer inorder to correct those.

Explain the states of a window service application?
Posted by: Tripati_tutu
a. Running: Normal operation occurs during this stage.
b. Paused: The service cannot perform anything beyond till the paused state is changed.
c. Stopped: In this, the service will not work until the service is started once again.
d. Pending: Running is the stage which comes after Pending. Its like waiting for something to run.

Explain what are the types of window services?
Posted by: Tripati_tutu
There are two types of windows services. Those are Win32OwnProcess , Win32ShareProcess .

a. Win32OwnProcess: It is a Win32 process that can be started by the Service Controller. This type of Win32 service runs in a process by itself.+

b. Win32ShareProcess: It is a Win32 service that allows sharing of processes with other Win32 services.

What are the Integer Type Supported by c#?
Posted by: Vpramodg
1.sbyte -8 bit signed integer
2.short -16 bit signed integer
3.int -32 bit signed integer
4.long -64 bit signed integer
5.byte -8 bit unsigned integer
6.ushort -16 bit unsigned integer
7.uint -32 bit unsigned integer
8.ulong -64 bit unsigned integer

When inheriting from a base class, whether the derived class inherits the destructor and constructor from the base class?
Posted by: Santosh.impossible
No, On inheriting from a base class the derived class inherits the only the members - including the code except the destructor and constructor of the base class.

What are Generics?
Posted by: Poster
Generics means parametrized types. A class, structure, interface, delegates that operates on a parametrized type is called generics.

The ability to create type-safe code in which type-mismatch errors are caught at compile time rather than run time is the key advantage of the Generics. So using generics on the class, interface, methods or delegates avoids run time errors as it is caught at the compile time itself.

In order to use Generics, we need to work with System.Collections.Generic namespace.

IList<>, IEnumerable, IEnuerator<>, IComparer<>, ICollection<> and IDictionary are some of the frequently used generics objects.

Write the syntax of foreach loop with hashtable and get the key, value pair from the hashtable?
Posted by: Peermohamedmydeen
HashTable ht = new HashTable();
ht.Add(1,"A");
ht.Add(2,"B");
ht.Add(3,"C");

foreach(DictionaryEntry de in ht)
{
Console.WriteLine(string.Format("Key : {0} Value: {1}", de.Key.ToString(),de.Value.ToString()));

}

What is Closed constructed type and Open constructed type?
Posted by: Poster
Closed constructed type and open constructed type is term that is used while instantiated an object.

For exmaple

class myClassO<T>

{



}

Class MyClassC<int>

{



}



In above code class myClassO is the open constructed type as we can pass any type of parameter while instantiating the myClassO object.

myClassO<int> i = new myClassO<int>(20); // Correct

myClassO<string> i = new myClassO<strubg>('my string"); // Correct


You can notice that I can pass either integer or string in the myClassO insntiation as this is the generic class.

myClassC is the closed constructed type as I have specified the type of argument to be passed in the myClassC instantiation.

myClassC<int> i = new myClassC<int>(20); // Correct

myClassC<string> i = new myClassC<strubg>('my string"); // InCorrect
.................................................................
Example for Compile time Polymorphism and Example for Run time Polymorphism?
Posted by: Peermohamedmydeen
Example of Compile Time Polymorphism - Method Overloading
Example of Run Time Polymorphism - Method Overriding

Why C# is called Strongly Typed Language?
Posted by: Poster
C# is called Strongly Typed Language becausen its type rules are very strict. For example you can't called a function that is designed to call Integer with a string or decimal. If you want to do so then you will have to explicitly convert them to integer.

String is a Class then why can't you create a object for the string like this String str = new String();
Posted by: Esakkriajak
Since String is sealed class we can't create object for it.

Explain About ref and out parameters?
Posted by: BangaruBabu
ref parameter:
Ref is keyword.
it must be used along with actual and formal arguments.
ref variables must be initialized before passing to a function

out parameter:
It is very similar to call by Reference.
Out is a Keyword.
Which must be used along with actual and formal arguments.
Out variables are not require to initialize, the initialized value will not be passed, only reference will be passed.

Some facts about Virtual methods.
Posted by: Raja
Virtual keyword is used to declare a method inside the base class that can be overridden.

Following conditions are applied to a virtual method

1. Virtual method can not be declared as Private
2. Virtual method can not be declared as Static
3. Virtual method may or may not be overridden.
4. In order to override the virtual method of the base class, Override keyword is used provided the method signature of the derived class is same as base class, even the access modifier should be same.
5. A Virtual method must contain the method body otherwise compiler shall throw error.
6. Virtual keyword is only used in base and derived class scenario where you want your method over-ridable in the derived class.

Enjoy virtual keyword :)

What is the difference between IQueryable<T> and IEnumerable<T> interface?
Posted by: Raja
IEnumerable<T>
IEnumerable<T> is best suitable for working with in-memory collection.
IEnumerable<T> doesn't move between items, it is forward only collection.

IQueryable<T>
IQueryable<T> best suits for remote data source, like a database or web service.
IQueryable<T> is a very powerful feature that enables a variety of interesting deferred execution scenarios (like paging and composition based queries).

So when you have to simply iterate through the in-memory collection, use IEnumerable<T>, if you need to do any manipulation with the collection like Dataset and other data sources, use IQueryable<T>.

Please let me know your feedback, if any

Can we declare a class as Protected?
Posted by: Poster
No, a class can not be declared as Protected.

A class can be declared with only following access modifiers.

Abstract
Internal
Public
Sealed
Static
Extern (The extern modifier is used to declare a method that is implemented externally. - http://msdn.microsoft.com/en-us/library/e59b22c5(VS.80).aspx)

Thanks

Can we inherit a private class into the public class?
Posted by: Poster
No, In C#, a derived class can’t be more accessible than it’s base class. It means that you can't inherit a private class into a public class. So always the base class should be more or equal accessible than a derived class.

// Following will throw compilation error

private class BaseClass

{

}

public class DerivedClass : BaseClass

{

}



// Following will compile without an error

public class BaseClass

{

}

public class DerivedClass : BaseClass

{

}



Hope this helps

Does Abstract classes contain Constructor?
Posted by: G_arora
NOTE: This is objective type question, Please click question title for correct answer.

what is the class used for dealing with graphics objects
Posted by: Puneet20884
System.Drawing.Graphics is the class used for dealing with graphics objects

Name any two "Permission Classes" generally used while working with CAS ?
Posted by: Puneet20884
1) FileIOPermission
2) UIPermission
3) SecurityPermission

Write a way to read an image from a path to a bitmap object
Posted by: Puneet20884
We can directly read an image file and load it into a Bitmap object as below.

Bitmap myBmpObj = Bitmap.FromFile(strPath);



We can also set Image path during the Initilization of Bitmap Object. Code as given below.

Bitmap loBMP = new Bitmap(strPath);
..................................................................
How we can gt the values of control on the previous page in case od server.transfer method?
Posted by: Lakhangarg
Using Page.PreviousPage.FindControl() method.

Can we use Page.PreviousPage to get the value of controls of the previous page in case of response.Redirect ?
Posted by: Lakhangarg
No, we can't use PreviousPage to find the control on previous page with response.redirect.

What is the page size in SQL Server?
Posted by: Lakhangarg
8 KB -- > 8192
you can check this with the query :
SELECT low FROM master..spt_values WHERE number = 1 AND type = 'E'

What is the main difference between RegisterStartUpScript and RegisterClientScriptBlock?
Posted by: Lakhangarg
RegisterStartUpScript Add the javascript code at the end of the page before the closing of form tag. while RegisterClientScriptBlock place the code at th top of the page.

Which methods are used to execute javascript code from code behind file?
Posted by: Lakhangarg
RegisterStartupScript and RegisterClientScriptBlock

If i will write a piece of code in finaly block, will it execute if there is an exception in try block.
Posted by: Lakhangarg
Yes, the code in finally block will execute.

Why 'static' keyword is used before Main()?
Posted by: Abhisek
Program execution starts from Main(). S it should be called before the creation of any object. By using static the Main() can now be called directly through the class name and there is no need to create the object to call it. So Main() is declared as static.

What is CharEnumerator in C#?
Posted by: Raja
CharEnumerator is an object in C# that can be used to enumerate through all the characters of a string. Below is the sample to do that


string str = "my name";

CharEnumerator chs = str.GetEnumerator();

        while(chs.MoveNext())

        {

            Response.Write(chs.Current);

        }



Moderator: please do not move this to Code section, this is a typical interview question that was asked :)

I would like to find all the directories of a folder How should I achieve this?
Posted by: Nishithraj
By Directory.GetDirectories method

Tell me one reason for dotnet doesn't have multiple inheritance
Posted by: Nishithraj
To avoid ambiguity and deadlocks

How can you check a nullable variable is assigned?
Posted by: Nishithraj
using hasvalue method

what is the syntax of a nullable variable?
Posted by: Nishithraj
Nullable myval=null;
...................................................................
I would like to check a variable as assigned or not. How can we do that?
Posted by: Nishithraj
Declare the variable as Nullable

What are the different compiler generated methods when a .NET delegate is compiled?
Posted by: Abhisek
Compilation of a .NET delegate results in a sealed class with three compiler generated methods whose parameters and return values are dependent on the delegate declaration. The methods are,
Invoke()
BeginInvoke() and
EndInvoke().

When TimerCallback delegate is used?
Posted by: Abhisek
Many application have the need to call a specific method during regular intervals. For such situations we can use the System.Threading.Timer type in conjunction with a related delegate named TimerCallback.

Which enumeration defines different PenCap in C#?
Posted by: Abhisek
LineCap enumeration which defines different pen cap styles as follows,

public enum LineCap

{

Flat, Square, Round, Triangle, NoAncher, SquareAnchor,

RoundAnchor, DiamondAnchor, ArrowAnchor, AnchorMask, Custom

}


What is the use of param keyword in C#?
Posted by: Abhisek
In C# param parameter allows us to create a method that may be sent to a set of identically typed arguments as a single logical parameter.

Which class defines different events for controls in C#?
Posted by: Abhisek
The "Control" class defines a number of events that are common to many controls.

What do you mean by properties in C#?
Posted by: Abhisek
Property acts as a cross link between the field and the method . Actually it behaves as a field. We can retrieve and store data from the field using property.

The compiler automatically translates the field like property into a call like special method called as 'accessor" . In property there are two accessor and that are used to save value and retrieve value from the field. The two properties are 'get' and 'set'.

The get property is used to retrieve a value from the field and the set property is used to assign a value to a field .

Depending on there use properties are categorised into three types,

ReadWrite Property :- When both get and set properties are present it is called as ReadWrite Property.

ReadOnly Property :- When there is only get accessor it is called as ReadOnly Property.

WriteOnly Property :- When there is only set accessor, it is called as WriteOnly Property.

What are the different method parameter modifiers in C#?
Posted by: Abhisek
out
ref
params

What are the different Iteration Constructs in C#?
Posted by: Abhisek
for loop
foreach/in loop
while loop
do/while loop

What is the use of ?? operator in C#?
Posted by: Abhisek
This operator allows you to assign a value to a nullable type if the retrieved value is in fact null.

What is the CIL representation of implicit and explicit keywords in C#?
Posted by: Abhisek
The CIL representation is op_Implicit and op_Explicit respectively.

Which operators in C# provides automatic detection of arithmetic overflow and underflow conditions?
Posted by: Abhisek
'checked' and 'unchecked' keywords provide automatic detection of arithmetic overflow and underflow conditions.
...................................................................
What is the use of stackalloc keyword in C#?
Posted by: Abhisek
In an unsafe context it is used to allocate C# array directly on the stack.

Which keyword in C# is used to temporarily fix a variable so that its address may be found?
Posted by: Abhisek
fixed keyword

What are the different C# preprocessor directives?
Posted by: Abhisek
#region , #endregion :- Used to mark sections of code that can be collapsed.

#define , #undef :-Used to define and undefine conditional compilation symbols.

#if , #elif , #else , #endif :- These are used to conditionally skip sections of source code.

What is the use of GetInvocationList() in C# delegates?
Posted by: Abhisek
GetInvocationList() returns an array of System.Delegate types, each representing a particular method that may be invoked.

C# delegate keyword is derived form which namespace?
Posted by: Abhisek
C# delegate keyword is derived form System.MulticastDelegate.

What will be the length of string type variable which is just declared but not assigned any value?
Posted by: Virendradugar
As variable is not initialized and it is of reference type. So it's length will be null and it will throw a run time exception of "System.NullReferenceException" type, if used.

How do we retrieve day, month and year from the datetime value in C#?
Posted by: Nishithraj
Using the methods Day,Month and Year as follows

int day = dobDate.Day;

int month = dobDate.Month;i

nt year = dobDate.Year;


I need to restrict a class by creating only one object throughout the application. How can I achieve this?
Posted by: Nishithraj
We can declare the constructor of the class as either protected or as private

int? d = 1; Type testType = d.GetType(); will result…
   1. System.Int64
   2. System.Int16
   3. System.Int32(answer)
   4. System.nullable<Int32>
How can you make your machine shutdown from your program?
Posted by: Bhakti
Process.Start("shutdown", "-s -f -t 0");

What is the use of unsafe keyword in C#?
Posted by: Abhisek
In C# the value can be directly referenced to a variable, so there is no need of pointer. Use of pointer sometime crashes the application. But C# supports pointer, that means we can use pointer in C#.

The use of pointer in C# is defined as a unsafe code. So if we want to use pointer in C# the pointer must be present in the body of unsafe declaration. But pointer does not come under garbage collection.

Example:-

unsafe
{
int a, *b;
a = 25;
b = &a;
Console.WriteLine("b= {0}",b);//returns b= 25
}

What is difference between var and Dynamic ?
Posted by: Bhakti
Var word was introduced with C#3.5(specifically for LINQ) while dynamic is introduced in C#4.0. variables declared with var keyword will get compiled and you can have all its related methods by intellisense while variables declared with dynamic keyword will never get compiled. All the exceptions related to dynamic type variables can only be caught at runtime.
...................................................................
What is dynamic keyword ?
Posted by: Bhakti
Its newly introduced keyword of C#4.0. To indicate that all operations will be performed runtime.

What will happen if you declare a variable named "checked" with any data type?
Posted by: Virendradugar
Compiler will throw an error as checked is a keyword in C# So It cannot be used as variable name. Checked keyword is used to check the overflow arithmetic checking.

What are anonymous methods?
Posted by: Bhakti
Anonymous methods are another way to declare delegates with inline code except named methods.

Restrictions of yield in try-catch.
Posted by: Bhakti
While using yield keyword, mainly two restrictions are observed.
First is , we can’t use yield in finally.
Second is , we can’t place yield keyword in the catch block if try contains more than one catch blocks.

With yield break statement, control gets …
   1. Out side iterator
   2. Move next method of iterator(answer)
   3. As specified by user
   4. Stops further execution.




What first action compiler will take on detection of iterator ?
Posted by: Bhakti
As soon as compiler will detect iterator, it will automatically generate current, MoveNext and Disposemethods of the IEnumerator or IEnumerator(T) type.

What is obsolete method?
Posted by: Virendradugar
Obsolete means old or no longer in use. We can define a method as obsolete using Obsolete keyword/attribute.

[Obsolete]

public int Fun1()

{



//Code goes here.



}



or

[Obsolete("Any user define message")] public int Fun1()

{



//Code goes here..



}



One thing to note here is O is always capital in Obsolete.

Can you have different access modifiers on the get/set methods of a property in C#?
Posted by: Virendradugar
No. it's not possible. The access specifier has to be same for get and set.

What is optional and named parameter in C#4.0?
Posted by: Bhakti
Optional parameter allows omitting arguments to function while named parameters allow passing arguments by parameter name.
By declaring below variable you are assigning default values to second and third parameter of 2 and 3 respectively (param2 and param3).
public void optionalParam(int Param1, int param2 = 2, int param3 = 3);

After this you can write,
optionalParam(1); //which will be equivalent to optionalParam(1,2,3);

Sometimes, you may need to not to pass param2. But, optionalParam(1,,3) is not valid statement with C#. At this point, named parameter comes to the picture.

You can specify arguments like,
optionalParam(1, param3:10); //which will be equivalent to
optionalParam(1,2,10);

What is the difference between a.Equals(b) and a == b?
Posted by: Chikul
For value types : “==” and Equals() works same way : Compare two objects by VALUE
Example:
int i = 5;
int k= 5;
i == k > True
i.Equals(k) > True

For reference types : both works differently :
“==” compares reference – returns true if and only if both references point to the SAME object while
"Equals" method compares object by VALUE and it will return true if the references refers object which are equivalent
Example:
StringBuilder sb1 = new StringBuilder(“Mahesh”);
StringBuilder sb2 = new StringBuilder(“Mahesh”);
sb1 == sb2 > False
sb1.Equals(sb2) > True

But now look at following issue:
String s1 = “Mahesh”;
String s2 = “Mahesh”;
In above case the results will be,
s1 == s2 > True
s1.Equals(s2) > True
String is actually reference type : its a sequence of “Char” and its also immutable but as you saw above, it will behave like Value Types in this case.
Exceptions are always there ;)

Now another interesting case:
int i = 0;
byte b = 0;
i == b > True
i.Equals(b) > False
So, it means Equals method compare not only value but it compares TYPE also in Value Types.

Recommendation :
For value types: use “==”
For reference types: use Equals method.

What is the difference between Parse and TryParse method?
Posted by: Virendradugar
Parse method is used to parse any value to specified data type.

For example

string test = "42";
int32 Result;
Result = Int32.Parse(test);

This will work fine bt what if when you are aware about the value of string variable test.

if test="abc"....

In that case if u try to use above method, .NET will throw an exception as you are trying to convert string data to integer.

TryParse is a good method if the string you are converting to an interger is not always numeric.

if(!Int32.TryParse(test,out iResult))
{
//do something
}


The TryParse method returns a boolean to denote whether the conversion has been successfull or not, and returns the converted value through an out parameter.

**declare variable iResult of Int32.

Can we define generics for any class?
Posted by: Indianengg84
No, generics is not supported for the classes which deos not inherits collect class.
..................................................................
Which method is used to return an item from the Top of the Stack?
   1. Push()
   2. Enqueue()
   3. Dequeue()
   4. Pop()(answer)

Which method is used to reads and removes an item from the head of the Queue.
   1. Dequeue()(answer)
   2. Enqueue()
   3. Pop()
   4. Peek()



Whcih method is used to add an Item on stack?
   1. Push()(answer)
   2. Enqueue()
   3. Pop()
   4. Peek()




Give Some Examples of Generic Classes?
Posted by: Syedshakeer
List<T>,Queue<T>,Stack<T>,LinkedList<T>,HashSet<T>

A Queue is a collection where elements are processed in
   1. First in First Out(FIFO)(answer)
   2. Last In First Out(LIFO)
   3. 1) and 2)
   4. None



Which method is used to add an Item to the end of the Queue?
   1. Enqueue()(answer)
   2. Dequeue()
   3. Peek()
   4. Push()



The Items that is put in the Queue is Reads ?
   1. First(answer)
   2. Last
   3. 1) and 2)
   4.




Stack is collection where elements are processed in
   1. Last In First Out(answer)
   2. First In First Out
   3. 1) and 2)
   4. None
Can we declare an array variable with var keyword in C# 3.0?
Posted by: Raja
No, var keyword is used to declare implicitly typed local variable. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

So you can declare a local variable of any type using var keyword but you can't declare an array of variable using var keyword.

Correct

 string[] str = { "ram", "sham" };

        foreach (var s in str)

        {



            Response.Write(s + "<br />");

        }




Wrong

var[] str = { "ram", "sham" };

        foreach (var s in str)

        {



            Response.Write(s + "<br />");

        }



This will throw "CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?) " error.

For more info on var keyword see http://msdn.microsoft.com/en-us/library/bb383973.aspx

Thanks

Is it possible to notify application when item is removed from cache ?
Posted by: Bhakti
Yes.
You can use CacheItemRemovedCallback delegate defining signature for event handler to call when item is removed from cache.

For an example:

HttpRuntime.Cache.Insert(

            "CacheItem1", //insert cache item

            "",

            null,

            Cache.NoAbsoluteExpiration,

            new TimeSpan(0, 0, 15),

            CacheItemPriority.Default,

            new CacheItemRemovedCallback(RemovalMethod)); //define method which needs to be called when item is removed from cache



the method will be like,


private static string RemovedAt = string.Empty;

    public static void RemovalMethod(String key, object value, //method is declared static so that it can be available when cache item is deleted

        CacheItemRemovedReason removedReason)

    {

       RemovedAt = "Cache Item Removed at:  " + DateTime.Now.ToString(); //Shows the time when cache item was removed

     }


How can you cache Multiple Versions of a Page?
Posted by: Bhakti
Using output cache you can cache multiple versions of the page.

We can either use,…
- @ OutputCache directive at design time declaratively for Declarative Approach
OR
- Response.Cacheclass at runtime for Programmatic Approach.

With @ OutputCache directive four parameters of VaryByParam , VaryByControl, VaryByHeader, VaryByCustom allows user to cache page depending on query string, control value, request's HTTP header, request's HTTP header respectively.
For an example:

To turn off caching,
Declarative Approach:

<%@ OutputCache Location="None" VaryByParam="None" %>


Programmatic Approach:

Response.Cache.SetCacheability(HttpCacheability.NoCache);



To cache the output for each HTTP request that arrives with a different ID:
Declarative Approach:

<%@ OutputCache duration="60" varybyparam=" ID" %>


Programmatic Approach:

Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));

Response.Cache.SetCacheability(HttpCacheability.Public);

Response.Cache.VaryByParams["ID"] = true;


You have to make user to enter just integer values with TextBox. Can you do this with CompareValidator?
Posted by: Bhakti
Yes. With the validator control, you need to set type attribute to the desired datatype which in this case is “Integer” and Operator to DataTypeCheck.

<asp:CompareValidator ID="CompareValidator1" ControlToValidate="TextBox1" Type="Integer" Operator="DataTypeCheck"

            runat="server" ErrorMessage="CompareValidator"></asp:CompareValidator>
..................................................................
How to Find Number of Days for provided date range?
Posted by: Bhakti
Code extract :

TimeSpan DayDifference = Convert.ToDateTime("2009-1-7").Subtract(Convert.ToDateTime("2009-1-1"));



To find the difference of the days, here we have used Subtract method. The Subtract method does not take start date into consideration. Hence, to get the exact number of days for the date range we need to add one more day to the result.

Response.Write("Number of Days : " + DayDifference.Days+1);

Can we throw exception from catch block ?
Posted by: Bhakti
Yes.
The exceptions which cant be handled in the defined catch block are thrown to its caller.

Which namespace is used to work with RegularExpression in C#?
Posted by: Raja
NOTE: This is objective type question, Please click question title for correct answer.

What Will be the output of the following Code? int i = 1; int j = 1; i = i++; j = ++j; Response.Write(i.ToString() + ":" + j.ToString());
Posted by: Lakhangarg
NOTE: This is objective type question, Please click question title for correct answer.

An array is fixed length type that can store group of objects.
Posted by: Syedshakeer
NOTE: This is objective type question, Please click question title for correct answer.

Can you store multiple datatypes in an Array?
Posted by: Syedshakeer
NOTE: This is objective type question, Please click question title for correct answer.

Which keyword is used to prevent one class from being inherited by another class in C#
Posted by: Syedshakeer
NOTE: This is objective type question, Please click question title for correct answer.

In this Sample Code which catch block will be executed? try { int j=10; try { int i=10; j=j-i; j=i/j; } catch(Exception ex) { throw ex; } } catch(Exception ex) { throw ex; }
Posted by: Lakhangarg
NOTE: This is objective type question, Please click question title for correct answer.

A try block having 4 catch block will fire all catch block or not?
Posted by: Poster
No, A try having more than one catch block will fire the first relevant catch block after that cursor will be moved to the finally block (if exists) leaving all remaining catch blocks.

So in all cases only one catch block will fire.

Thanks

What are three test cases you should do while unit testing?
Posted by: Poster
Positive test cases
This is done with correct data to check for correct output)


Negative test cases
This is done with broken or missing data to check for proper handling

Exception test cases
This is done with exceptions (giving unexpected data or behavior) and check for the exception caught properly or not.

What debugging tools come with the .NET Framework SDK?
Posted by: Poster
CorDBG – command-line debugger

The Runtime Debugger helps tools vendors and application developers find and fix bugs in programs that target the .NET Framework common language runtime. This tool uses the runtime Debug API to provide debugging services. Developers can examine the code to learn how to use the debugging services. Currently, you can only use Cordbg.exe to debug managed code; there is no support for debugging unmanaged code. To use CorDbg, you must compile the original C# file using the /debug switch.

Click for more details http://msdn.microsoft.com/en-us/library/a6zb7c8d(VS.80).aspx

DbgCLR – graphic debugger.

The Microsoft CLR Debugger (DbgCLR.exe) provides debugging services with a graphical interface to help application developers find and fix bugs in programs that target the common language runtime. The CLR Debugger, and the accompanying documentation, is based on work being done for the Microsoft Visual Studio 2005 Debugger. As a result, the documentation refers mostly to the Visual Studio Debugger, rather than the CLR Debugger. In most cases, the information is applicable to both debuggers. However, you will find sections of the documentation describing some features that are not implemented in the CLR Debugger (see the next paragraph). You can simply ignore these features and sections.

Here are some of the main differences between the CLR Debugger and the Visual Studio Debugger as described in the documentation:

* The CLR Debugger does not support the debugging of Win32 native code applications. Only applications written and compiled for the common language runtime can be debugged with the CLR Debugger.

* Remote debugging is not implemented in the CLR Debugger.

* The Registers window is implemented in the CLR Debugger, but no register information appears in the window. Other operations that involve registers or pseudoregisters, such as displaying or changing a register value, are not supported. For more information see, How to: Use the Registers Window.

* The Disassembly window is implemented in the CLR Debugger but shows the disassembly code that would be generated for the application if it were compiled as Win32 native code rather than common language runtime code. For more information see, How to: Use the Disassembly Window.

* The CLR Debugger does not support F1 help.

* The CLR Debugger does not support the Autos window feature.

Click for more details http://msdn.microsoft.com/en-us/library/7zxbks7z(VS.80).aspx

Which of the following class does not belong to Collection namespace ?
   1. ArrayList
   2. Queue
   3. DictionaryList(answer)
   4. Stack

# What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

# Can you store multiple data types in System.Array? No.
# What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.
# How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
# What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.
# What’s class SortedList underneath? A sorted HashTable.
# Will finally block get executed if the exception had not occurred? Yes.
# What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
# Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
# Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
# What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
# What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods.
# How’s the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
# What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
# What’s a satellite assembly? When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
# What namespaces are necessary to create a localized application? System.Globalization, System.Resources.
# What’s the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments.
# How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch.
# What’s the difference between <c> and <code> XML documentation tag? Single line code example and multiple-line code example.
# Is XML case-sensitive? Yes, so <Student> and <student> are different elements.
# What debugging tools come with the .NET SDK? CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
# What does the This window show in the debugger? It points to the object that’s pointed to by this reference. Object’s instance data is shown.
# What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
# What’s the difference between the Debug class and Trace class? Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.
# Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing 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? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
# Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
# Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
# What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
# What’s the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed.
# What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
# Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).
# What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
# Which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
# Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications.
# What does the parameter Initial Catalog define inside Connection String? The database name to connect to.
# What’s the data provider name to connect to Access database? Microsoft.Access.
# What does Dispose method do with the connection object? Deletes it from the memory.
# What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.







1) Can we have private constructor? when can I use them?

2) what is an internal specifier? what happens internally when I use access specifier Internal ?

3) DO we have inline function in C#? otherwise what is equivalent inline function in C#?

1. Explain the differences between Server-side and Client-side code?

ANS: Server side code will execute at server end all the business logic will execute at server end where as client side code will execute at client side at browser end.

2. What type of code (server or client) is found in a Code-Behind class?

ANS : Server side.

3. Should validation (did the user enter a real date) occur server-side or client-side? Why?

ANS : client side . there is no need to go to validate user input. If it relates to data base validation we need to validate at server side.

4. What does the “EnableViewState” property do? Why would I want it on or off?

ANS: IT keeps the data of the control during post backs.
if we turn off the values should not populate during server round trip.

5. What is the difference between Server.Transfer and
Response.Redirect? Why would I choose one over the other?

ANS: Server.Trnasfer will prevent round trip. it will redirect pages which or in the same directory. NO way to pass the query strings . Thru http context we can able to get the previous page control values.

Response.Redirect : There is a round trip to process the request. We can redirect to any page external / internal other than aspx. We can pass the query string thru which we can manage sessions.

6. Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component

ANS : Web services are best suite for Hetrogenious environment.
Remoting is best suite for Homogenious environment. The systems that under CLR.

7. Let’s say I have an existing application written using Visual Studio 6 (VB 6, InterDev 6) and this application utilizes Windows 2000 COM+ transaction services. How would you approach migrating this
application to .NET

We need to have Wrapper to communicate COM components in .net. and vis versa

CCW : Com Callable wrapper.
RCW : RUN time callable wrapper.

8. Can you explain the difference between an ADO.NET Dataset and anADO Recordset?\
ANS : DIsconnected architechure . Maintainace relation schemas. MUtilple table grouping.
Connected one .
9. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?

ANS: APplication_start need for global variable which are available over the application.
Sesssion_Start : login dependent ( user dependent)

10. If I’m developing an application that must accomodate multiple security levels though secure login and my ASP.NET web appplication is
spanned across three web-servers (using round-robbin load balancing)
what would be the best approach to maintain login-in state for the
users?

ANS : Database Support.
or Thru state service.

11. What are ASP.NET Web Forms? How is this technology different than what is available though ASP (1.0-3.0)?
ANS : ASP . Interprepter.. use the script engine.
ASP.Net Compiled.

12. How does VB.NET/C# achieve polymorphism?
ANS : Function overloading.
Operator overloading.
11. Can you explain what inheritance is and an example of when you might use it?

ANS : Heridity.
Use the existing functionality along with its own properities.

13. How would you implement inheritance using VB.NET/C#?
ANS: Derived Class : Basecalss
VB.NEt : Derived Class Inherits Baseclass
14. Whats an assembly
ANS : A Basic unit of executable code >

Which contains : Manifest - Meta data
versioning , Calture , IL, Reference

15. Describe the difference between inline and code behind - which is best in a loosely coupled solution

Tightly coupled - INLINE
ANS: inline function bind at compile time can write in aspx page with in <% %> .

17. Explain what a diffgram is, and a good use for one

ANS : is an xml grammer. it talk about state of node in xml file.

18. Where would you use an iHTTPModule, and what are the limitations of any approach you might take in implementing one

ANS: Preprocessing before going to IIS.

20. What are the disadvantages of viewstate/what are the benefits
ANS : IT can be hacked . page is size is heavy.

21 Describe session handling in a webfarm, how does it work and what are the limits

ANS:
Session - mode
State sever
OUtprocess
sql

22. How would you get ASP.NET running in Apache web servers - why would you even do this?

ANS: —- Install Mod_AspDotNet
Add at the end of C:\Program Files\Apache Group\Apache2\conf\httpd.conf the following lines

23. Whats MSIL, and why should my developers need an appreciation of it if at all?

ANS : Microsoft Intermeidate lanaguage. which is the out put for all the .net supported languages after comiplation will produce.
Appreciation for cross language support.

24. In what order do the events of an ASPX page execute. As a developer is it important to undertsand these events?
ANS : INIT, PageLoad, Prerender , UNload.

25. Which method do you invoke on the DataAdapter control to load your generated dataset with data?

Fill()

26. Can you edit data in the Repeater control?
NO

27. Which template must you provide, in order to display data in a Repeater control?
ITemtemplate

28. How can you provide an alternating color scheme in a Repeatercontrol?

AlternateItemTemplate

29. 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 Repeatercontrol?

Datasource,
DataBind

30. What base class do all Web Forms inherit from?

System.Web.UI.Page

31. What method do you use to explicitly kill a user s session?

abondon()

32 How do you turn off cookies for one page in your site?
disablecookies.

33. Which two properties are on every validation control?
control to validate, error message
34. What tags do you need to add within the asp:datagrid tags to bind
columns manually?
autogenerated columns is set to false
35. How do you create a permanent cookie?
Cooke = ne cookee().
cooke.adddate.

36. What tag do you use to add a hyperlink column to the DataGrid?
hyper link column

37. What is the standard you use to wrap up a call to a Web service
————
38. Which method do you use to redirect the user to another page without performing a round trip to the client?
server.transfer
39. What is the transport protocol you use to call a Web service SOAP
http
40. True or False: A Web service can only be written in .NET
false
41. What does WSDL stand for? webservice description language. it is used to generate for proxy( server object)

42. What property do you have to set to tell the grid which page to go to when using the Pager object?
Page Index.

43. Where on the Internet would you look for Web services?
UDDI
44. What tags do you need to add within the asp:datagrid tags to bind columns manually.

Auto generate columns

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

datatext
datavalue

46. How is a property designated as read-only?
get
47. Which control would you use if you needed to make sure the values in two different controls matched?
compare filed validator

48. True or False: To test a Web service you must create a windows application or Web application to consume this service?
no
49. How many classes can a single .NET DLL contain?



1. Explain the .NET architecture.
2. How many languages .NET is supporting now? - When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. The site DotNetLanguages.Net says 44 languages are supported.
3. How is .NET able to support multiple languages? - a language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation to this IL the language is not a barrier. A code can call or use a function written in another language.
4. How ASP .NET different from ASP? - Scripting is separated from the HTML, Code is compiled as a DLL, these DLLs can be executed on the server.
5. Resource Files: How to use the resource files, how to know which language to use?
6. What is smart navigation? - The cursor

position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.
7. What is view state? - The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The values are encrypted and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control
8. Explain the life cycle of an ASP .NET page.
9. How do you validate the controls in an ASP .NET page? - Using special validation controls that are meant for this. We have Range Validator, Email Validator.
10. Can the validation be done in the server side? Or this can be done only in the Client side? - Client side is done by default. Server side validation is also possible. We can switch off the client side and server side can be done.
11. How to manage pagination in a page? - Using pagination option in DataGrid control. We have to set the number of records for a page, then it takes care of pagination by itself.
12. What is ADO .NET and what is difference between ADO and ADO.NET? - ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the tables and select insert and updates to the database. I can update the actual database as a batch.

.NET



   1. Are private class-level variables inherited? - Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
   2. Why does DllImport not work for me? - All methods marked with the DllImport attribute must be marked as public static extern.
   3. Why does my Windows application pop up a console window every time I run it? - Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.
   4. Why do I get an error (CS1006) when trying to declare a method without specifying a return type? - If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)
   5. Why do I get a syntax error when trying to declare a variable called checked? - The word checked is a keyword in C#.
   6. Why do I get a security exception when I try to run my C# app? - Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.
   7. Why do I get a CS5001: does not have an entry point defined error when compiling? - The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }
   8. What optimizations does the C# compiler perform when you use the /optimize+ compiler option? - The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.
   9. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)? - The syntax for calling another constructor is as follows: class B { B(int i) { } } class C : B { C() : base(5) // call base constructor B(5) { } C(int i) : this() // call C() { } public static void Main() {} }
  10. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development? - Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.
  11. What is the difference between a struct and a class in C#? - From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.
  12. My switch statement works differently than in C++! Why? - C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:

13.switch(x)

14.{

15.  case 0: // do something

16.  case 1: // do something as continuation of case 0

17.  default: // do something in common with

18.         //0, 1 and everything else

19.  break;

20.}

To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):

class Test

{

  public static void Main() {

         int x = 3;

         switch(x)

         {

                 case 0: // do something

                 goto case 1;

                 case 1: // do something in common with 0

                 goto default;

                 default: // do something in common with 0, 1, and anything else

                 break;

         }

  }

}

  21. Is there regular expression (regex) support available to C# developers? - Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.
  22. Is there any sample C# code for simple threading? - Yes:

23.using System;

24.using System.Threading;

25.class ThreadTest

26.{

27.  public void runme()

28.  {

29.         Console.WriteLine("Runme Called");

30.  }

31.  public static void Main(String[] args)

32.  {

33.         ThreadTest b = new ThreadTest();

34.         Thread t = new Thread(new ThreadStart(b.runme));

35.         t.Start();

36.  }

}

  37. Is there an equivalent of exit() for quitting a C# .NET application? - Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.
  38. Is there a way to force garbage collection? - Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().
  39. Is there a way of specifying which block or loop to break out of when working with nested loops? - The easiest way is to use goto:

40.using System;

41.class BreakExample

42.{

43.  public static void Main(String[] args) {

44.          for(int i=0; i<3; i++)

45.         {

46.                 Console.WriteLine("Pass {0}: ", i);

47.                 for( int j=0 ; j<100 ; j++ )

48.                 {

49.                         if ( j == 10)

50.                                goto done;

51.                         Console.WriteLine("{0} ", j);

52.                 }

53.                 Console.WriteLine("This will not print");

54.         }

55.         done:

56.                 Console.WriteLine("Loops complete.");

57.  }

}

  58. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace? - There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.



Useful for preparation, but too specific to be used in the interview.

   1. Is it possible to inline assembly or IL in C# code? - No.
   2. Is it possible to have different access modifiers on the get/set methods of a property? - No. The access modifier on a property applies to both its get and set accessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.
   3. Is it possible to have a static indexer in C#? - No. Static indexers are not allowed in C#.
   4. If I return out of a try/finally in C#, does the code in the finally-clause run? - Yes. The code in the finally always runs. If you return out of the try block, or even if you do a “goto” out of the try, the finally block always runs:

using System;

class main

{

  public static void Main()

  {

         try

         {

                 Console.WriteLine("In Try block");

                 return;

         }

         finally

         {

                 Console.WriteLine("In Finally block");

         }

  }

}



  

Both “In Try block” and “In Finally block” will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it’s a return without an expression (as it is above), the IL emitted is identical whetherthe return is inside or outside of the try. If the return has an expression, there’s an extra store/load of the value of the expression (since it has to be computed within the try block).

   5. I was trying to use an “out int” parameter in one of my functions. How should I declare the variable that I am passing to it? - You should declare the variable as an int, but when you pass it in you must specify it as ‘out’, like the following: int i; foo(out i); where foo is declared as follows: [return-type] foo(out int o) { }
   6. How does one compare strings in C#? - In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings’ values. That will still work, but the C#compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If you actually do want to compare references, it can be done as follows: if ((object) str1 == (object) str2) { … } Here’s an example showing howstring compares work:

7.  using System;

8.  public class StringTest

9.  {

10.  public static void Main(string[] args)

11.  {

12.         Object nullObj = null; Object realObj = new StringTest();

13.         int i = 10;

14.         Console.WriteLine("Null Object is [" + nullObj + "]n"

15.                 + "Real Object is [" + realObj + "]n"

16.                 + "i is [" + i + "]n");

17.                 // Show string equality operators

18.         string str1 = "foo";

19.         string str2 = "bar";

20.          string str3 = "bar";

21.         Console.WriteLine("{0} == {1} ? {2}", str1, str2, str1 == str2 );

22.         Console.WriteLine("{0} == {1} ? {2}", str2, str3, str2 == str3 );

23.  }

24.}

  

Output:

Null Object is []

Real Object is [StringTest]

i is [10]

foo == bar ? False

bar == bar ? True

  

  25. How do you specify a custom attribute for the entire assembly (rather than for a class)? - Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. An example of this is as follows:

26.using System;

27.[assembly : MyAttributeClass] class X {}

  

Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.

  28. How do you mark a method obsolete? -

[Obsolete] public int Foo() {...}

or

[Obsolete("This is a message describing why this method is obsolete")] public int Foo() {...}

Note: The O in Obsolete is always capitalized.

  29. How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#? - You want the lock statement, which is the same as Monitor Enter/Exit:

30.lock(obj) { // code }

  

translates to

try {

  CriticalSection.Enter(obj);

  // code

}

finally

{

  CriticalSection.Exit(obj);

}

            

  31. How do you directly call a native function exported from a DLL? - Here’s a quick example of the DllImport attribute in action:

32.using System.Runtime.InteropServices;

33.class C

34.{

35.  [DllImport("user32.dll")]

36.  public static extern int MessageBoxA(int h, string m, string c, int type);

37.  public static int Main()

38.  {

39.         return MessageBoxA(0, "Hello World!", "Caption", 0);

40.  }

41.}

  

This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.

  42. How do I simulate optional parameters to COM calls? - You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters.

   





   

C# .NET interview questions



Good for preparation and general self-testing, but too specific for the actual job interview. This was sent in by a job applicant getting ready to step into the .NET field in India.

   1. Are private class-level variables inherited? - Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
   2. Why does DllImport not work for me? - All methods marked with the DllImport attribute must be marked as public static extern.
   3. Why does my Windows application pop up a console window every time I run it? - Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.
   4. Why do I get an error (CS1006) when trying to declare a method without specifying a return type? - If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)
   5. Why do I get a syntax error when trying to declare a variable called checked? - The word checked is a keyword in C#.
   6. Why do I get a security exception when I try to run my C# app? - Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.
   7. Why do I get a CS5001: does not have an entry point defined error when compiling? - The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }
   8. What optimizations does the C# compiler perform when you use the /optimize+ compiler option? - The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.
   9. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)? - The syntax for calling another constructor is as follows: class B { B(int i) { } } class C : B { C() : base(5) // call base constructor B(5) { } C(int i) : this() // call C() { } publicstatic void Main() {} }
  10. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development? - Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.
  11. What is the difference between a struct and a class in C#? - From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.
  12. My switch statement works differently than in C++! Why? - C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:

13.switch(x)

14.{

15.  case 0: // do something

16.  case 1: // do something as continuation of case 0

17.  default: // do something in common with

18.         //0, 1 and everything else

19.  break;

20.}

        

To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):

class Test

{

  public static void Main() {

         int x = 3;

         switch(x)

         {

                 case 0: // do something

                 goto case 1;

                 case 1: // do something in common with 0

                 goto default;

                 default: // do something in common with 0, 1, and anything else

                 break;

         }

  }

}

        

  21. Is there regular expression (regex) support available to C# developers? - Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.
  22. Is there any sample C# code for simple threading? - Yes:

23.using System;

24.using System.Threading;

25.class ThreadTest

26.{

27.  public void runme()

28.  {

29.         Console.WriteLine("Runme Called");

30.  }

31.  public static void Main(String[] args)

32.  {

33.         ThreadTest b = new ThreadTest();

34.         Thread t = new Thread(new ThreadStart(b.runme));

35.         t.Start();

36.  }

}

  37. Is there an equivalent of exit() for quitting a C# .NET application? - Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.
  38. Is there a way to force garbage collection? - Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().
  39. Is there a way of specifying which block or loop to break out of when working with nested loops? - The easiest way is to use goto:

40.using System;

41.class BreakExample

42.{

43.  public static void Main(String[] args) {

44.         for(int i=0; i<3; i++)

45.         {

46.                 Console.WriteLine("Pass {0}: ", i);

47.                 for( int j=0 ; j<100 ; j++ )

48.                 {

49.                         if ( j == 10)

50.                                goto done;

51.                         Console.WriteLine("{0} ", j);

52.                 }

53.                 Console.WriteLine("This will not print");

54.         }

55.         done:

56.                 Console.WriteLine("Loops complete.");

57.  }

58.}

            

  59. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace? - There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.

   






   

C# developer interview questions



A representative of a high-tech company in United Kingdom sent this in today noting that the list was used for interviewing a C# .NET developer. Any corrections and suggestions would be forwarded to the author. I won’t disclose the name of the company, since as far as I know they might still be using this test for prospective employees. Correct answers are in green color.

1) The C# keyword ‘int’ maps to which .NET type?

   1. System.Int16
   2. System.Int32
   3. System.Int64
   4. System.Int128

2) Which of these string definitions will prevent escaping on backslashes in C#?

   1. string s = #”n Test string”;
   2. string s = “’n Test string”;
   3. string s = @”n Test string”;
   4. string s = “n Test string”;



3) Which of these statements correctly declares a two-dimensional array in C#?

   1. int[,] myArray;
   2. int[][] myArray;
   3. int[2] myArray;
   4. System.Array[2] myArray;

4) If a method is marked as protected internal who can access it?

   1. Classes that are both in the same assembly and derived from the declaring class.
   2. Only methods that are in the same class as the method in question.
   3. Internal methods can be only be called using reflection.
   4. Classes within the same assembly, and classes derived from the declaring class.

5) What is boxing?

a) Encapsulating an object in a value type.

b) Encapsulating a copy of an object in a value type.

c) Encapsulating a value type in an object.

d) Encapsulating a copy of a value type in an object.

6) What compiler switch creates an xml file from the xml comments in the files in an assembly?

   1. /text
   2. /doc
   3. /xml
   4. /help

7) What is a satellite Assembly?

   1. A peripheral assembly designed to monitor permissions requests from an application.
   2. Any DLL file used by an EXE file.
   3. An assembly containing localized resources for another assembly.
   4. An assembly designed to alter the appearance or ‘skin’ of an application.

8) What is a delegate?

   1. A strongly typed function pointer.
   2. A light weight thread or process that can call a single method.
   3. A reference to an object in a different process.
   4. An inter-process message channel.

9) How does assembly versioning in .NET prevent DLL Hell?

   1. The runtime checks to see that only one version of an assembly is on the machine at any one time.
   2. .NET allows assemblies to specify the name AND the version of any assemblies they need to run.
   3. The compiler offers compile time checking for backward compatibility.
   4. It doesn’t.

10) Which “Gang of Four” design pattern is shown below?

public class A {

    private A instance;

    private A() {

    }

    public
static A Instance {

        get

        {

            if ( A == null )

                A = new A();

            return instance;

        }

    }

}

   1. Factory
   2. Abstract Factory
   3. Singleton
   4. Builder

11) In the NUnit test framework, which attribute must adorn a test class in order for it to be picked up by the NUnit GUI?

   1. TestAttribute
   2. TestClassAttribute
   3. TestFixtureAttribute
   4. NUnitTestClassAttribute

12) Which of the following operations can you NOT perform on an ADO.NET DataSet?

   1. A DataSet can be synchronised with the database.
   2. A DataSet can be synchronised with a RecordSet.
   3. A DataSet can be converted to XML.
   4. You can infer the schema from a DataSet.

13) In Object Oriented Programming, how would you describe encapsulation?

   1. The conversion of one type of object to another.
   2. The runtime resolution of method calls.
   3. The exposition of data.
   4. The separation of interface and implementation.


   





   

ASP.NET DataGrid questions



   1. What is datagrid? The DataGrid Web server control is a powerful tool for displaying information from a data source. It is easy to use; you can display editable data in a professional-looking grid by setting only a few properties. At the same time, the grid has a sophisticated object model that provides you with great flexibility in how you display the data.
   2. What’s the difference between the System.Web.UI.WebControls.DataGrid and and System.Windows.Forms.DataGrid? The Web UI control does not inherently support master-detail data structures. As with other Web server controls, it does not support two-way data binding. If you want to update data, you must write code to do this yourself. You can only edit one row at a time. It does not inherently support sorting, although it raises events you can handle in order to sort the grid contents. You can bind the Web Forms DataGrid to any object that supports the IEnumerable interface. The Web Forms DataGrid control supports paging. It is easy to customize the appearance and layout of the Web Forms DataGrid control as compared to the Windows Forms one.
   3. How do you customize the column content inside the datagrid? If you want to customize the content of a column, make the column a template column. Template columns work like item templates in the DataList or Repeater control, except that you are defining the layout of a column rather than a row.
   4. How do you apply specific formatting to the data inside the cells? You cannot specify formatting for columns generated when the grid’s AutoGenerateColumns property is set to true, only for bound or template columns. To format, set the column’s DataFormatString property to a string-formatting expression suitable for the data type of the data you are formatting.
   5. How do you hide the columns? One way to have columns appear dynamically is to create them at design time, and then to hide or show them as needed. You can do this by setting a column’s Visible property.
   6. How do you display an editable drop-down list? Displaying a drop-down list requires a template column in the grid. Typically, the ItemTemplate contains a control such as a data-bound Label control to show the current value of a field in the record. You then add a drop-down list to the EditItemTemplate. In Visual Studio, you can add a template column in the Property builder for the grid, and then use standard template editing to remove the default TextBox control from the EditItemTemplate and drag a DropDownList control into it instead. Alternatively, you can add the template column in HTML view. After you have created the template column with the drop-down list in it, there are two tasks. The first is to populate the list. The second is to preselect the appropriate item in the list — for example, if a book’s genre is set to “fiction,” when the drop-down list displays, you often want “fiction” to be preselected.
   7. How do you check whether the row data has been changed? The definitive way to determine whether a row has been dirtied is to handle the changed event for the controls in a row. For example, if your grid row contains a TextBox control, you can respond to the control’s TextChanged event. Similarly, for check boxes, you can respond to a CheckedChanged event. In the handler for these events, you maintain a list of the rows to be updated. Generally, the best strategy is to track the primary keys of the affected rows. For example, you can maintain an ArrayList object that contains the primary keys of the rows to update.

This is just a brief on dealing with ASP.NET DataGrid control. The full version of the document and the sample code is available on MSDN.

   





   

Windows code security questions



   1. What’s the difference between code-based security and role-based security? Which one is better? Code security is the approach of using permissions and permission sets for a given code to run. The admin, for example, can disable running executables off the Internet or restrict access to corporate database to only few applications. Role-based security most of the time involves the code running with the privileges of the current user. This way the code cannot supposedly do more harm than mess up a single user account. There’s no better, or 100% thumbs-up approach, depending on the nature of deployment, both code-based and role-based security could be implemented to an extent.
   2. How can you work with permissions from your .NET application? You can request permission to do something and you can demand certain permissions from other apps. You can also refuse permissions so that your app is not inadvertently used to destroy some data.
   3. How can C# app request minimum permissions?

using System.Security.Permissions;
[assembly:FileDialogPermissionAttribute(SecurityAction.RequestMinimum, Unrestricted=true)]

   4. What’s a code group? A code group is a set of assemblies that share a security context.
   5. What’s the difference between authentication and authorization? Authentication happens first. You verify user’s identity based on credentials. Authorization is making sure the user only gets access to the resources he has credentials for.
   6. What are the authentication modes in ASP.NET? None, Windows, Forms and Passport.
   7. Are the actual permissions for the application defined at run-time or compile-time? The CLR computes actual permissions at runtime based on code group membership and the calling chain of the code.

   





   

.NET Deployment questions



   1. What do you know about .NET assemblies? Assemblies are the smallest units of versioning and deployment in the .NET application. Assemblies are also the building blocks for programs such as Web services, Windows services, serviced components, and .NET remoting applications.
   2. What’s the difference between private and shared assembly? Private assembly is used inside an application only and does not have to be identified by a strong name. Shared assembly can be used by multiple applications and has to have a strong name.
   3. What’s a strong name? A strong name includes the name of the assembly, version number, culture identity, and a public key token.
   4. How can you tell the application to look for assemblies at the locations other than its own install? Use the
      directive in the XML .config file for a given application.

<probing privatePath="c:\mylibs; bin\debug” />

should do the trick. Or you can add additional search paths in the Properties box of the deployed application.

   5. How can you debug failed assembly binds? Use the Assembly Binding Log Viewer (fuslogvw.exe) to find out the paths searched.
   6. Where are shared assemblies stored? Global assembly cache.
   7. How can you create a strong name for a .NET assembly? With the help of Strong Name tool (sn.exe).
   8. Where’s global assembly cache located on the system? Usually C:\winnt\assembly or C:\windows\assembly.
   9. Can you have two files with the same file name in GAC? Yes, remember that GAC is a very special folder, and while normally you would not be able to place two files with the same name into a Windows folder, GAC differentiates by version number as well, so it’s possible for MyApp.dll and MyApp.dll to co-exist in GAC if the first one is version 1.0.0.0 and the second one is 1.1.0.0.
  10. So let’s say I have an application that uses MyApp.dll assembly, version 1.0.0.0. There is a security bug in that assembly, and I publish the patch, issuing it under name MyApp.dll 1.1.0.0. How do I tell the client applications that are already installed to start using this new MyApp.dll? Use publisher policy. To configure a publisher policy, use the publisher policy configuration file, which uses a format similar app .config file. But unlike the app .config file, a publisher policy file needs to be compiled into an assembly and placed in the GAC.
  11. What is delay signing? Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.

   





   

ASP.NET questions, part 1

   1. Explain the differences between Server-side and Client-side code? Server side scripting means that all the script will be executed by the server and interpreted as needed. ASP doesn’t have some of the functionality like sockets, uploading, etc. For these you have to make a custom components usually in VB or VC++. Client side scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Download time, browser compatibility, and visible code - since JavaScript and VBScript code is included in the HTML page, then anyone can see the code by viewing the page source. Also a possible security hazards for the client computer.
   2. What type of code (server or client) is found in a Code-Behind class? C#
   3. 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.
   4. What does the "EnableViewState" property do? Why would I want it on or off? Enable ViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip (as in the datagrid example in tip #4), then you do not need the control to maintain it’s view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false.
   5. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other? Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist accros the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive. Response.Dedirect() :client know the physical loation (page name and query string as well). Context.Items loses the persisitance when nevigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some 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.
   6. Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component? When to Use Web Services:
          * Communicating through a Firewall When building a distributed application with 100s/1000s of users spread over multiple locations, there is always the problem of communicating between client and server because of firewalls and proxy servers. Exposing your middle tier components as Web Services and invoking the directly from a Windows UI is a very valid option.
          * Application Integration When integrating applications written in various languages and running on disparate systems. Or even applications running on the same platform that have been written by separate vendors.
          * Business-to-Business Integration This is an enabler for B2B intergtation which allows one to expose vital business processes to authorized supplier and customers. An example would be exposing electronic ordering and invoicing, allowing customers to send you purchase orders and suppliers to send you invoices electronically.
          * Software Reuse This takes place at multiple levels. Code Reuse at the Source code level or binary componet-based resuse. The limiting factor here is that you can reuse the code but not the data behind it. Webservice overcome this limitation. A scenario could be when you are building an app that aggregates the functionality of serveral other Applicatons. Each of these functions could be performed by individual apps, but there is value in perhaps combining the the multiple apps to present a unifiend view in a Portal or Intranet.
          * When not to use Web Services: Single machine Applicatons When the apps are running on the same machine and need to communicate with each other use a native API. You also have the options of using component technologies such as COM or .NET Componets as there is very little overhead.
          * Homogeneous Applications on a LAN If you have Win32 or Winforms apps that want to communicate to their server counterpart. It is much more efficient to use DCOM in the case of Win32 apps and .NET Remoting in the case of .NET Apps.
   7. Let’s say I have an existing application written using Visual Studio (VBInterDevand this application utilizes WindowsCOM+ transaction services. How would you approach migrating this application to .NET?
   8. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset? In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset. There are important differences between them.
          * A recordset looks like a single table. If a recordset is to contain data from multiple database tables, it must use a JOIN query, which assembles the data from the various database tables into a single result table. In contrast, a dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple DataTable objects. That is, each DataTable object typically corresponds to a single database table or view. In this way, a dataset can mimic the structure of the underlying database. A dataset usually also contains relationships. A relationship within a dataset is analogous to a foreign-key relationship in a database —that is, it associates rows of the tables with each other. For example, if a dataset contains a table about investors and another table about each investor’s stock purchases, it could also contain a relationship connecting each row of the investor table with the corresponding rows of the purchase table. Because the dataset can hold multiple, separate tables and maintain information about relationships between them, it can hold much richer data structures than a recordset, including self-relating tables and tables with many-to-many relationships.
          * In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET, rows are represented as collections, so you can loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. DataRelation objects maintain information about master and detail records and provide a method that allows you to get records related to the one you are working with. For example, starting from the row of the Investor table for "Nate Sun," you can navigate to the set of rows of the Purchase table describing his purchases. A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object. For more information about cursor functionality, see Data Access Technologies.
          * Minimized Open Connections: In ADO.NET you open connections only long enough to perform a database operation, such as a Select or Update. You can read rows into a dataset and then work with them without staying connected to the data source. In ADO the recordset can provide disconnected access, but ADO is designed primarily for connected access. There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source. The important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database — by optimizing for performance, performing data validation checks, or adding any other extra processing. Data adapters, data connections, data commands, and data readers are the components that make up a .NET Framework data provider. Microsoft and third-party providers can make available other .NET Framework data providers that can be integrated into Visual Studio.
          * Sharing Data Between Applications. Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected recordset. To transmit an ADO disconnected recordset from one component to another, you use COM marshalling. To transmit data in ADO.NET, you use a dataset, which can transmit an XML stream.
          * Richer data types.COM marshalling provides a limited set of data types — those defined by the COM standard. Because the transmission of datasets in ADO.NET is based on an XML format, there is no restriction on data types. Thus, the components sharing the dataset can use whatever rich set of data types they would ordinarily use.
          * Performance. Transmitting a large ADO recordset or a large ADO.NET dataset can consume network resources; as the amount of data grows, the stress placed on the network also rises. Both ADO and ADO.NET let you minimize which data is transmitted. But ADO.NET offers another performance advantage, in that ADO.NET does not require data-type conversions. ADO, which requires COM marshalling to transmit records sets among components, does require that ADO data types be converted to COM data types.
          * Penetrating Firewalls.A firewall can interfere with two components trying to transmit disconnected ADO recordsets. Remember, firewalls are typically configured to allow HTML text to pass, but to prevent system-level requests (such as COM marshalling) from passing.
   9. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines? The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. It’s a good place to initialize global variables. For example, you might want to retrieve a list of products from a database table and place the list in application state or the Cache object. SessionStateModule exposes both Session_Start and Session_End events.
  10. If I’m developing an application that must accomodate multiple security levels though secure login and my ASP.NET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be the best approach to maintain login-in state for the users?
  11. 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.
  12. How does VB.NET/C# achieve polymorphism? By using Abstract classes/functions.
  13. Can you explain what inheritance is and an example of when you might use it? Inheritance is a fundamental feature of an object oriented system and it is simply the ability to inherit data and functionality from a parent object. Rather than developing new objects from scratch, new code can be based on the work of other programmers, adding only new features that are needed.
  14. How would you implement inheritance using VB.NET/C#? When we set out to implement a class using inheritance, we must first start with an existing class from which we will derive our new subclass. This existing class, or base class, may be part of the .NET system class library framework, it may be part of some other application or .NET assembly, or we may create it as part of our existing application. Once we have a base class, we can then implement one or more subclasses based on that base class. Each of our subclasses will automatically have all of the methods, properties, and events of that base class ? including the implementation behind each method, property, and event. Our subclass can add new methods, properties, and events of its own - extending the original interface with new functionality. Additionally, a subclass can replace the methods and properties of the base class with its own new implementation - effectively overriding the original behavior and replacing it with new behaviors. Essentially inheritance is a way of merging functionality from an existing class into our new subclass. Inheritance also defines rules for how these methods, properties, and events can be merged.

   





   

ASP.NET questions, part 2



   1. Whats an assembly? Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.
   2. Describe the difference between inline and code behind - which is best in a loosely coupled solution? ASP.NET supports two modes of page development: Page logic code that is written inside <script runat=server> blocks within an .aspx file and dynamically compiled the first time the page is requested on the server. Page logic code that is written within an external class that is compiled prior to deployment on a server and linked "behind" the .aspx file at run time.
   3. Explain what a diffgram is, and a good use for one? A DiffGram is an XML format that is used to identify current and original versions of data elements. The DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet, including column values from both the Original and Current row versions, row error information, and row order.
   4. Where would you use an iHTTPModule, and what are the limitations of anyapproach you might take in implementing one? One of ASP.NET’s most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You can use them to extend your ASP.NET applications by adding pre- and post-processing to each HTTP request coming into your application. For example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes in and process the request in a custom HTTP module.
   5. What are the disadvantages of viewstate/what are the benefits?
   6. Describe session handling in a webfarm, how does it work and what are the limits?
   7. How would you get ASP.NET running in Apache web servers - why would you even do this?
   8. Whats MSIL, and why should my developers need an appreciation of it if at all?
   9. In what order do the events of an ASPX page execute. As a developer is it important to undertsand these events? Every Page object (which your .aspx page is) has nine events, most of which you will not have to worry about in your day to day dealings with ASP.NET. The three that you will deal with the most are: Page_Init, Page_Load, Page_PreRender.
  10. Which method do you invoke on the DataAdapter control to load your generated dataset with data?

System.Data.Common.DataAdapter.Fill(System.Data.DataSet);

If my DataAdapter is sqlDataAdapter and my DataSet is dsUsers then it is called this way:

sqlDataAdapter.Fill(dsUsers);

  11. ata in the Repeater control?
  12. Which template must you provide, in order to display data in a Repeater control? ItemTemplate
  13. 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.
  14. 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 DataMember property which Gets or sets the specific table in the DataSource to bind to the control and the DataBind method to bind data from a source to a server control. This method is commonly used after retrieving a data set through a database query.
  15. What base class do all Web Forms inherit from? System.Web.UI.Page
  16. What method do you use to explicitly kill a user’s session?


      The Abandon method destroys all the objects stored in a Session object and releases their resources.
      If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.

      Syntax: Session.Abandon
  17. How do you turn off cookies for one page in your site?
      Use the Cookie.Discard Property which Gets or sets the discard flag set by the server. When true, this
      property instructs the client application not to save the Cookie on the user’s hard disk when a session ends.
  18. Which two properties are on every validation control? ControlToValidate & ErrorMessage properties
  19. What tags do you need to add within the asp:datagrid tags to bind columns manually?
  20. How do you create a permanent cookie? Setting the Expires property to MinValue means that the Cookie never expires.
  21. What tag do you use to add a hyperlink column to the DataGrid?
  22. What is the standard you use to wrap up a call to a Web service?
  23. Which method do you use to redirect the user to another page without performing a round trip to the client? Server.transfer()
  24. What is the transport protocol you use to call a Web service? SOAP. Transport Protocols: It is essential for the acceptance of Web Services that they are based on established Internet infrastructure. This in fact imposes the usage of of the HTTP, SMTP and FTP protocols based on the TCP/IP family of transports. Messaging Protocol: The format of messages exchanged between Web Services clients and Web Services should be vendor neutral and should not carry details about the technology used to implement the service. Also, the message format should allow for extensions and different bindings to specific transport protocols. SOAP and ebXML Transport are specifications which fulfill these requirements. We expect that the W3C XML Protocol Working Group defines a successor standard.
  25. True or False: A Web service can only be written in .NET. False.
  26. What does WSDL stand for? Web Services Description Language
  27. What property do you have to set to tell the grid which page to go to when using the Pager object?
  28. Where on the Internet would you look for Web services? UDDI repositaries like uddi.microsoft.com, IBM UDDI node, UDDI Registries in Google Directory, enthusiast sites like XMethods.net.
  29. What tags do you need to add within the asp:datagrid tags to bind columns manually? Column tag and an ASP:databound tag.
  30. 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?
  31. How is a property designated as read-only? In VB.NET:

32.Public ReadOnly Property PropertyName As ReturnType

33.  Get             ‘Your Property Implementation goes in here

34.  End Get

End Property

in C#

public returntype PropertyName

{

   get{

           //property implementation goes here

   }

   // Do not write the set implementation

}

          

  35. Which control would you use if you needed to make sure the values in two different controls matched? Use the CompareValidator control to compare the values
      of 2 different controls.
  36. True or False: To test a Web service you must create a windows application or Web application to consume this service? False.
  37. How many classes can a single .NET DLL contain? Unlimited

   





   

.NET and COM interop questions



   1. Describe the advantages of writing a managed code application instead of unmanaged one. What’s involved in certain piece of code being managed? The advantages include automatic garbage collection, memory management, support for versioning and security. These advantages are provided through .NET FCL and CLR, while with the unmanaged code similar capabilities had to be implemented through third-party libraries or as a part of the application itself.
   2. Are COM objects managed or unmanaged? Since COM objects were written before .NET, apparently they are unmanaged.
   3. So can a COM object talk to a .NET object? Yes, through Runtime Callable Wrapper (RCW) or PInvoke.
   4. How do you generate an RCW from a COM object? Use the Type Library Import utility shipped with SDK. tlbimp COMobject.dll /out:.NETobject.dll or reference the COM library from Visual Studio in your project.
   5. I can’t import the COM object that I have on my machine. Did you write that object? You can only import your own objects. If you need to use a COM component from another developer, you should obtain a Primary Interop Assembly (PIA) from whoever authored the original object.
   6. How do you call unmanaged methods from your .NET code through PInvoke? Supply a DllImport attribute. Declare the methods in your .NET code as static extern. Do not implement the methods as they are implemented in your unmanaged code, you’re just providing declarations for method signatures.
   7. Can you retrieve complex data types like structs from the PInvoke calls? Yes, just make sure you re-declare that struct, so that managed code knows what to do with it.
   8. I want to expose my .NET objects to COM objects. Is that possible? Yes, but few things should be considered first. Classes should implement interfaces explicitly. Managed types must be public. Methods, properties, fields, and events that are exposed to COM must be public. Types must have a public default constructor with no arguments to be activated from COM. Types cannot be abstract.
   9. Can you inherit a COM class in a .NET application? The .NET Framework extends the COM model for reusability by adding implementation inheritance. Managed types can derive directly or indirectly from a COM coclass; more specifically, they can derive from the runtime callable wrapper generated by the runtime. The derived type can expose all the method and properties of the COM object as well as methods and properties implemented in managed code. The resulting object is partly implemented in managed code and partly implemented in unmanaged code.
  10. Suppose I call a COM object from a .NET applicaiton, but COM object throws an error. What happens on the .NET end? COM methods report errors by returning HRESULTs; .NET methods report them by throwing exceptions. The runtime handles the transition between the two. Each exception class in the .NET Framework maps to an HRESULT.

   





   

COM/COM+ services and components in .NET

   1. Explain transaction atomicity. We must ensure that the entire transaction is either committed or rolled back.
   2. Explain consistency. We must ensure that the system is always left at the correct state in case of the failure or success of a transaction.
   3. Explain integrity. Ensure data integrity by protecting concurrent transactions from seeing or being adversely affected by each other’s partial and uncommitted results.
   4. Explain durability. Make sure that the system can return to its original state in case of a failure.
   5. Explain object pooling. With object pooling, COM+ creates objects and keeps them in a pool, where they are ready to be used when the next client makes a request. This improves the performance of a server application that hosts the objects that are frequently used but are expensive to create.
   6. Explain JIT activation. The objective of JIT activation is to minimize the amount of time for which an object lives and consumes resources on the server. With JIT activation, the client can hold a reference to an object on the server for a long time, but the server creates the object only when the client calls a method on the object. After the method call is completed, the object is freed and its memory is reclaimed. JIT activation enables applications to scale up as the number of users increases.
   7. Explain role-based security. In the role-based security model, access to parts of an application are granted or denied based on the role to which the callers belong. A role defines which members of a Windows domain are allowed to work with what components, methods, or interfaces.
   8. Explain queued components. The queued components service enables you to create components that can execute asynchronously or in disconnected mode. Queued components ensure availability of a system even when one or more sub-systems are temporarily unavailable. Consider a scenario where salespeople take their laptop computers to the field and enter orders on the go. Because they are in disconnected mode, these orders can be queued up in a message queue. When salespeople connect back to the network, the orders can be retrieved from the message queue and processed by the order processing components on the server.
   9. Explain loosely coupled events. Loosely coupled events enable an object (publisher) to publish an event. Other objects (subscribers) can subscribe to an event. COM+ does not require publishers or subscribers to know about each other. Therefore, loosely coupled events greatly simplify the programming model for distributed applications.
  10. Define scalability. The application meets its requirement for efficiency even if the number of users increases.
  11. Define reliability. The application generates correct and consistent information all the time.
  12. Define availability. Users can depend on using the application when needed.
  13. Define security. The application is never disrupted or compromised by the efforts of malicious or ignorant users.
  14. Define manageability. Deployment and maintenance of the application is as efficient and painless as possible.
  15. Which namespace do the classes, allowing you to support COM functionality, are located? System.EnterpriseServices
  16. How do you make a NET component talk to a COM component? To enable the communication between COM and .NET components, the .NET Framework generates a COM Callable Wrapper (CCW). The CCW enables communication between the calling COM code and the managed code. It also handles conversion between the data types, as well as other messages between the COM types and the .NET types.

   





   

No comments:

Post a Comment