What is MSIL?
MSIL:
(Microsoft intermediate language)
When compiling the managed code, the compiler translates your source code into
Microsoft intermediate language (MSIL), which is a CPU-independent set of
instructions that can be efficiently converted to native code. MSIL includes
instructions for loading, storing, initializing, and calling methods on
objects, as well as instructions for arithmetic and logical operations, control
flow, direct memory access, exception handling, and other operations.
Before
code can be executed, MSIL must be converted to CPU-specific code, usually by a
just-in-time (JIT) compiler. Because the common language runtime supplies one
or more JIT compilers for each computer architecture it supports, the same set
of MSIL can be JIT-compiled and executed on any supported architecture.
When a compiler produces MSIL, it also produces metadata. Metadata describes
the types in your code, including the definition of each type, the signatures
of each type's members, the members that your code references, and other data
that the runtime uses at execution time. The MSIL and metadata are
contained in a portable executable (PE)
file.
What is the CLR?
CLR
is a set of standard resources that any .NET applications can take advantage
of, regardless of programming language.
Note:
Not all languages will support all CLR services.
What is the CTS?
The
specification that determines how the CLR defines, uses, and manages types.
CTS
is the range of types that.NET runtime understands, and therefore that .NET
applications can use.
CTS
is a superset of the CLS.
Note:
Not all languages will support all CLS services.
What is the CLS?
CLS
is the one which all .NET languages support.
CLS
is a subset of the CTS.
What is Dll Hell?
The
versioning problem is what we call DLL HELL.
Problems araises when when multiple applications attempt to share a common
component (DLL/COM).
One
application will install a new version of the shared component that is not
backward compatible with the version already on the machine. Then application that
was referring to previous version component might potentially stop working, and
there will be delay for the user to discover why the application stopped
working.
The reason for these issues is that
1. Application using components version information aren't recorded
2.
Current run-time environment will allow only a single version of a component or
an application Therefore the component authors must write their code in a way
that remains backward compatible.
Solution to this problem
is using Assemblies which allows side-by-side execution.
In
.NET, Side by side is the ability to
install and run multiple versions of the same component on the machine at the
same time.
Assemblies are building blocks
used by the .NET Framework to solve versioning and deployment issues.
Assemblies are the deployment unit for types and resources. In essence,
assemblies are a "logical DLLs."
Private assembly –
Used
by one application alone.
Private
assemblies are deployed within application’s directory structure.
Shared assembly –
Used
by multiple applications on the machine.
A
shared assembly must have a name that is globally unique. (bind it with a
techinque called strong names)
Shared
assembly may be deployed within application’s directory structure OR to the
Global Assembly Cache.
Static assemblies
These
are the .NET PE files that you create at compile time.
Dynamic assemblies
These
are PE-formatted, in-memory assemblies that you dynamically create at runtime
using the classes in the System.Reflection.Emit namespace.
What is an
Assemblies?
They
are self describing installation units consisting of one or more files.
One
assembly could be made up of different files (like metadata, resource files,
DLL and an EXE).
Version dependencies are recorded inside the assembly manifest.
Big
advantage of assemblies is
They can be private or shared.
They can be loaded side by side
What are the
contents of assembly?
Contains
four elements:
Assembly metadata.
Type metadata.
Microsoft intermediate language (MSIL) code that implements the types.
A set of resources.
How do assemblies find each other?
For private assemblies the search
path is normally the application's directory and its sub-directories.
For
shared assemblies, the search path
is private assembly path + GAC.
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 is Partial
Assembly References?
Full assembly
reference
includes the assembly's name, version, culture, and public key token (if the
assembly has a strong name).
A
full assembly reference is required if you reference any assembly that is
located in the global assembly cache.
Partial Assembly
reference: We
can dynamically reference an
assembly by providing only partial information, such as specifying only the
assembly name. When you specify a partial assembly reference, the runtime looks
for the assembly only in the application
directory.
We can make partial references to an assembly in your code one of the following
ways:
-> Use a method such as System.Reflection.Assembly.Load
and specify only a partial reference. The runtime checks for the assembly in
the application directory.
-> Use the System.Reflection.Assembly.LoadWithPartialName
method and specify only a partial reference. The runtime checks for the
assembly in the application directory
and in the global assembly cache
What are class
access modifiers ?
Access
modifiers are keywords used to specify the declared accessibility of a member
or a type. This section introduces the four access modifiers:
· Public -
Access is not restricted.
· Protected -
Access is limited to the containing class or types derived from the containing
class.
· Internal - Access
is limited to the current assembly.
· Protected inertnal - Access is
limited to the current assembly or types derived · from the containing class.
· Private - Access
is limited to the containing type.
Changes to which
portion of version number indicates an incompatible change?
Major or minor,
both indicate an incompatible change.
How does assembly versioning work?
Each assembly has a version number called the compatibility version. Also each
reference to an assembly (from another assembly) includes both the name and
version of the referenced assembly. The version number has four numeric parts
(e.g. 5.5.2.33). Assemblies with either of the first two parts different are normally viewed as incompatible. If the first two parts
are the same, but the third is
different, the assemblies are deemed as 'maybe
compatible'. If only the fourth
part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the
version policy that decides to what
extent these rules are enforced. The
version policy can be specified via the application configuration file.
Can two application
one using private assembly and other using Shared assembly be stated as a
side-by-side executables?
Since
versioning is only applied to shared assemblies, and not to private assemblies,
two application one using private assembly and one using shared assembly cannot
be stated as side-by-side executables.
Diff between MODULE
and ASSEMBLY?
An Assembly is a DLL /EXE
Hold
assembly metadata.
A
Module is a DLL
Don’t
hold assembly metadata.
May
hold Type metadata. So this module can be added to assemblies at later time.
Application Domain?
Before .NET,
PROCESS acts as a boundary to isolate between applications.
A
running instance of an application is called Process. A Process can hold single application.
Application running in one process could not access the memory of another
application.
In .NET, APPLICATION DOMAIN acts as a boundary to isolate between
applications.
Here Process can hold multiple Application Domains.
Wherein
one application domain can hold single application.
In short - Multiple applications can run in a single process within multiple
application domains.
Individual applications can be stopped without stopping the entire process
Faults in one application cannot directly affect other applications inside the
same process
Objects that exists in different Application Domains interact with each other
by transporting copies of objects to each other or by using proxies for message
exchange (by reference).
FUNDAMENTAL:
At
runtime all managed code is loaded into an application domain and is run by a
managed thread. Several threads can be executed at any given time in a single
application domain. The runtime
keeps track of which threads are running in which application domains.
You
can locate the domain in which a
thread is executing at any time by calling the GetDomain method.
The .NET Framework
has two main components:CLR & Framework - the common language runtime and
the .NET Framework class library.
1. CLR is for code management.
CLR manages code at execution time,
providing core services such as memory management, thread management, security
& remoting.
Code that targets the runtime is known as managed code, while code that does
not target the runtime is known as unmanaged code
2. The Class Library provides a collection of reusable types that you can
use to develop applications ranging
from traditional command-line or graphical user interface (GUI) applications to
applications like ASP.NET, Web Forms and XML Web services.
The .NET Framework can be hosted by unmanaged components that load the CLR into
their processes and initiate the execution of managed code.
.NET provides several runtime hosts - ASP.NET, IE(unmanaged application that
host runtime).
ActiveX
& COM components can be used in a .NET application using Runtime Callable Wrapper (RCW).
Similarly, the .NET code can be used in a COM application using COM Callable Wrappers (CCW).
NET.Runtime
creates CCW. CCW lives in the unmanaged Heap.
When to use late
binding in .NET during Binding to the COM component and invoking its methods
from a .NET Application?
1.
When COM typelibrary is available, we generate metadata proxy using
TLBIMP xyz.tlb /out:xyzmetadataproxy.dll
(Note:
Like oleview.exe to view COM information, .NET SDK ships with a disassembler
called ILDASM that allows us to view the metadata & the Intermediate
language (IL) code information)
Now .NET application at runtime using this metadataproxy manufacture RCW which
handles the activation of COM, marshalling, object lifetime management and tons
of other jobs.
When
using metadata, early binding takes
place.
2. Assume if no typelibrary is available for COM component then .NET
application has to late bind to a
COM object through a mechanism called Reflection.
NOTE: If your COM component
implements only dispinterface and no
Iunknown, then you are pretty much limited to only using Reflection to activate your object and invoke methods on its
interface.
For late binding to a COM object, you need to know the object's ProgID or CLSID
What is reflection?
All
.NET compilers produce metadata
about the types defined in the modules they use.
This
metadata is packaged along with the module (modules in turn are packaged
together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection
namespace contains classes that can be used to interrogate the types for a module/assembly. Reflection can also be
used to dynamically invoke methods
(see System.Type.InvokeMember ) or even create types dynamically
at run-time (see System.Reflection.Emit.TypeBuilder).
What are the steps are involved
in creating shared assemblies :
* Create your DLL/EXE source code
* Generate unique assembly name using SN utility
* Sign your DLL/EXE with the private key by modifying AssemblyInfo
file
* Compile your DLL/EXE
* Place the resultant DLL/EXE in global assembly cache using
How to deploy an
assembly into the global assembly cache:
·
Use an installer designed to work
with the global assembly cache. This is the preferred option for installing
assemblies into the global assembly cache.
· Use a developer tool called the GAC tool (Gacutil.exe), provided by .NET SDK.
·
Use Windows Explorer to drag
assemblies into the cache.
RCW
Generating metadata from the COM Type library:
Consuming a Classic COM Component from a .NET
application
A
.NET application that needs to talk to our COM component cannot directly
consume the functionality that's exposed by it. So, we need to generate some
metadata. This metadata layer is used by the runtime to glean out type
information, so that it can use this type information at runtime to manufacture
what is called as a Runtime Callable Wrapper (RCW). The RCW handles
the actual activation of the COM object and handles the marshaling requirements
when the .NET application interacts with it. The RCW also does tons of other
chores like managing object identity, object lifetime, and interface
caching. Object lifetime management is a very critical issue here because
the .NET runtime moves objects around and garbage collects them. The RCW serves
the purpose of giving the .NET application the notion that it is interacting
with a managed .NET component and it gives the COM component in the unmanaged
space, the impression that it's being called by a good old COM client. The
RCW's creation & behavior varies depending on whether you are early binding
or late binding to the COM object. Under the hood, the RCW is doing all the
hard work and thunking down all the method invocations into corresponding
v-table calls into the COM component that lives in the unmanaged world. It's an
ambassador of goodwill between the managed world and the unmanaged IUnknown
world.
Let's
generate the metadata wrapper for our xyz COM component. To do that, we need to
use a tool called the TLBIMP.exe. The Type library Importer (TLBIMP)
ships with the .NET framework SDK and can be found under the Bin
subfolder of your SDK installation. The Type library Importer utility reads a
type library and generates the corresponding metadata wrapper containing type
information that the .NET runtime can comprehend.
From
the DOS command line, type the following command:
TLBIMP
xyz.tlb /out:xyz.dll
This
command tells the type library importer to read your xyzInfo COM type library
and generate a corresponding metadata wrapper called xyz.dll.
Differnce between
Managed code and unmanaged code ?
Managed Code:
Managed
code will supply the metadata to CLR which at runtime provide services such as
memory management, cross-language integration, code access security, and
automatic lifetime control of objects. All code based on Microsoft intermediate
language (MSIL) executes as managed code.
Un-Managed Code:
Code
that doesn’t provide metadata information to CLR.
Unmanaged
code executes in the CLR environment with minimal services (for example, no
garbage collection, limited debugging, and so on).
About NAMESPACE
It’s
used to - declare a scope, organize
your code, create globally unique types.
Within
a namespace you can declare the following types
a)class b)interface c)struct d)enum e)delegate f) another namespace Namespace implicitly
have public access by default.
2TYPES
- USER DEFINED(namespace defined in
your code), SYSTEM DEFINED (defined
by .NET Framework class lib)
Advantage of Namespace?
The
biggest problem with global scope is overcome by using namespace.
Using
namespace you can either
>import
all the symbols ( using namespace
BOSS;)
> import individual symbol ( using BOSS:: BOOK_VERSION;)
> one
time use ( if ( x ==
BOSS::BOOK_VERSION) then {} )
About USING
They
can be used as a DIRECTIVE, STATEMENT and ALIAS
DIRECTIVE : Using-directive allows
you to use the types in the
namespace without having to specify the namespace
STATEMENT : After using an object
you have to make sure to call objects DISPOSE method to clean up the object.
This job is taken care by "using statement".
Its adds the try-finally block
for our code and call the object Dispose()
method.
EXAMPLE:
string connString = "Datasource=localhost;.....";
string cmdstring ="select id,name from customers";
using(sqlconnection conn = new
sqlconnection(connstring))
{
using(sqlcommand cmd = new sqlcommand(cmdstring,cn))
{
conn.Open();
cmd.executenonquery();
}
}
THIS ABOVE CODE IS EQUIVALENT TO
sqlconnection conn = null;
sqlcommand cmd = null;
try
{
conn = new sqlconnection(connstring);
cmd=new sqlcommand(cmdstring);
conn.open();
cmd.executenonquery();
}
finally
{
if(null !=cmd) cm.Dispose();
if(null !=conn) conn.Dispose();
}
Following are the advantage of using statement
1. here you will not call CLOSE() on
the sqlconnection. Internally DISPOSE()
checks the status of the connection and closes
it for you.
2. Also DISPOSE() destroys the
connection string of the sqlconnection class. Therefore if you want to
re-open the connection you will have to
re-establish the connection string. If not it will throw an exception
[ NOTE: sqlconnection and sqlcommand implement IDisposable Which means they
could have unmanaged resources to cleanup and it is our job- the developers
to make sure DISPOSE() gets called on these classes after we are finished with
them.]
ALIAS: using alias = system.console;
alias.writeline("hello");
IMPORTANT: Using statement is
only for objects whose lifetime does not extent beyond the method in which its
constructed. Objects you use must implement the system.IDisposable interface
DELEGATES
Delegate
is a class whose object store references to methods. (Its
can point to static methods too)
Delegates are reference type.
Delegates are type-safe. Meaning
Delegate signature should match that
of the function it points to. Else
you get compile time error.
Single delegate instance can reference multiple methods of a particular type
(signature), wherein this type is
indicated during delegate declaration - the
input parameter and return type.
NOTE :function pointer in "C" points to a memory location but it knows
nothing about the method parameter and return type.
By invoking a single delegate will cause multiple methods to be called.
You can add the invocation list
using "+=" operator OR
remove from invocation list using "-="
operator.
Delegate instances can be combined.
Delegate instance are immutable.
If a delegate(holding multiple
method reference) returns a value and if its invoked then the value it returns
will be corresponding to the one returned by the last simple delegate in
the list.
Example:
public delegate VOID PRINT(STRING
S); -------- DECLARATION
public void someMethod(string ss) -------- class member function OR static
method
{ //code }
PRINT delvar = new PRINT(someMethod); -------- DEFINATION
(OR)
PRINT delvar = null;
delvar += new PRINT (someMethod); -------- ADDING TO INVOCATION LIST
delvar += new PRINT (otherMethod);
delvar(); -------- INVOKING DELEGATE
[ Equivalent to delvar.Invoke() ]
EVENTS
Events
are outcome of an action
Events are really restricted delegates
Events adds a layer of protection on the delegate instance.
Events
can be invoked only by the class
that defined it.
Events
cannot reset the delegate invocation list by assign it to null.
Events can only add/remove the
delegate invocation list.
DIFFERENCE BETWEEN
EVENTS AND DELEGATES
namespace
Example
{
public delegate void
MYDELEGATE();
public class ClassA
{
public MYDELEGATE mydelvar;
public event MYEVENT
myevtvar;
public ClassA ()
{}
public void FireEvent()
{
myevtvar();
}
}
}
namespace Example
{
class Client
{
static void Main(string[] args)
{
ClassA objA = new ClassA();
objA.mydelvar += new MYDELEGATE(MyFunc1);
objA.myevtvar += new MYDELEGATE(MyFunc2);
objA.mydelvar();
//invokes the delegate
objA.FireEvent();
// invokes the event
}
public static void MyFunc1()
{
console.WriteLine("MyFunc1");
}
public static void MyFunc2()
{
console.WriteLine("MyFunc2");
}
}
}
NOTE: In Main() the following lines
of code are not allowed. It produces compilation error
objA.myevtvar = new MYDELEGATE(MyFunc2);
objA.myevtvar();
1. Through events you can only
add/remove from the delegate invocation list, but never reset the delegate using "="
2. you cannot invoke an event outside the class that defines the event. Inside
ClassA its allowed but not inside Client class.
Therefore if we use the event keyword no client class can be set it to
null. Multiple clients can use the same delegate. After multiple clients have
added a function to listen to the callback of the delegate. But now if one
client sets the delegate to null or uses "=" sign to add a new
callback, this means that the previous invocation list will not be used anymore
and all the previous client will not get any callback even if they have
registered for the callback.
Therefore event keyword adds a layer of protection on the instance of the
delegate. This protection prevents any client to reset the delegate invocation
list. Only clients are allowed to add/remove the target from invocation list.
What are differences
b/w Typed & UnTyped Datasets ? Which would give you a better performance?
Untyped dataset is a direct instantiation of
System.Data.Dataset, whereas
Typed dataset is a distinct class
that inherits from System.Data.Dataset.
A typed dataset exposes its tables, and
the columns within them, as object
properties
while
an untyped you have to deal with
tables and items collection.
Example
Typed dataset :
Me.dsOrder.OrderHeaders(0).OrderID
Untyped dataset : Me.dsOrders.Tables("OrderHeader").Rows(0).Item("OrderID")
Adv
of Typed DataSet –
MS
Visual studio supports intellisense
for Typed data set.
Supports compile time type checking.
Gives
better performance.
What is the difference between the value-type
variables and reference-type variables in terms of garbage collection?
The value-type variables are NOT garbage-collected, they just fall
off the stack when they fall out of scope, the reference-type objects are
picked up by GC when their references go null.
Example
Value
types: Struct Type + Enumeration Type
Reference
Type : Class + Interface + Delegate
Built-in
reference types: object + string
What is garbage collection?
One of the good features of the CLR is Garbage Collection, which runs in the
background collecting unused object references, freeing us from having to
ensure we always destroy them. In reality the time difference between you
releasing the object instance and it being garbage collected is likely to be
very small, since the GC is always running.
Why doesn't the .NET runtime offer deterministic
destruction?
Because of the garbage collection algorithm, the garbage collector works by
periodically running through a list of all the objects that are currently being
referenced by an application. The implication of this algorithm is that the
runtime doesn't get notified immediately when the final reference on an object
goes away - it only finds out during the periodic cycle/ collection sweep.
Is the lack of deterministic destruction in .NET a
problem?
It's certainly an issue that affects component design. If you have objects that
maintain expensive or scarce resources (e.g. database locks), you need to
provide some way for the client to tell the object to release the resource when
it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this
causes problems for distributed objects - in a distributed system who
calls the Dispose() method? Some form of reference-counting or
ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help
with this.
What is the
difference between Finalize and Dispose (Garbage collection) ?
Many
objects encapsulate resources that are not managed by the runtime, such as
window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way
to free those resources. Provide implicit
control by implementing the protected
Finalize Method on an object (destructor syntax in C# and the Managed
Extensions for C++). The garbage collector calls this method at some point
after there are no longer any valid references to the object. In some cases,
you might want to provide programmers using an object with the ability to explicitly release these external resources
before the garbage collector frees the object. If an external resource is
scarce or expensive, better performance can be achieved if the programmer
explicitly releases resources when they are no longer being used. To provide
explicit control, implement the Dispose
method provided by the IDisposable
Interface. The consumer of the object should call this method when it is done
using the object.
Dispose
can be called even if other references to the object are alive. Note that even when you provide explicit control
by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from
permanently leaking if the programmer fails to call Dispose.
IDisposable.Dispose()
method is responsible for 4 tasks
freeing
all managed resources
freeing
all unmanaged resources
setting
a state flag to indicate that the
object has been disposed
How do you enforce garbage collection in .NET?
System.GC.Collect();
How do you enforce garbage collection NOT to call
Finalize() ?
GC.SuppressFinalization(this).
What is the
difference between setting an object to NULL and calling objects DISPOSE method
?
Object
obj = new Object();
obj
= null
obj.dispose()
When
we set any object to null, that
means that object is subject to garbage
collection. But we dont have any control when exactly garbage collector
reclaim memory and resources from this object. So incase we have occupied some
heavy resources in any object, its better to implement a Dispose() method.
So
on calling the dispose() method explicitly, we can free the resources
immediately.
What is the
difference between Constant and Readonly?
'const':
Declared
and initialized simultaneously.
Value
is evaluated at compile time.
Holds primitive
datatypes alone ( Numbers (int and float) and strings)
Can't be static.
Use readonly values for instance constants
- storing different values for each instance of a class type.
'readonly':
Can be initialized in declaration or by code in the constructor.
Value is evaluated at run time.
Holds any
data type
Can
be either instance-level or static.
Use Compile time constants are by
definition static constants, which are shared among class instances.
Ex:
You
can initialize readonly variables to some runtime values. Let's say your
program uses current date and time as one of the values that won't change. This
way you declare
public
readonly string DateT = new DateTime().ToString().
Difference between
String and Stringbuilder?
Strings
are immutable. Meaning you cannot change a String
object once its been created.
eg:
String name = "Prasad";
means
now you cannot change the value in “name” object internally.
Whenever
you change the name a new String object is created in memory and assigns the
new value to the new space.
eg:
name = "Prasad Reddy";
A
new “name” object is created in memory and the value "Prasad Reddy"
is assigned to it
But
StringBuilder class occupies the same space even if you change the
value.
You
can use StringBuilder's Append() method to use concatenation
Use
stringbuilder whenever you need to do LOTS of string manipulations.
Note: Strings are reference types,The only reason a
string MAY be faster to instantiate
is because it doesn't allocate a buffer, it simply allocates a 4-byte pointer and sets it to null.
Whereas
a stringbuilder will allocate an initial buffer (though the default buffer size
is only sixteen characters).
What is the
difference between System.String and string?
In
short they are one and the same. The only difference per se is,
"string" is a c# specific keyword which maps to
"System.String" which is a .NET Framework class.
What is the
difference between a.Equals(b) and a == b?
For value types
== & Equals() - usually
compare two objects by value.
For
example:
int x = 10; int y = 10;
Console.WriteLine( x == y );
Console.WriteLine( x.Equals(y) );
will
display:
True
True
For
reference types –
== perform
an identity comparison, i.e. return
true if both references point to the same object.
Equals() perform a value comparison,
For
example:
StringBuilder s1 = new
StringBuilder("fred");
StringBuilder s2 = new
StringBuilder("fred");
Console.WriteLine( s1 == s2 );
Console.WriteLine( s1.Equals(s2) );
will
display:
False
True
s1
and s2 are different objects (hence == returns false).
( NOTE: Equals() supports Value comparison alone)
Bottom line:
If
you want to perform an identity
comparison use the ReferenceEquals()
method.
If
you want to perform a value
comparison, use Equals() but be
aware that it will only work if the type has overridden the default
implementation.
Avoid operator== with reference types (except perhaps
strings), as it's simply too ambiguous.
How do you define
pointers in c#?
Pointers
in C# are syntactically used in the same way as you would use in c/c++. The
only thing that is important to note is that, all code that is going to use
pointers or address of operators is unsafe in .NET world and thus has to be
marked with an unsafe modifier or has to be enclosed in an "unsafe" block. E.g.
unsafe
modifer:-
unsafe
void someFuncA(int *x)
{
//...do something
}
unsafe
static void
{
int j = 100;
someFunc(&j);
}
unsafe
block:-
void someFunction()
{
int j = 10;
unsafe
{
int* i = &j;
}
}
Lastly, all source code which contains
"unsafe" code has to be
compiled with "/unsafe" compiler option.
What is shallow
copying ? How does MemberWiseClone method work ?
A
shallow copy creates a new instance of the same type as the original object,
and then copies the nonstatic fields of the original object. If the field is a value type, a bit-by-bit copy of the field is performed.
If
the field is a reference type, the
reference is copied but the referred
object is not; therefore, the reference in the original object and the
reference in the clone point to the same object.
In
contrast, a deep copy of an object duplicates everything directly or
indirectly referenced by the fields in the object.
What is the difference
between a Debug and Release build? Is there a significant speed difference?
The
biggest difference between these is that:
In
a debug build the complete symbolic
debug information is emitted to help while debugging applications and also
the code optimization is not taken into account.
While
in release build the symbolic debug info is not emitted and the code execution
is optimized.
Also,
because the symbolic info is not emitted in a release build, the size of the
final executable is lesser than a debug executable.
In
terms of execution speed, a release executable will execute faster for sure,
but not always will this different be significant.
What is native image
cache?
Create
an image of an assembly using
Ngen.exe tool and place it the GAC.
This
native image file contains compiled processor-specific machine code.
Once
created the runtime will automatically uses this native image each time it runs
the assembly.
Therefore
it loads and execute faster, because it restores
code and data structures from the native image cache rather than generating them dynamically.
Important:
The
native image that Ngen.exe generates cannot
be shared across Application Domains.
Therefore, you cannot use Ngen.exe in application scenarios, such as ASP.NET,
that require assemblies to be shared across application domains.
Note To run Ngen.exe, you must have
administrative privileges
What is the
difference between Arrays and Structures?
Following
are the differences that i can think of :
Array - Reference
Type
- Given instance can only contain similar data type objects. Ex:
Array of string / Array of int
- Can contain both value type and reference type.
- Objects are created in the Heap
- Objects are Garbage Collected (GC)
Structure - Value
Type
- Given instance can contain different value type objects.
- Can contain only value types as objects .
- Objects are created in the Stack
- Objects are not Garbage
Collected. User has to release the objects resources.
What's an abstract class?
A class that cannot be instantiated. An abstract class is a class that
must be inherited and have the methods overridden. An abstract class is
essentially a blueprint for a class without any implementation.
When do you absolutely have to declare a class as
abstract?
1. When at least one of the methods
in the class is abstract.
2. When the class itself is inherited
from an abstract class, but not all base abstract methods have been overridden.
What's an interface?
It's an abstract class with public abstract methods all of which must be
implemented in the inherited classes.
What is the
difference between virtual method and abstract method?
Virtual
method has an implementation & provide the derived class with the option of overriding it.
Abstract
method does not provide an implementation & forces the derived class to override
the method.
What's the difference between an interface and
abstract class?
In the interface all methods must be abstract, in the abstract class some
methods can be concrete.
In
the interface no accessibility modifiers
are allowed, which is ok in abstract classes.
Can we break an
assembly in multiple modules while deploying, in case the assembly is too
large?
No at deployment
time.
Once
your assembly is created then you can’t split in multiple assemblies and no .NET
tool supports split assembly while deployment.
Yes at production
time.
Use
your favorite compiler and using different switches provided with compiler can
help in this.
How to build
assembly for different modules
You
can generate modules as output as shown following
csc
/target:module firstmodule.cs
this
will create “firstmodule.netmodule”
Note:
creating modules are not supported in Visual studio environment.
Or
csc
first.cs /out:secondmodule.netmodule
/target:module secondmodule.cs
This
will compile first.cs and create output file first.exe, as well as build
secondmodule.cs and create module output file secondmodule.netmodule:
So
like this, you can generate different modules for different code files and then
as per your choice you can add these modules to any dll or exe you want.
Note:
1.
You can not include assembly manifest in .netmodule
2.
You can generate multiple output in one compilation but one output should be
.exe or .winexe or .dll and others can be .netmodule type
How to add modules
in assembly?
csc
/addmodule:firstmodule.netmodule;secondmodule.netmodule /out:main.exe main.cs
This
will compile source file main.cs and add metadata from firstmodule.netmodule
and secondmodule.netmodule to produce main.exe
Platform Invoke:
The
platform invoke services offers a method to call functions that are exported
from an unmanaged DLL.
The
most distinctive use of PInvoke is to allow .Net components to interact with
the Win32 API.
PInvoke is also used to access functions exports defined in custom
DLLs.
In
order to call a DLL export in unmanaged code, we need to declare the method
with DllImport attribute
using
System;
using
System.Runtime.InteropServices;
namespace
TestPInvoke
{
class MyClass
{
[DllImport("kernel32.dll")]
public static extern bool Beep(int frequency, int duration);
[STAThread]
Static void
{
Beep
(random. Next (10000), 100);
}
}
}
What is
tracing?Where it used.Explain few methods available
Tracing
refers to collecting information about the application while it is running.
You
use tracing information to troubleshoot
an application.
Tracing allows us to observe and correct programming errors. Tracing enables
you to record information in various log files about the errors that might occur
at run time. You can analyze these log files to find the cause of the errors.
In
.NET we have objects called Trace Listeners. A listener is an object that
receives the trace output and outputs it somewhere; that somewhere could be a
window in your development environment, a file on your hard drive, a Windows
Event log
Is there built-in
support for tracing/logging?
Yes,
in the System.Diagnostics namespace. There are two main classes that deal with
tracing - Debug and Trace.
Use
System.Diagnostics.Trace.WriteLine for tracing to work in debug and release
builds, and System.Diagnostics.Debug.WriteLine for tracing to work only in
debug builds.
What's the difference between the Debug class and
Trace class?
Use Debug class for debug builds, use Trace class for both
debug and release builds.
Can I redirect
tracing to a file?
Yes.
Why are there five tracing levels in
System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose. Five levels range from None to
Verbose, allowing you to fine-tune the tracing activities.
Where is the output of TextWriterTraceListener
redirected?
To the Console or a text file depending on the parameter passed to the
constructor.
Can I look at the IL
for an assembly?
Yes.
MS supply a tool called Ildasm which
can be used to view the metadata and
IL for an assembly.
Can source code be
reverse-engineered from IL?
Yes,
it is often relatively straightforward to regenerate high-level source (e.g.
C#) from IL.
How can I stop my
code being reverse-engineered from IL?
Using
IL obfuscation tools.
Of
course if you are writing web services then reverse-engineering is not a
problem as clients do not have access to your IL.
What is Boxing and
unboxing?
Boxing:
The
conversion of a value type instance to an object which will be allocated in the
heap. Here copy of the value type is embed
into a newly allocated object.
Un-Boxing:
The
conversion of an object instance to a value type.
int
i = 123; // A value type
object box = i; // Boxing
int j = (int)box; // Unboxing
What are the types of authentication in .net?
We have three types of authentication:
1. Form authentication
2. Windows authentication
3. Passport
This has to be declared in web.config file.
What is the difference between a Struct and a
Class ?
A struct is a value type, while a
class is a reference type.
The
struct type is suitable for representing lightweight
objects such as Point, Rectangle, and Color. Although it is possible to
represent a point as a class, a struct is more efficient in some scenarios. For
example, if you declare an array of 1000 Point objects,you will allocate
additional memory for referencing each object. In this case, the struct is less expensive.
How big is the datatype int in .NET?
32
bits.
How big is the char?
16
bits (Unicode).
What data type should you use if you want an 8-bit
value that's signed?
sbyte.
What's the .NET datatype that allows the retrieval
of data by a unique key?
HashTable.
How do you convert a string into an integer in .NET?
Int32.Parse(string)
How do you initiate a string without escaping each
backslash?
Put an @ sign in front of the double-quoted string.
What's the access level of the visibility type
internal?
Current application.
When you inherit a protected class-level variable,
who is it available to?
Derived Classes.
Are private class-level variables inherited?
Yes, but they are not accessible.
Although they are not visible or accessible via the class interface, they are
inherited.
Describe the accessibility modifier
"protected internal".
It is available to derived classes and classes within the same Assembly (and
naturally from the base class it's declared in).
Explain encapsulation ?
The implementation is hidden, the interface is exposed.
Speaking of Boolean data types, what's different
between C# and C/C++?
There's no conversion between 0 and false, as well as any other number and
true, like in C/C++.
Where do the reference-type variables go in the
RAM?
The references go on the stack, while the objects themselves go on the heap.
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.
Will finally block get executed if the exception
had not occurred?
Yes.
Can multiple catch blocks be executed?
No, once the proper catch code fires off, the control is transferred to the
finally block (if there are any), and then whatever follows the finally block.
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.
What's the implicit name of the parameter that
gets passed into the class' set method?
Value, and it's datatype depends on whatever variable we're changing.
Does C# support multiple inheritance?
No, use interfaces instead.
What's the top .NET class that everything is
derived from?
System.Object.
How's method overriding different from
overloading?
When overriding, you change the method behavior for a derived class.
Overloading
simply involves having a method with the same name within the class.
What does the keyword virtual mean in the method
definition?
The method can be overridden.
Can you declare the override method static while
the original method is non-static?
No.
Can you override private
virtual methods?
No.
Can you prevent your class from being inherited
and becoming a base class for some other classes?
Yes, that's what keyword sealed in
the class definition is for.
Can you allow class to be inherited, but prevent
the method from being over-ridden?
Yes, just leave the class public and make the method sealed.
Why can't you specify the accessibility modifier
for methods inside the interface?
NO. They all must be public.
Can you inherit multiple interfaces?
Yes, why not.
Can you write a class without specifying
namespace? Which namespace does it belong to by default?
Yes,
you can, then the class belongs to global
namespace which has no name.
What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one
end, and deserializing and
decoding messages into data on the other end.
What is GUID , why
we use it and where?
GUID
:-- GUID is Short form of Globally Unique Identifier, a unique 128-bit number
that is produced by the Windows OS or by some Windows applications to identify
a particular component/application. A GUID is also used in a Windows registry
to identify COM DLLs.
GUIDs
can be created in a number of ways, but usually they are a combination of a few
unique settings based on specific point in time (e.g., an IP address, network
MAC address, clock date/time, etc.).
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
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.
ATTRIBUTES
Attributes
are "just" classes that
derives from System.Attribute.
These
attributes can be associated with C# classes.
These
attributes can be queried at runtime.
Attributes
give you the ability to store additional
information with your application or assembly metadata, which can be
queried at runtime by using the .NET Frameworks Reflection capabilities.
It
can be applied to assembly, class,
constructor, delegate, enum, event, field, interface, method, module,
parameter, property, return value and struct.
C# supports 2 types
of attributes: 1. PreDefined & 2.
Custom Attributes
PreDefined:
To indicate that a given class supports
serialization we use the attribute Serialization.
Serializable
attribute indicates that MySerialableClass is serializable class, which
supports the default serialization functionality provided by .net framework. To
indicate that a particular attribute should not be serialized in a class we use
the NonSerialized attribute
[Serializable()]
public
class MySerialableClass
{
public
string strSerializeMe;
public
intSerializeMe;
[NonSerialized()]
public string strLeaveMeAlone;
}
Custom :
The mechanism to invent new attributes
is also referred as ‘Custom Attributes’. We can use custom attributes to
associate information with C# classes. Custom Attributes can be used to store
information that can be stored at compile time and retrieved at run time.
Let's
look an example - Meou attribute for cat
classes
describes why some kind of cats says "Meou".
public class MeouAttribute : Attribute
{
public string Why;
public MeouAttribute(string Why)
{
this.Why=Why;
}
}
By
writing those lines we have defined custom attribute! Let's use it:
[Meou("No reason")] // normal cats say
meou without reason
public class Cat
{
}
public string
WhyISaidMeou(Cat cat)
{
Type type=cat.GetType();// Get object type
object obj=type.GetCustomAttributes()[0];//
Get first attribute
if(obj is MeouAttribute)// If it's Meou
return ((MeouAttribute)obj).Why;
else// other attribute
return "First attribute is not
Meou!";
}
Usage:
Cat
cat1=new Cat();
why1=WhyISaidMeou(cat1);//
receives "No reason"
PROPERTIES
In
dotnet its assumed that you will use properties for your public data
members.The databinding code classes in dotnet framework support properties,
not public data members.
Databinding
ties a property of an object to a UI control or Web Control or Windows Form
control. The data binding mechanism uses reflection to find a named property
public
class A
{
private string name;
public
string Name
{
get
{
return name;
}
set
{
if((value == null) || ( value.Length == 0))
throw new
ArgumentException("Name cannot be blank", "Name");
name = value;
}
}
}
if
you used public datamembers you are stuck looking for every bit of code that
sets a customer name and fixing it
there. This is time consuming
Because
properties are implemented with methods, adding multi-threaded support is
easier.
public
string Name
{
get
{
lock(this)
{
return name;
}
}
set
{
lock(this)
{
name = value;
}
}
}
immutable
: a copy is made at construction
MarshalAs :
The
MarshalAs attribute can be used to
specify how data should be marshaled between managed and unmanaged code when we
need to override the defaults.
When
we pass a string to a COM method, the default conversion is a COM BSTR;
when
we pass a string to a non-COM method, the default conversion is C- LPSTR.
But,
if you want to pass a C-style, null-terminated string to a COM method, you will
need to use MarshalAs to override the default conversion.
Pinning:
GC
moves objects in a managed heap when it compacts memory during a collection. If
we need to pass a pointer from a managed object to an unmanaged function, we
need to ensure that the GC doesn't move the object while its address is being
used through the pointer. This process of fixing an object in memory is called
pinning, and it's accomplished in C# by using the “fixed” keyword. The fixed keyword is
responsible for the pinning of managed objects
[http://blog.vuscode.com/malovicn/archive/2006/10/20/How-to-do-multiple-inheritance-in-C_2300_-_2D00_-Implementation-over-delegation-_2800_IOD_2900_.aspx]
How to do multiple inheritance in C# - Implementation over delegation (IOD)
IOD is a very simple coding techniques which allows a
developers fast implementation of an system interfaces and *multiple
inheritance* in C# Well the whole idea is basically to have a class field of
desired type and to expose functionality public properties of the class based
on hidden calls to the member field
So if we have something like Class A and Class B are
parents of a Class C.An example of that situation could be the case when we
would have a user control which should be able to handle and present a list of
customers
Illustration 1. UML Multiple inheritance diagram
Because user control and List<T> are bot classes
you couldn't do that directly, by inheriting, because there is no support for
multiple inheritance in the case of c# (and I'm happy with that because I think
multiple inheritance when not properly used very often leads to class explosion
anti pattern)
Usually developers are going to solution like this
one which I think is bad solution:
Illustration 2. Inherit the inherited one anti pattern
Our collection class would inherit user control and our
own user control would inherit that *power collection class*.
Even if it will do the task of multiple inheritance in C# I don't like this
solution because of the next facts:
a) Class B "the power collection" is now
collection class with attributes of user controls, which is bed because all
user control members are visible on collection level . What should
developer of class c think about collection class which exposes width and
height?
b)Class A could define some virtual members which could
be overridden by class B
c)Class B couldn't be reusable in case when somebody
wants to use her primarily functionality (it is a collection) but don't need
the burden of a user control
d) It is very tightly coupled model.
e)It makes almost impossible inheritance of more
than two parent classes
Code example
class CustomerCollection
: System.Windows.Forms.UserControl
{
protected virtual void Add(string customerName)
{
/*Customer collection add method specific code*/
}
protected virtual void Delete(string customerName)
{
/*Customer collection delete method specific code*/
}
}
class MyUserControl:
CustomerCollection
{
/*MyUserControl specific code goes here*/
}
The right approach is by my opining implementation over
delegation (IOD) approach which would in our case look like:
Illustration 3. Implementation over delegation multiple
inheritance pattern
This pattern is based on a fact that we define an
interface of a class B and than our class c is inheriting Class A
directly (MyUserControl should inherit UserControl) and implements a IClassB
interface.
The implementation of an interface itself is been done by
keeping private member of a class B type and inside of the interface
implementation methods we are just calling the method of that privately
contained member.
interface ICustomerCollection
{
void Add(string customerName);
void Delete(string customerName);
}
class CustomerCollection
: ICustomerCollection
{
public void Add(string
customerName)
{
/*Customer collection
add method specific code*/
}
public void Delete(string
customerName)
{
/*Customer collection
delete method specific code*/
}
}
class MyUserControl:
UserControl, ICustomerCollection
{
CustomerCollection _customerCollection=new CustomerCollection();
public void Add(string
customerName)
{
_customerCollection.Add(customerName);
}
public void Delete(string
customerName)
{
_customerCollection.Add(customerName);
}
}
WebService
-Web services provide a standard means of interoperating between different
software applications, running on a variety of platforms and/or frameworks.
Web
services, called XML Web services by Microsoft, are the components that are
instantiated via HTTP. Data is passed to, and received from, Web services using
HTTP and SOAP, which is clear text and based upon XML. Thanks to Web services,
passing data between different operating systems on different platforms has
been simplified. Web services use HTTP
to communicate, and this requires a Web server. Requests must be turned into
SOAP messages that are sent to the Web server. There, they are processed, the
object is instantiated, the method is executed, and the data is placed in an
XML format to be returned to the client. The client application processes the
XML as necessary. Given this scenario,
it is no great surprise that Web services are slow when compared to direct
binary access of objects. Without Web services, data does not have to be
serialized to XML and deserialized on the client. Requests and returns do not
have to flow through a Web server. Of
course, Web services do offer advantages. First, they can be called by almost
any client. The client does not have to be a .NET application. In fact, the
client machine does not need to be running a Windows operating system. Second,
because Web services use SOAP, the data flows across firewalls easily; all data
is passed as XML. Finally, as far as .NET is concerned, the .NET Framework
makes it incredibly easy to create Web services, and you can do so with just a
few lines of code.
Web services can be
called across platforms and OS regardless of the programming language used.
Credit
Card Validation is an example of webservice
In Dot Net
Distributed Applications are built with the help of
1.remoting
2.web
services
Web
services are programmable Application Logic accessible via standard internet
protocols
Data
Format will be in - XML
Message
Format will be in - SOAP
Accessible
via - HTTP protocol
WSDL-
Web Service Description Language
TO describe about input/output parameters
of a web service
DISCO-Dicovery
File
When we know the Service Provider
URL, we can use DISCO to find the Web Service
that will fulfill our requirement
UDDI-
Universal Description ,Discovery and Integration
This provides the info about various
Service Providers.
We can use this when we do not know
the exact URL of a service provider
What are the various ways of accessing a web
service ?
1.Asynchronous Call
Application can make a call to the Webservice and then continue todo
watever oit wants to do.When the service is ready it will notify the
application.Application can use BEGIN and END method to make asynchronous
call to the webmethod.We can use either a WaitHandle or a Delegate object
when making asynchronous call.
The
WaitHandle class share resources between several objects. It provides
several methods which will wait for the resources to become available
The
easiest and most powerful way to to implement an asynchronous call is using a
delegate object. A delegate object wraps up a callback function. The idea is
to pass a method in the invocation of the web method. When the webmethod
has finished it will call this callback function to process the result
2.Synchronous Call
Application
has to wait until execution has completed.
In
a Webservice, need to display 10 rows from a table. So DataReader or DataSet is
best choice?
WebService
will support only DataSet.
What are stateful
webservices ? How can you make a web service stateful ?
As
we all know that the nature of the HTTP protocol is stateless.It means that
each and every request of the client is to be responded without tracking that
the request is coming from the same client or different.
Similarly this is true for the Webservice
invoked over HTTP.When the request reaches the Web server, the ASP.NET runtime
manages the request by instantiating an instance of your Web service type,
deserializing the SOAP envelope XML stream, and invoking the requested method
passing parameters if applicable. A new instance of the Web service type is
created for each HTTP request targeting the service, so any information stored
in data fields contained within the type are recreated for each round trip. If
you want to persist state you must specifically enable state for the method as
shown here:
[
WebMethod(EnableSession=true) ]
public
object getcatalog()
{
return
Session["catalog"];
}
[
WebMethod(EnableSession=true) ]
public
void change(object val)
{
Session["catalog"]
= val;
}
This will cause the ASP.NET runtime to create
an HttpSessionState object the first time a method that has session state
enabled is called. Each subsequent call to a method that has session enabled
will share the same session state object, so long as the client passes a session
cookie with each subsequent request. If the client does not pass a session
cookie ASP.NET will create a new session for each call.
The client invoking the service must be
session aware, something we take for granted when we navigate Web sites with a
browser. The client proxy created for a .NET Web service includes a
CookieContainer property, and .NET provides us with CookieContainer type that
we can instantiate and assign the proxy as follows:
// create cookie container once for the
duration of the session
System.Net.CookieContainer
cookies = new System.Net.CookieContainer();
//
each time invoking the service, assign the same cookie container before
invoking methods
localhost.SessionService1
svc = new localhost.SessionService1();
svc.CookieContainer
= cookies;
MessageBox.Show(svc.UpdateHitCounter());
When the proxy invokes the service, it
serializes the method call into a SOAP envelope, and builds an HTTP request
with appropriate headers, and posts to the endpoint URI of the Web service. The
HTTP headers will include the session cookie if one is provided here, and
that's how ASP.NET can find the right session state object to make it available
to your Web method.
Check
: http://groups.msn.com/MumbaiUserGroup/june2005.msnw
What is Remoting?
The
process of communication between different operating system processes,
regardless of whether they are on the same computer. The .NET remoting system
is an architecture designed to simplify communication between objects living in
different application domains, whether on the same computer or not, and between
different contexts, whether in the same application domain or not.
What is the difference between .Net Remoting and
Web Services?
Although
we can develop an application using both technologies, each of them has its
distinct advantages. Yes you can look at them in terms of performance but you
need to consider your need first. There are many other factors such
authentications, authorizing in process that need to be considered.
Point |
Remoting |
Webservices |
If your application needs interoperability
with other platforms or operating systems |
No |
Yes, Choose Web Services because it is
more flexible in that they are support SOAP. |
If performance is the main requirement
with security |
You should use the TCP channel and the
binary formatter |
No |
Complex Programming |
Yes |
No |
State Management |
Supports a range of state management,
depending on what object lifetime scheme you choose (single call or singleton
call). |
Its stateless service management (does not
inherently correlate multiple calls from the same user) |
Transport Protocol |
It can access through TCP or HTTP channel. |
It can be access only through HTTP
channel. |
Can you give an example of when it would be appropriate to
use a web service as opposed to non-serviced .NET component
Web service is one of main component in Service Oriented Architecture. You
could use web services when your clients and servers are running on different
networks and also different platforms. This provides a loosely coupled system.
And also if the client is behind the firewall it would be easy to use web
service since it runs on port 80 (by default) instead of having some thing else
in Service Oriented Architecture applications.
What is the standard
you use to wrap up a call to a Web service
"SOAP.”
What is the transport protocol you use to call a
Web service SOAP
HTTP with SOAP
What protocols are
used in .net remoting?
HTTP,TCP\IP
and custom protocols.
What does WSDL stand for?
"WSDL stands for Web Services Dsescription Langauge. There is WSDL.exe
that creates a .wsdl Files which defines how an XML Web service behaves and
instructs clients as to how to interact with the service.
eg: wsdl http://LocalHost/WebServiceName.asmx"
Where on the Internet would you look for Web
Services?
www.uddi.org
What does WSDL stand for?
Web Services Description Language
To test a Web service you must create a windows
application or Web application to consume
this service?
False.
What are VSDISCO files?
VSDISCO files are DISCO files that support dynamic discovery of Web services.
If you place the following VSDISCO file in a directory on your Web server, for
example, it returns references to all ASMX and DISCO files in the
host directory and any subdirectories not noted in <EXCLUDE>elements:
<DYNAMICDISCOVERY
xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">
<EXCLUDE path="_vti_cnf" />
<EXCLUDE path="_vti_pvt" />
<EXCLUDE path="_vti_log" />
<EXCLUDE path="_vti_script" />
<EXCLUDE path="_vti_txt" />
</DYNAMICDISCOVERY>
How does dynamic discovery work?
ASP.NET maps the file name extension VSDISCO to an HTTP handler that scans the
host directory and subdirectories for ASMX and DISCO files and returns a
dynamically generated DISCO document. A client who requests a VSDISCO file gets
back what appears to be a static DISCO document.
Note that VSDISCO files are disabled in the release version of ASP.NET. You can
reenable them by uncommenting the line in the
<HTTPHANDLERS>section of Machine.config that maps *.vsdisco to
System.Web.Services.Discovery.DiscoveryRequestHandler and granting the
ASPNET user account permission to read the IIS metabase. However,
Microsoft is actively discouraging the use of VSDISCO files because they could
represent a threat to Web server security.
Is it possible to prevent a browser from caching an ASPX
page?
Just
call SetNoStore on the HttpCachePolicy object exposed through the Response
object's Cache property, as demonstrated here:
<%@ Page Language="C#"
%>
<%
Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
%>
SetNoStore
works by returning a Cache-Control: private, no-store header in the HTTP
response. In this example, it prevents caching of a Web page that shows the
current time.
Can two different programming languages be mixed in a
single ASMX file?
No.
What is WSDL?
WSDL
is the Web Service Description Language, and it is implemented as a specific
XML vocabulary. While it's very much more complex than what can be described
here, there are two important aspects to WSDL with which you should be aware.
First, WSDL provides instructions to consumers of Web Services to describe the
layout and contents of the SOAP packets the Web Service intends to issue.
It's an interface description document, of sorts. And second, it isn't intended
that you read and interpret the WSDL. Rather, WSDL should be processed by
machine, typically to generate proxy source code (.NET) or create dynamic
proxies on the fly (the SOAP Toolkit or Web Service Behavior).
What is a Windows Service and how does its
lifecycle differ from a "standard" EXE?
Windows service is a application that runs in the background. It is equivalent
to a NT service.
The executable created is not a Windows application, and hence you can't just
click and run it . it needs to be installed as a service, VB.Net has a facility
where we can add an installer to our program and then use a utility to install
the service. Where as this is not the case with standard exe
How can a win service developed in .NET be
installed or used in Win98?
Windows service cannot be installed on Win9x machines even though the .NET
framework runs on machine.
Can you debug a Windows Service? How ?
Yes
we can debug a Windows Service.
Attach
the WinDbg debugger to a service after the service starts
Does the .NET Framework have in-built support for
serialization?
There are two separate mechanisms provided by the .NET class library -
XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer
for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are
available for use in your own code.
Can I customise the serialization process?
Yes. XmlSerializer supports a range of attributes that can be used to configure
serialization for a particular class. For example, a field or property can be
marked with the [XmlIgnore] attribute to exclude it from serialization. Another
example is the [XmlElement]
attribute,
which can be used to specify the XML element name to be used for a particular
property or field.
Serialization via SoapFormatter/BinaryFormatter can also be controlled to some
extent by attributes. For example, the [NonSerialized] attribute is the
equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the
serialization process can be acheived by implementing the the ISerializable
interface on the class whose instances are to be serialized.
Why is XmlSerializer so slow?
There is a once-per-process-per-type overhead with XmlSerializer. So the first
time you serialize or deserialize an object of a given type in an application,
there is a significant delay. This normally doesn't matter, but it may mean,
for example, that XmlSerializer is a poor choice for loading configuration settings
during startup of a GUI application.
Why do I get errors when I try to serialize a
Hashtable?
XmlSerializer will refuse to serialize instances of any class that implements
IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this
restriction.
Which are the
abstract classes available under system.xml namespace?
The
System.XML namespace provides XML related processing ability in .NET framework.
XmlReader and XMLWriter are the two abstract classes at the core of .NET
Framework XML classes:
1.
XmlReader provides a fast, forward-only, read-only cursor for processing an XML
document stream.
2. XmlWriter provides an interface for producing XML document streams that
conform to the W3C's XML standards.
Both
XmlReader and XmlWriter are abstract base classes, which define the
functionality that all derived classes must support.
What are the derived
classes from xmlReader and xmlWriter?
Both
XmlReader and XmlWriter are abstract base classes, which define the
functionality that all derived classes must support.
There are three concrete implementations of XmlReader:
1.XmlTextReader
2.XmlNodeReader
3.XmlValidatingReader
There are two concrete implementations of XmlWriter:
1.XmlTextWriter
2.XmlNodeWriter
XmlTextReader and XmlTextWriter support reading data to/from text-based stream,
while XmlNodeReader and XmlNodeWriter are designed for working with in-memory
DOM tree structure. The custom readers and writers can also be developed to
extend the built-in functionality of XmlReader and XmlWriter.
-DataSet vs.
DataReader
To
determine whether to use the DataSet or the DataReader when you design your
application, consider the level of functionality that is needed in the
application.
Use
the DataSet in order to do the following with your application:
Navigate
between multiple discrete tables of results.
Manipulate
data from multiple sources (for example, a mixture of data from more than one
database, from an XML file, and from a spreadsheet).
Exchange
data between tiers or using an XML Web service. Unlike the DataReader, the
DataSet can be passed to a remote client.
Reuse
the same set of rows to achieve a performance gain by caching them (such as for
sorting, searching, or filtering the data).
Perform
a large amount of processing per row. Extended processing on each row returned
using a DataReader ties up the connection serving the DataReader longer than
necessary, impacting performance.
Manipulate
data using XML operations such as Extensible Stylesheet Language Transformations
(XSLT transformations) or XPath queries.
Use
the DataReader in your application if you:
Do
not need to cache the data.
Are
processing a set of results too large to fit into memory.
Need
to quickly access data once, in a forward-only and read-only manner.
Note The
DataAdapter uses the DataReader when filling a DataSet. Therefore, the
performance gained by using the DataReader instead of the DataSet is that you
save on the memory that the DataSet would consume and the cycles it takes to populate
the DataSet. This performance gain is, for the most part, nominal so you should
base your design decisions on the functionality required.
When
using a DataSet, you will often make use of a DataAdapter (and possibly a
CommandBuilder) to interact with your data source. Also, when using a DataSet,
you may employ a DataView to apply sorting and filtering to the data in the
DataSet
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnadonet/html/adonetbest.asp
ExecuteScalar and
ExecuteNonQuery
If
you want to return a single value such as the result of Count(*), Sum(Price),
or Avg(Quantity), you can use Command.ExecuteScalar. ExecuteScalar returns the
value of the first column of the first row, returning result set as a scalar
value. ExecuteScalar both simplifies your code and improves performance by
accomplishing in a single step, what would have been a two-step process using a
DataReader (that is, ExecuteReader + Get the value).
When
using SQL statements that do not return rows, like those that modify data (such
as INSERT, UPDATE, or DELETE) or return only output parameters or return
values, use ExecuteNonQuery. This removes any unnecessary processing to create
an empty DataReader.
ADO.Net -
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/daag.asp
If you are designing a data access layer for
a .NET-based application, you should use Microsoft® ADO.NET as the data access
model. ADO.NET is feature rich and supports the data access requirements of
loosely coupled, multitier Web applications and Web services.
ADO.NET is the data access model for
.NET-based applications. It can be used to access relational database systems
such as SQL Server 2000, Oracle, and many other data sources for which there is
an OLE DB or ODBC provider
One of the key changes that ADO.NET
introduces is the replacement of the ADO Recordset object with a combination of
the DataTable, DataSet, DataAdapter, and DataReader objects
ADO.NET relies on the services of .NET data
providers. These provide access to the underlying data source, and they
comprise four key objects (Connection, Command, DataReader, and DataAdapter).
The
SQL Server .NET Data Provider. This is a provider for Microsoft SQL Server 7.0
and later databases. It is optimized for accessing SQL Server, and it
communicates directly with SQL Server by using the native data transfer
protocol of SQL Server. Always use this provider when you connect to SQL Server
7.0 or SQL Server 2000.
The
Oracle .NET Data Provider. The .NET Framework Data Provider for Oracle enables
data access to Oracle data sources through Oracle client connectivity software.
The data provider supports Oracle client software version 8.1.7 and later.
The
OLE DB .NET Data Provider. This is a managed provider for OLE DB data sources.
It is slightly less efficient than the SQL Server .NET Data Provider, because
it calls through the OLE DB layer when communicating with the database. Note
that this provider does not support the OLE DB provider for Open Database Connectivity
(ODBC), MSDASQL. For ODBC data sources, use the ODBC .NET Data Provider
(described later) instead.
The
ODBC .NET Data Provider. The .NET Framework Data Provider for ODBC uses native
ODBC Driver Manager (DM) to enable data access by means of COM interoperability.
Namespace
Organization
System.Data.SqlClient.
Contains the SQL Server .NET Data Provider types.
System.Data.OracleClient.
Contains the Oracle .NET Data Provider
System.Data.OleDb.
Contains the OLE DB .NET Data Provider types.
System.Data.Odbc.
Contains the ODBC .NET Data Provider types.
System.Data.
Contains provider-independent types such as the DataSet and DataTable.
The SqlClient implementations are prefixed
with "Sql" and the OleDb implementations are prefixed with
"OleDb."
______________________
Generic Programming
:
If you are likely to target different data
sources and want to move your code from one to the other, consider programming
to the IDbConnection, IDbCommand, IDataReader, and IDbDataAdapter interfaces
located within the System.Data namespace.
In
brief, all data provider classes such as a connection, command, data adapter
and data reader are inherited from interfaces.
Now
you can write a generic class, which can access data by using OLE DB, SQL, and
ODBC data providers based on the user selection at runtime.
Each
data provider's implements some interfaces. These interfaces are defined in the
System.Data namespace. For example, SqlConnection, OleDbConnection, and
OdbcConnection classes are derived from IDbConnection interface.
Similar
to the connection classes, other ADO.NET components such as DataAdapter,
DataReader, Command also implement their relative interfaces.
Write
a class GenericAdoNetComp, which provides two methods GetConnection and
GetDataAdapter
public
IDbConnection GetConnection(int connType, string connString)
public
IDbDataAdapter GetDataAdapter(int connType, string connString, string sql)
using
System;
using
System.Data;
using
System.Data.Common;
using
System.Data.OleDb;
using
System.Data.SqlClient;
using
Microsoft.Data.Odbc;
namespace
GenericDataAccessApp
{
public class GenericAdoNetComp
{
private IDbConnection
idbConn = null;
private IDbDataAdapter
idbAdapter = null;
private DbDataAdapter
dbAdapter = null;
private IDataReader iReader = null;
public GenericAdoNetComp()
{}
// GetConnection returns
IDbConnection
public IDbConnection
GetConnection(int connType, string connString)
{
switch(connType)
{
case
1: // OleDb Data Provider
idbConn
= new OleDbConnection(connString);
break;
case
2: // Sql Data Provider
idbConn
= new SqlConnection(connString);
break;
case
3: // ODBC Data Provider
idbConn
= new OdbcConnection(connString);
break;
//
case 3: // Add your custom data provider
default:
break;
}
return
idbConn;
}
// GetDataAdapter
returns IDbDataAdapter
public IDbDataAdapter GetDataAdapter(int connType,string
connString,string sql)
{
switch(connType)
{
case 1: //
OleDb Data Provider
idbAdapter = new
OleDbDataAdapter(sql, connString);
break;
case 2: //
Sql Data Provider
idbAdapter
= new SqlDataAdapter(sql, connString);
break;
case 3: //
ODBC Data Provider
idbAdapter
= new OdbcDataAdapter(sql, connString);
break;
// case 3:
// Add your custom data provider
default:
break;
}
return
idbAdapter;
}
}
}
Consumer Application
Now let's see how to use this class in a
Windows application. To test this, I create a Windows application.As you can pretty
much guess from this form, I provide a user options to select the kind of data
provider they want to use.Based on the selection, the Connect button connects
to a database and fills data from the database to the DataGrid.
Now
in my application, I define the following variables.
private
string connString, sql;
IDbConnection
conn = null;
IDbDataAdapter
adapter = null;
And
here is the code on the Connect button event handler, which creates an instance
of GenericAdoNetComp class and calls its GetConnection and GetDataAdapter
methods. Once you've a DataAdapter, you can simply call Fill and Update methods
to read and write data.
private
void ConnectBtn_Click(object sender, System.EventArgs e)
{
GenericAdoNetComp genDP = new
GenericAdoNetComp();
sql = "SELECT * FROM Employees";
if(radioButton1.Checked)
{
connString =
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\\Northwind.mdb";
conn = genDP.GetConnection(1,
connString);
adapter =
genDP.GetDataAdapter(1, connString, sql);
}
else if (radioButton2.Checked)
{
connString = "Data
Source=MCB;Initial Catalog=Northwind;user id=sa;password=;";
conn = genDP.GetConnection(2,
connString);
adapter = genDP.GetDataAdapter(2,
connString, sql);
}
else if (radioButton3.Checked)
{
// Construct your connection
string here
conn = genDP.GetConnection(3,
connString);
adapter =
genDP.GetDataAdapter(3, connString, sql);
}
try
{
conn.Open();
// Fill a DataSet
DataSet ds = new
DataSet();
adapter.Fill(ds);
dataGrid1.DataSource =
ds.Tables[0].DefaultView;
}
catch(Exception exp)
{
MessageBox.Show(exp.Message);
}
finally
{
conn.Close();
}
}
__________________
MSMQ -Microsoft
Message Queuing
Microsoft
Message Queuing (MSMQ) is a feature of the Windows operating system. MSMQ
provides an inter-application messaging infrastructure, implementing the
features for sending messages between disconnected applications. This is a crucial
requirement for using Business tier components in an application.
Managed Providers
Managed
providers works with in the boundaries of Common Language Runtime. There are no
COM interoperability, obviously no worry about serialization and marshaling. Managed
providers expose provider specific behavior through methods, properties and
interfaces, which are much efficient than OLEDB providers. Hence the final
result will be better performance. Currently there are matured managed
providers for SQL Server and Oracle database (SqlClient and OracleClient). We
are still waiting for System.Data.Db2Client namespace. So
current option is to use other third party managed providers available in
market (IBM DB2 UDB 8.1.2)ome of them are still under development.
Advantage of
ADO.Net?
ADO.NET
Does Not Depend On Continuously Live Connections
Database
Interactions Are Performed Using Data Commands
Data
Can Be Cached in Datasets
Datasets
Are Independent of Data Sources
Data
Is Persisted as XML
Schemas
Define Data Structures
Differences
between dataset.clone and dataset.copy?
Clone
- Copies the structure of the DataSet, including all DataTable schemas,
relations, and constraints.Does not copy any data
Copy - Copies both the structure and data for this DataSet
NUnit
-NUnit
is a unit-testing framework for all .Net languages
-It is written entirely in C#
AJAX
- AJAX stands for Asynchronous JavaScript And XML.
-
-With AJAX you can create better, faster, and more user-friendly web
applications.
-
-
-With
What is QTP?
-
Quick Test is a graphical interface record-playback automation tool
-Quick Test enables you to test standard web objects and ActiveX controls,Java
applets,multimedia objects on Applications as well as standard Windows
applications, Visual Basic 6 applications and.NET framework applications.
-Quick Test stores the definitions for application objects in a file called the
Object Repository. As you record your test, Quick Test will add an entry for
each item you interact with. Each Object Repository entry will be identified by
a logical name (determined automatically by Quick Test), and will contain a set
of properties (type, name, etc) that uniquely identify each object.
What is Parameterizing Tests?
- When you test your application, you may want to check how it performs the
same operations with multiple sets of data.
For example, suppose you want to check how your application responds to ten
separate sets of data. You could record ten separate tests, each with its own
set of data. Alternatively, you can create a parameterized test that runs ten
times: each time the test runs, it uses a different set of data
SOA
-whose goal is to achieve loose coupling among interacting software agents.
-It is independent of the technology used for implementation
-It provides a better relationship between the business and information
systems(that support the business)
-Its life cycle comprises of MODEL - ASSEMBLE - DEPLOY - MANAGE
-here all functions are defined as reusable services which are defined by a
service interface.
-dynamic nature of SOA require an additional level of security, management, and
control
NHibernate
-NHibernate
is a .NET based -"object persistence library" for relational
databases
-NHibernate handles persisting your .NET objects to and from an underlying relational
database.
Rather than you having to write SQL to get your objects in and out of the
database, NHibernate takes care of this for you. Your code only needs to be
concerned with your objects, NHibernate generates the SQL and makes sure that
things end up in the correct tables and columns.
-Persistent classes do not need to implement any interface or inherit from a
special base class -5 things to do
Create a .NET class that needs to be persisted.
Create the table to persist the .NET class.
Create a mapping file specifying how to persist the .NET class' properties
Create a configuration file specifying how to connect to your database
Use the NHibernate API
Making use of NHibernate in your source is pretty straightforward
-Add a reference to NHibernate.dll (in the 'bin' folder where you installed
NHibernate)
-Create a configuration object
-Tell the configuration about the type of objects you want to store
-Create a session to your database of choice
-Load, save and query your objects
-Flush() your Session back to the database
using NHibernate;
Configuration cfg = new Configuration();
cfg.AddAssembly("classname");
ISessionFactory factory = cfg.BuildSessionFactory(); //represents a connection
to your backend database
ISession session = factory.OpenSession(); //represents a NHibernate managed
Transaction.
User newUser = new User();
newUser.Id = "joe_cool";
newUser.UserName = "Joseph Cool";
newUser.Password = "abc123";
newUser.EmailAddress = "joe@cool.com";
newUser.LastLogon = DateTime.Now;
// Tell NHibernate that this object should be saved
session.Save(newUser);
// commit all of the changes to the DB and close the ISession
transaction.Commit();
session.Close();
---------------------------------------------------------------------------------------------------------