Loading...
Gadget by Dot Net Spiders.

Saturday, November 27, 2010

Difference between Properties and Indexers : Properties Vs Indexers

Properties and indexers are two of the most important concepts in C#.Properties are popularly known as 'Smart fields' and they provide access to the fields of a class whereas indexers are popularly known as 'Smart arrays' and they allows objects to be indexed as an array which is useful for looping or iterating or data binding operations.Defining an indexer is much like defining property but there exists a subtle differences between these two.

What is Property?

Properties are natural extension of data fields.The main advantage of using a Property over a public field is, with the property, we can perform some validation or any other logic in the Get and Set accessors before returning any values or assigning to the private field.Another advantage of property is that the data fields are not directly accessible out side the class.We must use the set/get methods to access the data fields.
The general form of declaring a property is as follows. The first part of the syntax looks quite similar to a field declaration and second part consists of a get accessor and a set accessor.


{
get
{
   // Get codes goes here

}
set
{
   // Set codes goes here

}}

Where access_modifier can be private, public, protected or internal. The return_type can be any valid C# type.
The code block for the get accessor is executed when the property is read; the code block for the set accessor is executed when the property is assigned a new value. A property without a set accessor is considered read-only. A property without a get accessor is considered write-only. A property with both accessors is read-write.
public class Today 
{ 
 private int day = 31; //"backing store" 
 public int Day
 { 
  get 
  { 
   return day;
   } 
  set
  {
   if ((value > 0) && (value < 32)) 
   { 
    day = value; 
   } 
  } 
 }
} 
In this example, Day is declared as a property so that the set accessor can make sure the Day value is set between 1 and 31.The body of the get accessor is similar to that of a method. It must return a value of the property type. The set accessor is similar to a method whose return type is void. It uses an implicit parameter called value, whose type is the type of the property. When you reference the property, the get accessor is invoked to read the value of the property. It is a bad programming style to change the state of the object by using the get accessor.The get accessor can either be used to return the field value or to compute it and return it.When you assign a value to the property, the set accessor is invoked with an argument that provides the new value.
Today t1 = new Today();
t1.Day = 25;  // the set accessor is invoked here                

System.Console.Write(t1.Day);   // the get accessor is invoked here
Properties can be marked as public, private, protected, internal, or protected internal. The get and set accessors for the same property may have different access modifiers. A property may be declared as a static property using the static keyword. This makes the property available to callers at any time, even if no instance of the class exists. A property may be marked as a virtual property using the virtual keyword. This allows derived classes to override the property behavior using the override keyword.A property overriding a virtual property can also be sealed, specifying that for derived classes it is no longer virtual. Lastly, a property can be declared abstract, meaning there is no implementation in the class, and derived classes must write their own implementation.Moreover,it is an error to use a virtual , abstract , or override modifier on an accessor of a static property. 


Drawbacks: 
  1.  A property cannot be passed as an out or ref parameter to a method; a field can.
  2. A property method may take a long time to execute than a datafield. 
What is Indexer ? 

Properties allow you to access objects state with field-like syntax. An indexer is similar to a property.As with properties, we use get and set when defining an indexer. Unlike properties, you are not obtaining a specific data member; rather, you are obtaining a value from the object itself. When you define a property, you define a property name.With indexers, instead of creating a name as you do with properties, you use the this keyword, which refers to the object instance and thus the object name is used. The general form of declaring an indexer is follows. this[argument list]

{
  get
{
// Get codes goes here
}
set
{
 // Set codes goes here
 }
 }
Where the modifier can be private, public, protected or internal .The return type can be any valid C# types. The 'this' is a special keyword in C# to indicate the object of the current class. The formal-argument-list specifies the parameters of the indexer.The indexers must have at least one parameter. Other wise the compiler will generate a compilation error.Indexers cannot be static. This is because static methods do not have access to ‘this’.
class Customer
{
 private string[] name = new string[10]; 
 public string this[int index] 
 { 
    get
  {
       return name[index]; 
     } 
     set 
    { 
       name[index] = value; 
     } 
 } 
} 

class IndexTest
{
  public static void Main() 
  { 
     Customer cust = new Customer(); 
     cust[0] = "Schumaker"; 
     cust[1] = "levin"; 
     cust[2] = "thomson"; 
     Console.WriteLine("{0}\n,{1}\n,{2}\n,", cust[0], cust[1], cust[2]);
     Console.ReadLine();
  }
} 
Differences between properties and indexers  

  1. Properties are accessed by names but indexers are accessed using indexes. 
  2. Properties can be static but Indexers should always be instance members of the class.we cannot have static indexers.
  3. The get accessor of a property does not accept any parameter but the get accessor of the indexer accepts the same formal parameters as the indexer.
  4. The set accessor of a property contains an implicit parameter called "value". The set accessor of an indexer contains the same formal parameters as that of the indexer and also the "value" as an implicit parameter.

Property

Indexer

Allows methods to be called as if they were public data members.

Allows elements of an internal collection of an object to be accessed by using array notation on the object itself.

Accessed through a simple name.

Accessed through an index.

Can be a static or an instance member.

Must be an instance member.

A get accessor of a property has no parameters.

A get accessor of an indexer has the same formal parameter list as the indexer.

A set accessor of a property contains the implicit value parameter.

A set accessor of an indexer has the same formal parameter list as the indexer, and also to the value parameter.

Supports shortened syntax with Auto-Implemented Properties (C# Programming Guide).

Does not support shortened syntax.


Read more On "Difference between Properties and Indexers : Properties Vs Indexers" >>>

Friday, October 30, 2009

Dot Net Framework FAQ - Part Ten

What does this useful command line do? tasklist /m "mscor*"
Lists all the applications and associated tasks/process currently running on the system with a module whose name begins "mscor" loaded into them; which in nearly all cases means "all the .NET processes"
BUF7H9VJ2R8S.

What’s wrong with a line like this? DateTime.Parse(myString);
Therez nothing wrong with this declaration.Converts the specified string representation of a date and time to its DateTime equivalent.But If the string is not a valid DateTime,It throws an exception.

What are PDBs? Where must they be located for debugging to work?
A program database (PDB) files holds debugging and project state information that allows incremental linking of debug configuration of your program.There are several different types of symbolic debugging information. The default type for Microsoft compiler is the so-called PDB file. The compiler setting for creating this file is /Zi, or /ZI for C/C++(which creates a PDB file with additional information that enables a feature called ""Edit and Continue"") or a Visual Basic/C#/JScript .NET program with /debug.

A PDB file is a separate file, placed by default in the Debug project subdirectory, that has the same name as the executable file with the extension .pdb. Note that the Visual C++ compiler by default creates an additional PDB file called VC60.pdb for VisulaC++6.0 and VC70.PDB file for VisulaC++7.0. The compiler creates this file during compilation of the source code, when the compiler isn't aware of the final name of the executable. The linker can merge this temporary PDB file into the main one if you tell it to, but it won't do it by default. The PDB file can be useful to display the detailed stack trace with source files and line numbers.

What is FullTrust? Do GAC’ed assemblies have FullTrust?
Before the .NET Framework existed, Windows had two levels of trust for downloaded code. This old model was a binary trust model. You only had two choices: Full Trust, and No Trust. The code could either do anything you could do, or it wouldn't run at all.

The permission sets in .NET include FullTrust, SkipVerification, Execution, Nothing, LocalIntranet, Internet and Everything. Full Trust Grants unrestricted permissions to system resources. Fully trusted code run by a normal, nonprivileged user cannot do administrative tasks, but can access any resources the user can access, and do anything the user can do. From a security standpoint, you can think of fully trusted code as being similar to native, unmanaged code, like a traditional ActiveX control.
GAC assemblies are granted FullTrust. In v1.0 and 1.1, the fact that assemblies in the GAC seem to always get a FullTrust grant is actually a side effect of the fact that the GAC lives on the local machine. If anyone were to lock down the security policy by changing the grant set of the local machine to something less than FullTrust, and if your assembly did not get extra permission from some other code group, it would no longer have FullTrust even though it lives in the GAC.


What does this do? gacutil /l | find /i "Corillian"
The Global Assembly Cache tool allows you to view and manipulate the contents of the global assembly cache and download cache.The tool comes with various optional params to do that.
""/l"" option Lists the contents of the global assembly cache. If you specify the assemblyName parameter(/l [assemblyName]), the tool lists only the assemblies matching that name.

What does this do .. sn -t foo.dll ?
Sn -t option displays the token for the public key stored in infile. The contents of infile must be previously generated using -p.
Sn.exe computes the token using a hash function from the public key. To save space, the common language runtime stores public key tokens in the manifest as part of a reference to another assembly when it records a dependency to an assembly that has a strong name. The -tp option displays the public key in addition to the token.

How do you generate a strong name?
.NET provides an utility called strong name tool. You can run this toolfrom the VS.NET command prompt to generate a strong name with an option "-k" and providing the strong key file name. i.e. sn- -k <>
What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?
The Debug build is the program compiled with full symbolic debug information and no optimization. The Release build is the program compiled employing optimization and contains no symbolic debug information. These settings can be changed as per need from Project Configuration properties. The release runs faster since it does not have any debug symbols and is optimized.

Explain the use of virtual, sealed, override, and abstract.
Abstract: The keyword can be applied for a class or method.

  1. Class: If we use abstract keyword for a class it makes theclass an abstract class, which means it cant be instantiated. Thoughit is not nessacary to make all the method within the abstract class to be virtual. ie, Abstract class can have concrete methods
  2. Method: If we make a method as abstract, we dont need to provide implementationof the method in the class but the derived class need to implement/override this method.

Sealed: It can be applied on a class and methods. It stops the type from further derivation i.e no one can derive class
from a sealed class,ie A sealed class cannot be inherited.A sealed class cannot be a abstract class.A compile time error is thrown if you try to specify sealed class as a base class.
When an instance method declaration includes a sealed modifier, that method is said to be a sealed method. If an instance method declaration includes the sealed modifier, it must also include the override modifier. Use of the sealed modifier prevents a derived class from further overriding the method For Egs: sealed override public void Sample() { Console.WriteLine("Sealed Method"); }

Virtual & Override: Virtual & Override keywords provides runtime polymorphism. A base class can make some of its methods
as virtual which allows the derived class a chance to override the base class implementation by using override keyword.

For e.g. class Shape
{
int a
public virtual void Display()
{
Console.WriteLine("Shape");
}
}

class Rectangle:Shape
{
public override void Display()
{
Console.WriteLine("Derived");
}
}


Explain the importance and use of each, Version, Culture and PublicKeyToken for an assembly.
This three alongwith name of the assembly provide a strong name or fully qualified name to the assembly. When a assebly is referenced with all three.
PublicKeyToken: Each assembly can have a public key embedded in its manifest that identifies the developer. This ensures that once the assembly ships, no one can modify the code or other resources contained in the assembly.

Culture: Specifies which culture the assembly supports

Version: The version number of the assembly.It is of the following form major.minor.build.revision.
Explain the differences between public, protected, private and internal.
These all are access modifier and they governs the access level. They can be applied to class, methods, fields.

Public: Allows class, methods, fields to be accessible from anywhere i.e. within and outside an assembly.
Private: When applied to field and method allows to be accessible within a class.
Protected: Similar to private but can be accessed by members of derived class also.
Internal: They are public within the assembly i.e. they can be accessed by anyone within an assembly but outside assembly they are not visible.

What is the difference between typeof(foo) and myFoo.GetType()?
Typeof is operator which applied to a object returns System.Type object. Typeof cannot be overloaded white GetType has lot of overloads.GetType is a method which also returns System.Type of an object. GetType is used to get the runtime type of the object.
Example from MSDN showing Gettype used to retrive type at untime:-
public class MyBaseClass: Object {
}
public class MyDerivedClass: MyBaseClass {
}
public class Test {
public static void Main() {
MyBaseClass myBase = new MyBaseClass();
MyDerivedClass myDerived = new MyDerivedClass();
object o = myDerived;
MyBaseClass b = myDerived;
Console.WriteLine("mybase: Type is {0}", myBase.GetType());
Console.WriteLine("myDerived: Type is {0}", myDerived.GetType());
Console.WriteLine("object o = myDerived: Type is {0}", o.GetType());
Console.WriteLine("MyBaseClass b = myDerived: Type is {0}", b.GetType());
}
}

/*
This code produces the following output.
mybase: Type is MyBaseClass
myDerived: Type is MyDerivedClass
object o = myDerived: Type is MyDerivedClass
MyBaseClass b = myDerived: Type is MyDerivedClass
*/


Can "this" be used within a static method?
No 'This' cannot be used in a static method. As only static variables/methods can be used in a static method.

What is the purpose of XML Namespaces?
An XML Namespace is a collection of element types and attribute names. It consists of 2 parts

  1. The first part is the URI used to identify the namespace
  2. The second part is the element type or attribute name itself.
Together they form a unique name. The various purpose of XML Namespace are

  1. Combine fragments from different documents without any naming conflicts. (See example below.)
  2. Write reusable code modules that can be invoked for specific elements and attributes. Universally unique names guarantee that such modules are invoked only for the correct elements and attributes.
  3. Define elements and attributes that can be reused in other schemas or instance documents without fear of name collisions. For
example, you might use XHTML elements in a parts catalog to provide part descriptions. Or you might use the nil attribute
defined in XML Schemas to indicate a missing value.
<>
<>DVS1< /Name >
< addr="http://www.tu-darmstadt.de/ito/addresses">
<>Wilhelminenstr. 7< /addr:Street >
<>Darmstadt< /addr:City >
<>Hessen< /addr:State >
<>Germany< /addr:Country >
<>D-64285< /addr:PostalCode >
< /addr:Address >
< serv="http://www.tu-darmstadt.de/ito/servers">
<>OurWebServer< /serv:Name >
<>123.45.67.8< /serv:Address >
< /serv:Server >
< /Department >

What is difference between MetaData and Manifest ?
Metadata and Manifest forms an integral part of an assembly( dll / exe ) in .net framework .


Out of which Metadata is a mandatory component , which as the name suggests gives the details about various components of IL code viz : Methods , properties , fields , class etc.

Essentially Metadata maintains details in form of tables like Methods Metadata tables , Properties Metadata tables , which maintains the list of given type and other details like access specifier , return type etc.
Now Manifest is a part of metadata only , fully called as “manifest metadata tables” , it contains the details of the references needed by the assembly of any other external assembly / type , it could be a custom assembly or standard System namespace .

Now for an assembly that can independently exists and used in the .Net world both the things ( Metadata with Manifest ) are mandatory , so that it can be fully described assembly and can be ported anywhere without any system dependency . Essentially .Net framework can read all assembly related information from assembly itself at runtime .

But for .Net modules , that can’t be used independently , until they are being packaged as a part of an assembly , they don’t contain Manifest but their complete structure is defined by their respective metadata .
Ultimately . .Net modules use Manifest Metadata tables of parent assembly which contain them .

What is the use of Internal keyword?
Internal keyword is one of the access specifier available in .Net framework , that makes a type visible in a given assembly , for e.g : a single dll can contain multiple modules , essentially a multi file assembly , but it forms a single binary component , so any type with internal keyword will be visible throughout the assembly and can be used in any of the modules .

What actually happes when you add a something to arraylistcollection ?
Following things will happen :
Arraylist is a dynamic array class in c# in System.Collections namespace derived from interfaces – ICollection , IList , ICloneable , IConvertible . It terms of in memory structure following is the implementation .

  1. Check up the total space if there’s any free space on the declared list .
  2. If yes add the new item and increase count by 1 .
  3. If No Copy the whole thing to a temporary Array of Last Max. Size .
  4. Create new Array with size ( Last Array Size + Increase Value )
  5. Copy back values from temp and reference this new array as original array .
  6. Must doing Method updates too , need to check it up .

What is Boxing and unboxing? Does it occure automaatically or u need to write code to box and unbox?
Boxing – Process of converting a System.ValueType to Reference Type , Mostly base class System.Object type and allocating it memory on Heap .Reverse is unboxing , but can only be done with prior boxed variables.
Boxing is always implicit but Unboxing needs to be explicitly done via casting , thus ensuring the value type contained inside .

How Boxing and unboxing occures in memory?
Boxing converts value type to reference type , thus allocating memory on Heap . Unboxing converts already boxed reference types to value types through explicit casting , thus allocating memory on stack .

Why only boxed types can be unboxed?
Unboxing is the process of converting a Reference type variable to Value type and thus allocating memory on the stack . It happens only to those Reference type variables that have been earlier created by Boxing of a Value Type , therefore internally they contain a value type , which can be obtained through explicit casting . For any other Reference type , they don’t internally contain a Value type to Unboxed via explicit casting . This is why only boxed types can be unboxed .

Read more On "Dot Net Framework FAQ - Part Ten" >>>

Thursday, October 29, 2009

Dot Net Framework FAQ - Part Nine

What is the difference between an EXE and a DLL?
You can create an objects of Dll but not of the EXE.
Dll is an In-Process Component whereas EXE is an OUt-Process Component.
Exe is for single use whereas you can use Dll for multiple use.
Exe can be started as standalone where dll cannot be.

What is strong-typing versus weak-typing? Which is preferred? Why?
Strong typing implies that the types of variables involved in operations are associated to the variable, checked at compile-time, and require explicit conversion; weak typing implies that they are associated to the value, checked at run-time, and are implicitly converted as required. (Which is preferred is a disputable point, but I personally prefer strong typing because I like my errors to be found as soon as possible.)

What is a PID? How is it useful when troubleshooting a system?
PID is the process Id of the application in Windows. Whenever a process starts running in the Windows environment, it is associated with an individual process Id or PID.
The PID (Process ID) a unique number for each item on the Process Tab, Image Name list. How do you get the PID to appear? In Task Manger, select the View menu, then select columns and check PID (Process Identifier).
In Linux, PID is used to debug a process explicitly. However we cannot do this in a windows environment.
Microsoft has launched a SDK called as Microsoft Operations Management (MOM). This uses the PID to find out which dll’s have been loaded by a process in the memory. This is essentially helpful in situations where the Process which has a memory leak is to be traced to a erring dll. Personally I have never used a PID, our Windows debugger does the things required to find out.


What is the GAC? What problem does it solve?
Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies that are to be shared by several applications on the computer. This area is typically the folder under windows or winnt in the machine.
All the assemblies that need to be shared across applications need to be done through the Global assembly Cache only. However it is not necessary to install assemblies into the global assembly cache to make them accessible to COM interop or unmanaged code.
There are several ways to deploy an assembly into the global assembly cache:
  • Use an installer designed to work with the global assembly cache. This is the preferred option for installing assemblies into the global assembly cache.
  • Use a developer tool called the Global Assembly Cache tool (Gacutil.exe), provided by the .NET Framework SDK.
  • Use Windows Explorer to drag assemblies into the cache.
GAC solves the problem of DLL Hell and DLL versioning. Unlike earlier situations, GAC can hold two assemblies of the same name but different version. This ensures that the applications which access a particular assembly continue to access the same assembly even if another version of that assembly is installed on that machine.

Describe what an Interface is and how it’s different from a Class.
An interface is a structure of code which is similar to a class. An interface is a prototype for a class and is useful from a logical design perspective. Interfaces provide a means to define the protocols for a class without worrying about the implementation details. The syntax for creating interfaces follows:
interface Identifier {
InterfaceBody
}
Identifier is the name of the interface and InterfaceBody refers to the abstract methods and static final variables that make up the interface. Because it is assumed that all the methods in an interface are abstract, it isn't necessary to use the abstract keyword
An interface is a description of some of the members available from a class. In practice, the syntax typically looks similar to a class definition, except that there's no code defined for the methods — just their name, the arguments passed and the type of the value returned.
So what good is it? None by itself. But you create an interface so that classes will implement it.
But what does it mean to implement an interface. The interface acts as a contract or promise. If a class implements an interface, then it must have the properties and methods of the interface defined in the class. This is enforced by the compiler.
Broadly the differentiators between classes and interfaces is as follows
  • Interface should not have any implementation.
  • Interface can not create any instance.
  • Interface should provide high level abstraction from the implementation.
  • Interface can have multiple inheritances.
  • Default access level of the interface is public.

What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?
ASP.NET Web services and .NET Remoting provide a full suite of design options for cross-process and cross-plaform communication in distributed applications. In general, ASP.NET Web services provide the highest levels of interoperability with full support for WSDL and SOAP over HTTP, while .NET Remoting is designed for common language runtime type-system fidelity and supports additional data format and communication channels. Hence if we looking cross-platform communication than web services is the choice coz for .NET remoting .Net framework is requried which may or may not present for the other platform.

Serialization and Metadata
ASP.NET Web services rely on the System.Xml.Serialization.XmlSerializer class to marshal data to and from SOAP messages at runtime. For metadata, they generate WSDL and XSD definitions that describe what their messages contain. The reliance on pure WSDL and XSD makes ASP.NET Web services metadata portable; it expresses data structures in a way that other Web service toolkits on different platforms and with different programming models can understand. In some cases, this imposes constraints on the types you can expose from a Web service—XmlSerializer will only marshal things that can be expressed in XSD. Specifically, XmlSerializer will not marshal object graphs and it has limited support for container types.

.NET Remoting relies on the pluggable implementations of the IFormatter interface used by the System.Runtime.Serialization engine to marshal data to and from messages. There are two standard formatters, System.Runtime.Serialization.Formatters.Binary.BinaryFormatter and System.Runtime.Serialization.Formatters.Soap.SoapFormatter. The BinaryFormatter and SoapFormatter, as the names suggest, marshal types in binary and SOAP format respectively. For metadata, .NET Remoting relies on the common language runtime assemblies, which contain all the relevant information about the data types they implement, and expose it via reflection. The reliance on the assemblies for metadata makes it easy to preserve the full runtime type-system fidelity. As a result, when the .NET Remoting plumbing marshals data, it includes all of a class's public and private members; handles object graphs correctly; and supports all container types (e.g., System.Collections.Hashtable). However, the reliance on runtime metadata also limits the reach of a .NET Remoting system—a client has to understand .NET constructs in order to communicate with a .NET Remoting endpoint. In addition to pluggable formatters, the .NET Remoting layer supports pluggable channels, which abstract away the details of how messages are sent. There are two standard channels, one for raw TCP and one for HTTP. Messages can be sent over either channel independent of format.

Distributed Application Design: ASP.NET Web Services vs. .NET Remoting
ASP.NET Web services favor the XML Schema type system, and provide a simple programming model with broad cross-platform reach. .NET Remoting favors the runtime type system, and provides a more complex programming model with much more limited reach. This essential difference is the primary factor in determining which technology to use. However, there are a wide range of other design factors, including transport protocols, host processes, security, performance, state management, and support for transactions to consider as well.

Security
Since ASP.NET Web services rely on HTTP, they integrate with the standard Internet security infrastructure. ASP.NET leverages the security features available with IIS to provide strong support for standard HTTP authentication schemes including Basic, Digest, digital certificates, and even Microsoft® .NET Passport. (You can also use Windows Integrated authentication, but only for clients in a trusted domain.) One advantage of using the available HTTP authentication schemes is that no code change is required in a Web service; IIS performs authentication before the ASP.NET Web services are called. ASP.NET also provides support for .NET Passport-based authentication and other custom authentication schemes. ASP.NET supports access control based on target URLs, and by integrating with the .NET code access security (CAS) infrastructure. SSL can be used to ensure private communication over the wire.

Although these standard transport-level techniques to secure Web services are quite effective, they only go so far. In complex scenarios involving multiple Web services in different trust domains, you have to build custom ad hoc solutions. Microsoft and others are working on a set of security specifications that build on the extensibility of SOAP messages to offer message-level security capabilities. One of these is the XML Web Services Security Language (WS-Security), which defines a framework for message-level credential transfer, message integrity, and message confidentiality.

As noted in the previous section, the .NET Remoting plumbing does not secure cross-process invocations in the general case. A .NET Remoting endpoint hosted in IIS with ASP.NET can leverage all the same security features available to ASP.NET Web services, including support for secure communication over the wire using SSL. If you are using the TCP channel or the HTTP channel hosted in processes other than aspnet_wp.exe, you have to implement authentication, authorization and privacy mechanisms yourself.

One additional security concern is the ability to execute code from a semi-trusted environment without having to change the default security policy. ASP.NET Web Services client proxies work in these environments, but .NET Remoting proxies do not. In order to use a .NET Remoting proxy from a semi-trusted environment, you need a special serialization permission that is not given to code loaded from your intranet or the Internet by default. If you want to use a .NET Remoting client from within a semi-trusted environment, you have to alter the default security policy for code loaded from those zones. In situations where you are connecting to systems from clients running in a sandbox—like a downloaded Windows Forms application, for instance—ASP.NET Web Services are a simpler choice because security policy changes are not required.

Conceptually, what is the difference between early-binding and late-binding?
Early binding – Binding at Compile Time
Late Binding – Binding at Run Time

Early binding implies that the class of the called object is known at compile-time; late-binding implies that the class is not known until run-time, such as a call through an interface or via Reflection.

Early binding is the preferred method. It is the best performer because your application binds directly to the address of the function being called and there is no extra overhead in doing a run-time lookup. In terms of overall execution speed, it is at least twice as fast as late binding.

Early binding also provides type safety. When you have a reference set to the component's type library, Visual Basic provides IntelliSense support to help you code each function correctly. Visual Basic also warns you if the data type of a parameter or return value is incorrect, saving a lot of time when writing and debugging code.

Late binding is still useful in situations where the exact interface of an object is not known at design-time. If your application seeks to talk with multiple unknown servers or needs to invoke functions by name (using the Visual Basic 6.0 CallByName function for example) then you need to use late binding. Late binding is also useful to work around compatibility problems between multiple versions of a component that has improperly modified or adapted its interface between versions.

What is an Asssembly Qualified Name? Is it a filename? How is it different?
An assembly qualified name isn't the filename of the assembly; it's the internal name of the assembly combined with the assembly version, culture, and public key, thus making it unique.
e.g. (""System.Xml.XmlDocument, System.Xml, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"")

How is a strongly-named assembly different from one that isn’t strongly-named?
Strong names are used to enable the stricter naming requirements associated with shared assemblies. These strong names are created by a .NET utility – sn.exe
Strong names have three goals:
  • Name uniqueness. Shared assemblies must have names that are globally unique.
  • Prevent name spoofing. Developers don't want someone else releasing a subsequent version of one of your assemblies and falsely claim it came from you, either by accident or intentionally.
  • Provide identity on reference. When resolving a reference to an assembly, strong names are used to guarantee the assembly that is loaded came from the expected publisher.
Strong names are implemented using standard public key cryptography. In general, the process works as follows: The author of an assembly generates a key pair (or uses an existing one), signs the file containing the manifest with the private key, and makes the public key available to callers. When references are made to the assembly, the caller records the public key corresponding to the private key used to generate the strong name.

Weak named assemblies are not suitable to be added in GAC and shared. It is essential for an assembly to be strong named.

Strong naming prevents tampering and enables assemblies to be placed in the GAC alongside other assemblies of the same name.

How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?
The hugely simplistic version is that every time it garbage-collects, it starts by assuming everything to be garbage, then goes through and builds a list of everything reachable. Those become not-garbage, everything else doesn't, and gets thrown away. What makes it generational is that every time an object goes through this process and survives, it is noted as being a member of an older generation (up to 2, right now). When the garbage-collector is trying to free memory, it starts with the lowest generation (0) and only works up to higher ones if it can't free up enough space, on the grounds that shorter-lived objects are more likely to have been freed than longer-lived ones.

Non-deterministic finalization implies that the destructor (if any) of an object will not necessarily be run (nor its memory cleaned up, but that's a relatively minor issue) immediately upon its going out of scope. Instead, it will wait until first the garbage collector gets around to finding it, and then the finalisation queue empties down to it; and if the process ends before this happens, it may not be finalised at all. (Although the operating system will usually clean up any process-external resources left open - note the usually there, especially as the exceptions tend to hurt a lot.)

What is the difference between Finalize() and Dispose()?
Dispose() is called by the user of an object to indicate that he is finished with it, enabling that object to release any unmanaged resources it holds. Finalize() is called by the run-time to allow an object which has not had Dispose() called on it to do the same. However, Dispose() operates determinalistically, whereas there is no guarantee that Finalize() will be called immediately when an object goes out of scope - or indeed at all, if the program ends before that object is GCed - and as such Dispose() is generally preferred.

How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?
The using() pattern is useful because it ensures that Dispose() will always be called when a disposable object (defined as one that implements IDisposable, and thus the Dispose() method) goes out of scope, even if it does so by an exception being thrown, and thus that resources are always released.
Read more On "Dot Net Framework FAQ - Part Nine" >>>

Monday, October 12, 2009

Dot Net Framework FAQ - Part Eight

How you deploy .NET assemblies?
One way is simply use xcopy. others are use and the setup projects in .net. and one more way is use of nontuch deployment.

What is Globalizationa and Localization ?
Globalization is the process of creating an application that meets the needs of users from multiple cultures. It includes using the correct
currency, date and time format, calendar, writing direction, sorting rules, and other issues. Accommodating these cultural differences in an application is called localization.Using classes of System.Globalization namespace, you can set application's current culture.
This can be achieved by using any of the following 3 approaches.
  1. Detect and redirect
  2. Run-time adjustment
  3. Using Satellite assemblies.

Whate are Resource Files ? How are they used in .NET?
Resource files are the files containing data that is logically deployed with an application.These files can contain data in a number of formats including strings, images and persisted objects. It has the main advantage of If we store data in these files then we don't need to compile these if the data get changed. In .NET we basically require them storing culture specific informations by localizing application's resources. You can deploy your resources using satellite assemblies.

Difference between Dispose and Finallize method?

Finalize method is used to free the memory used by some unmanaged resources like window handles (HWND). It's similar to the destructor syntax in C#. The GC calls this method when it founds no more references to the object. But, In some cases we may need release the memory used by the resources explicitely.To release the memory explicitly we need to implement the Dispose method of IDisposable interface.

What is encapsulation ?
Encapsulation is the ability to hide the internal workings of an object's behavior and its data. For instance, let's say you have a object named Bike and this object has a method named start(). When you create an instance of a Bike object and call its start() method you are not worried about what happens to accomplish this, you just want to make sure the state of the bike is changed to 'running' afterwards. This kind of behavior hiding is encapsulation and it makes programming much easier.

How can you prevent your class to be inherated further?
By setting Sealed - Key word
public sealed class Planet
{
//code goes here
}
class Moon:Planet
{
//Not allowed as base class is sealed
}

What is GUID and why we need to use it and in what condition? How this is created?
A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated. Visual Studio .NET IDE has a utility under the tools menu to generate GUIDs.

Why do you need to serialize.?
We need to serialize the object,if you want to pass object from one computer/application domain to another.Process of converting complex objects into stream of bytes that can be persisted or transported.Namespace for serialization is System.Runtime.Serialization.The ISerializable interface allows you to make any class Serializable..NET framework features 2 serializing method.
1.Binary Serialization 2.XML Serialization

What is inline schema, how does it works?
Schemas can be included inside of XML file is called Inline Schemas.This is useful when it is inconvenient to physically seprate the schema and the XML document.A schema is an XML document that defines the structure, constraints, data types, and relationships of the elements that constitute the data contained inside the XML document or in another XML document.Schema can be an external file which uses the XSD or XDR extension called external schema. Inline schema can take place even when validation is turned off.

Describe the advantages of writing a managed code application instead of unmanaged one. What's involved in certain piece of code being managed?
"Advantage includes automatic garbage collection,memory management,security,type checking,versioning
Managed code is compiled for the .NET run-time environment. It runs in the Common Language Runtime (CLR), which is the heart of the .NET Framework. The CLR provides services such as security,
memory management, and cross-language integration. Managed applications written to take advantage of the features of the CLR perform more efficiently and safely, and take better advantage of developers existing expertise in languages that support the .NET Framework.
Unmanaged code includes all code written before the .NET Framework was introduced—this includes code written to use COM, native Win32, and Visual Basic 6. Because it does not run inside the .NET environment, unmanaged code cannot make use of any .NET managed facilities."

What are multicast delegates ? give me an example ?
Delegate that can have more than one element in its invocation List.
using System;
namespace SampleMultiCastDelegate
{
class MultiCast
{
public delegate string strMultiCast(string s);
}
}

MainClass defines the static methods having same signature as delegate.
using System;
namespace SampleMultiCastDelegate
{
public class MainClass
{
public MainClass()
{
}
public static string Jump(string s)
{
Console.WriteLine("Jump");
return String.Empty;
}
public static string Run(string s)
{
Console.WriteLine("Run");
return String.Empty;
}
public static string Walk(string s)
{
Console.WriteLine("Walk");
return String.Empty;
}
}
}

The Main class:
using System;
using System.Threading;
namespace SampleMultiCastDelegate
{
public class MainMultiCastDelegate
{
public static void Main()
{
MultiCast.strMultiCast Run,Walk,Jump;
MultiCast.strMultiCast myDelegate;
///here mydelegate used the Combine method of System.MulticastDelegate
///and the delegates combine
myDelegate=(MultiCast.strMultiCast)System.Delegate.Combine(Run,Walk);

}
}
}

Can a nested object be used in Serialization ?
Yes. If a class that is to be serialized contains references to objects of other classes, and if those classes have been marked as serializable, then their objects are serialized too.

Difference between int and int32 ?
Both are same. System.Int32 is a .NET class. Int is an alias name for System.Int32.

Describe the difference between a Thread and a Process?
A Process is an instance of an running application. And a thread is the Execution stream of the Process. A process can have multiple Thread.
When a process starts a specific memory area is allocated to it. When there is multiple thread in a process, each thread gets a memory for storing the variables in it and plus they can access to the global variables which is common for all the thread. Eg.A Microsoft Word is a Application. When you open a word file,an instance of the Word starts and a process is allocated to this instance which has one thread.

Read more On "Dot Net Framework FAQ - Part Eight" >>>

Sunday, October 4, 2009

Dot Net Framework FAQ - Part Seven

What is Value type and refernce type in .Net?.
Value Type : A variable of a value type always contains a value of that type. The assignment to a variable of a value type creates a copy of the assigned value, while the assignment to a variable of a reference type creates a copy of the reference but not of the referenced object.
The value types consist of two main categories:
  • Stuct Type
  • Enumeration Type
Reference Type :Variables of reference types, referred to as objects, store references to the actual data. This section introduces the following keywords used to declare reference types:
  • Class
  • Interface
  • Delegate
This section also introduces the following built-in reference types:
  • object
  • string

What is the difference between structures and enumeration?.
Unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly contains the data of the struct, whereas a variable of a class type contains a reference to the data. They are derived from System.ValueType class.
Enum->An enum type is a distinct type that declares a set of named constants.They are strongly typed constants. They are unique types that allow to declare symbolic names to integral values. Enums are value types, which means they contain their own value, can't inherit or be inherited from and assignment copies the value of one enum to another.
public enum Grade
{
A,
B,
C
}

What is namespaces?.
Namespace is a logical naming scheme for group related types.Some class types that logically belong together they can be put into a common namespace. They prevent namespace collisions and they provide scoping. They are imported as "using" in C# or "Imports" in Visual Basic. It seems as if these directives specify a particular assembly, but they don't. A namespace can span multiple assemblies, and an assembly can define multiple namespaces. When the compiler needs the definition for a class type, it tracks through each of the different imported namespaces to the type name and searches each referenced assembly until it is found.
Namespaces can be nested. This is very similar to packages in Java as far as scoping is concerned.

How do you create shared assemblies?.
Just look through the definition of Assemblies..

  • An Assembly is a logical unit of code
  • Assembly physically exist as DLLs or EXEs
  • One assembly can contain one or more files
  • The constituent files can include any file types like image files, text files etc. along with DLLs or EXEs
  • When you compile your source code by default the exe/dll generated is actually an assembly
  • Unless your code is bundled as assembly it can not be used in any other application
  • When you talk about version of a component you are actually talking about version of the assembly to which the component belongs.
  • Every assembly file contains information about itself. This information is called as Assembly Manifest.
Following 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 AL utility

What is global assembly cache?
Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.
There are several ways to deploy an assembly into the global assembly cache:

  • Use an installer designed to work with the global assembly cache. This is the preferred option for installing assemblies into the global assembly cache.
  • Use a developer tool called the Global Assembly Cache tool (Gacutil.exe), provided by the .NET Framework SDK.
  • Use Windows Explorer to drag assemblies into the cache.

What is MSIL?.
When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Before code can be run, MSIL must be converted to CPU-specific code, usually by a just-in-time (JIT) compiler. Because the common language runtime supplies one or more JIT compilers for each computer architecture it supports, the same set of MSIL can be JIT-compiled and run on any supported architecture.
When a compiler produces MSIL, it also produces metadata. Metadata describes the types in your code, including the definition of each type, the signatures of each type's members, the members that your code references, and other data that the runtime uses at execution time. The MSIL and metadata are contained in a portable executable (PE) file that is based on and extends the published Microsoft PE and common object file format (COFF) used historically for executable content. This file format, which accommodates MSIL or native code as well as metadata, enables the operating system to recognize common language runtime images. The presence of metadata in the file along with the MSIL enables your code to describe itself, which means that there is no need for type libraries or Interface Definition Language (IDL). The runtime locates and extracts the metadata from the file as needed during execution.

What is Jit compilers?.How many are available in CLR?
Just-In-Time compiler- it converts the language that you write in .Net into machine language that a computer can understand. there are tqo types of JITs one is memory optimized & other is performace optimized.

What is tracing?Where it used.Explain few methods available?
Tracing refers to collecting information about the application while it is running. You use tracing information to troubleshoot an application.
Tracing allows us to observe and correct programming errors. Tracing enables you to record information in various log files about the errors that might occur at run time. You can analyze these log files to find the cause of the errors.
In .NET we have objects called Trace Listeners. A listener is an object that receives the trace output and outputs it somewhere; that somewhere could be a window in your development environment, a file on your hard drive, a Windows Event log, a SQL Server or Oracle database, or any other customized data store.
The System.Diagnostics namespace provides the interfaces, classes, enumerations and structures that are used for tracing The System.Diagnostics namespace provides two classes named Trace and Debug that are used for writing errors and application execution information in logs.
All Trace Listeners have the following functions. Functionality of these functions is same except that the target media for the tracing output is determined by the Trace Listener.
Method Name
Result Fail Outputs the specified text with the Call Stack.
Write Outputs the specified text.
WriteLine Outputs the specified text and a carriage return.
Flush Flushes the output buffer to the target media.
Close Closes the output stream in order to not receive the tracing/debugging output.

How to set the debug mode?
Debug Mode for ASP.NET applications - To set ASP.NET appplication in debugging mode, edit the application's web.config and assign the "debug" attribute in
<> section to "true" as show below:
<>
<>
< defaultlanguage="vb" debug="true">
....
...
..
< / configuration >
This case-sensitive attribute 'debug tells ASP.NET to generate symbols for dynamically generated files and enables the
debugger to attach to the ASP.NET application. ASP.NET will detect this change automatically, without the need to restart the server. Debug Mode for ASP.NET Webservices - Debugging an XML Web service created with ASP.NET is similar to the debugging an ASP.NET Web application.

What is the property available to check if the page posted or not?
The Page_Load event handler in the page checks for IsPostBack property value, to ascertain whether the page is posted. The Page.IsPostBack gets a value indicating whether the page is being loaded in response to the client postback, or it is for the first time. The value of Page.IsPostBack is True, if the page is being loaded in response to the client postback; while its value is False, when the page is loaded for the first time. The Page.IsPostBack property facilitates execution of certain routine in Page_Load, only once (for e.g. in Page load, we need to set default value in controls, when page is loaded for the first time. On post back, we check for true value for IsPostback value and then invoke server-side code to
update data).

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.

Is it possible to use multipe inheritance in .net?
Multiple Inheritance is an ability to inherit from more than one base class i.e. ability of a class to have more than one superclass, by inheriting from different sources and thus combine separately-defined behaviors in a single class. There are two types of multiple inheritance: multiple type/interface inheritance and multiple implementation inheritance. C# & VB.NET supports only multiple type/interface inheritance, i.e.
you can derive an class/interface from multiple interfaces. There is no support for multiple implementation inheritance in .NET. That means a class can only derived from one class.

What are the derived classes from xmlReader and xmlWriter?
Both XmlReader and XmlWriter are abstract base classes, 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.

What is managed and unmanaged code?
The .NET framework provides several core run-time services to the programs that run within it - for example exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime. i.e., code executing under the control of the CLR is called managed code. For example, any code written in C# or Visual Basic .NET is managed code.
Code that runs outside the CLR is referred to as "unmanaged code." COM components, ActiveX components, and Win32 API functions are examples of unmanaged code.
Read more On "Dot Net Framework FAQ - Part Seven" >>>

Tuesday, September 29, 2009

Dot Net Framework FAQ - Part Six

What are the Main Features of .NET platform?
Features of .NET Platform are :-
Common Language Runtime
Explains the features and benefits of the common language runtime, a run-time environment that manages the execution of code and provides services that simplify the development process.
Assemblies
Defines the concept of assemblies, which are collections of types and resources that form logical units of functionality. Assemblies are the fundamental units of deployment, version control, reuse, activation scoping, and security permissions.
Application Domains
Explains how to use application domains to provide isolation between applications.
Runtime Hosts
Describes the runtime hosts supported by the .NET Framework, including ASP.NET, Internet Explorer, and shell executables.
Common Type System
Identifies the types supported by the common language runtime.
Metadata and Self-Describing Components
Explains how the .NET Framework simplifies component interoperation by allowing compilers to emit additional declarative information, or metadata, into all modules and assemblies.
Cross-Language Interoperability
Explains how managed objects created in different programming languages can interact with one another.
.NET Framework Security
Describes mechanisms for protecting resources and code from unauthorized code and unauthorized users.
.NET Framework Class Library
Introduces the library of types provided by the .NET Framework, which expedites and optimizes the development process and gives you access to system functionality.

What is the use of JIT ?
JIT (Just - In - Time) is a compiler which converts MSIL code to Native Code (ie.. CPU-specific code that runs on the same computer architecture).
Because the common language runtime supplies a JIT compiler for each supported CPU architecture, developers can write a set of MSIL that can be JIT-compiled and run on computers with different architectures. However, your managed code will run only on a specific operating system if it calls platform-specific native APIs, or a platform-specific class library.
JIT compilation takes into account the fact that some code might never get called during execution. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as needed during execution and stores the resulting native code so that it is accessible for subsequent calls. The loader creates and attaches a stub to each of a type's methods when the type is loaded. On the initial call to the method, the stub passes control to the JIT compiler, which converts the MSIL for that method into native code and modifies the stub to direct execution to the location of the native code. Subsequent calls of the JIT-compiled method proceed directly to the native code that was previously generated, reducing the time it takes to JIT-compile and run the code.

What meant of assembly & global assembly cache (gac) & Meta data?
Assembly :-- An assembly is the primary building block of a .NET based application. It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files). All managed types and resources are marked either as accessible only within their implementation unit, or as accessible by code outside that unit. It overcomes the problem of 'dll Hell'.The .NET Framework uses assemblies as the fundamental unit for several purposes:
  • Security
  • Type Identity
  • Reference Scope
  • Versioning
  • Deployment
Global Assembly Cache :-- Assemblies can be shared among multiple applications on the machine by registering them in global Assembly cache(GAC). GAC is a machine wide a local cache of assemblies maintained by the .NET Framework. We can register the assembly to global assembly cache by using gacutil command.
We can Navigate to the GAC directory, C:\winnt\Assembly in explore. In the tools menu select the cache properties; in the windows displayed you can set the memory limit in MB used by the GAC
MetaData :--Assemblies have Manifests. This Manifest contains Metadata information of the Module/Assembly as well as it contains detailed Metadata of other assemblies/modules references (exported). It's the Assembly Manifest which differentiates between an Assembly and a Module.

What are the mobile devices supported by .net platform?
The Microsoft .NET Compact Framework is designed to run on mobile devices such as mobile phones, Personal Digital Assistants (PDAs), and embedded devices. The easiest way to develop and test a Smart Device Application is to use an emulator.
These devices are divided into two main divisions:
1) Those that are directly supported by .NET (Pocket PCs, i-Mode phones, and WAP devices)
2) Those that are not (Palm OS and J2ME-powered devices).

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, file, database entry, and/or user. For instance, a Web site may generate a GUID and assign it to a user's browser to record and track the session. A GUID is also used in a Windows registry to identify COM DLLs. Knowing where to look in the registry and having the correct GUID yields a lot information about a COM object (i.e., information in the type library, its physical location, etc.). Windows also identifies user accounts by a username (computer/domain and username) and assigns it a GUID. Some database administrators even will use GUIDs as primary key values in databases.
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.

Whats MSIL, and why should my developers need an appreciation of it if at all?
When compiling the source code to managed code, the compiler translates the source into Microsoft intermediate language (MSIL). This is a CPU-independent set of instructions that can efficiently be converted to native code. Microsoft intermediate language (MSIL) is a translation used as the output of a number of compilers. It is the input to a just-in-time (JIT) compiler. The Common Language Runtime includes a JIT compiler for the conversion of MSIL to native code.
Before Microsoft Intermediate Language (MSIL) can be executed it, must be converted by the .NET Framework just-in-time (JIT) compiler to native code. This is CPU-specific code that runs on the same computer architecture as the JIT compiler. Rather than using time and memory to convert all of the MSIL in a portable executable (PE) file to native code. It converts the MSIL as needed whilst executing, then caches the resulting native code so its accessible for any subsequent calls.

How many .NET languages can a single .NET DLL contain?
One

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

Server

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.

How many classes can a single .NET DLL contain?

Unlimited.

What is the difference between string and String ?

No difference

What is manifest?
It is the metadata that describes the assemblies.

What is metadata?
Metadata is machine-readable information about a resource, or ""data about data."" Such information might include details on content, format, size, or other characteristics of a data
source. In .NET, metadata includes type definitions, version information, external assembly references, and other standardized information.

What are the types of assemblies?
There are four types of assemblies in .NET:
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.
Private assemblies
These are static assemblies used by a specific application.

Public or shared assemblies
These are static assemblies that must have a unique shared name and can be used by any application.
An application uses a private assembly by referring to the assembly using a static path or through an XML-based application configuration file. While the CLR doesn't enforce versioning policies-checking whether the correct version is used-for private assemblies, it ensures that an
application uses the correct shared assemblies with which the application was built. Thus, an application uses a specific shared assembly by referring to the specific shared assembly, and the CLR ensures that the correct version is loaded at runtime.
In .NET, an assembly is the smallest unit to which you can associate a version number;

What are delegates?where are they used ?
A delegate defines a reference type that can be used to encapsulate a method with a specific signature. A delegate instance encapsulates a static or an instance method. Delegates are roughly similar to function pointers in C++; however, delegates are type-safe and secure.

When do you use virutal keyword?.
When we need to override a method of the base class in the sub class, then we give the virtual keyword in the base class method. This makes the method in the base class to be overridable. Methods, properties, and indexers can be virtual, which means that their implementation can be overridden in derived classes.

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.

What Is Boxing And Unboxing?
Boxing :- Boxing is an implicit conversion of a value type to the type object type
Example:-
Consider the following declaration of a value-type variable:
int i = 123;
object o = (object) i;
Boxing Conversion
UnBoxing :- Unboxing is an explicit conversion from the type object to a value type
Eg:
int i = 123; // A value type
object box = i; // Boxing
int j = (int)box; // Unboxing
Read more On "Dot Net Framework FAQ - Part Six" >>>

Saturday, September 26, 2009

Dot Net Framework FAQ - Part Five

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

What's the top .NET class that everything is derived from?
System.Object.

What's the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. 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 .NET class that allows the retrieval of a data element using a unique key?

HashTable.

Will the finally block get executed if an exception has not occurred?

Yes.

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.

Why can't you specify the accessibility modifier for methods inside the interface?
They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice,
you are not allowed to specify any accessibility, it's public by default.

What's the difference between an interface and abstract class?

In an interface class, all methods must be abstract. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed, which is ok in an abstract class.

How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves
having another method with the same name within the class.

Can you declare an override method to be static if the original method is non-static?
No. The signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

Can you override private virtual methods?
No. Private methods are not accessible outside the class.

Can you write a class without specifying namespace? Which namespace does it belong to by default?
Yes, you can, then the class belongs to global namespace which has no name. For commercial products, naturally, you wouldn't want global namespace.

What is a formatter?
A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.

Different b/w .NET & J2EE ?
Differences between J2EE and the .NET Platform

Vendor Neutrality
The .NET platform is not vendor neutral, it is tied to the Microsoft operating systems. But neither are any of the J2EE implementations
Many companies buy into J2EE believing that it will give them vendor neutrality. And, in fact, this is a stated goal of Sun's vision:
A wide variety of J2EE product configurations and implementations, all of which meet the requirements of this specification, are possible. A portable J2EE application will function correctly when successfully deployed in any of these products. (ref : Java 2 Platform Enterprise Edition Specification, v1.3, page 2-7 available at http://java.sun.com/j2ee/)

Overall Maturity
Given that the .NET platform has a three year lead over J2EE, it should be no surprise to learn that the .NET platform is far more mature than the J2EE platform. Whereas we have high volume highly reliable web sites using .NET technologies (NASDAQ and Dell being among many examples)

Interoperability and Web Services
The .NET platform eCollaboration model is, as I have discussed at length, based on the UDDI and SOAP standards. These standards are widely supported by more than 100 companies. Microsoft, along with IBM and Ariba, are the leaders in this area. Sun is a member of the UDDI consortium and recognizes the importance of the UDDI standards. In a recent press release, Sun's George Paolini, Vice President for the Java Community Development, says:
"Sun has always worked to help establish and support open, standards-based technologies that facilitate the growth of network-based applications, and we see UDDI as an important project to establish a registry framework for business-to-business e-commerce.

But while Sun publicly says it believes in the UDDI standards, in reality, Sun has done nothing whatsoever to incorporate any of the UDDI standards into J2EE.

Scalability
Typical Comparision w.r.t Systems and their costs

Framework Support
The .NET platform includes such an eCommerce framework called Commerce Server. At this point, there is no equivalent vendor-neutral framework in the J2EE space. With J2EE, you should assume that you will be building your new eCommerce solution from scratch.

Moreover, no matter what [J2EE] vendor you choose, if you expect a component framework that will allow you to quickly field complete e-business applications, you are in for a frustrating experience.

Language
In the language arena, the choice is about as simple as it gets. J2EE supports Java, and only Java. It will not support any other language in the foreseeable future. The .NET platform supports every language except Java (although it does support a language that is syntactically and functionally equivalent to Java, C#). In fact, given the importance of the .NET platform as a language independent vehicle, it is likely that any language that comes out in the near future will include support for the .NET platform.

Some companies are under the impression that J2EE supports other languages. Although both IBM's WebSphere and BEA's WebLogic support other languages, neither does it through their J2EE technology. There are only two official ways in the J2EE platform to access other languages, one through the Java Native Interface and the other through CORBA interoperability. Sun recommends the later approach. As Sun's Distinguished Scientist and Java Architect Rick Cattell said in a recent interview.

Portability
The reason that operating system portability is a possibility with J2EE is not so much because of any inherent portability of J2EE, as it is that most of the J2EE vendors support multiple operating systems. Therefore as long as one sticks with a given J2EE vendor and a given database vendor, moving from one operating system to another should be possible. This is probably the single most important benefit in favor of J2EE over the .NET platform, which is limited to the Windows operating system. It is worth noting, however, that Microsoft has submitted the specifications for C# and a subset of the .NET Framework (called the common language infrastructure) to ECMA, the group that standardizes JavaScript.
J2EE offers an acceptable solution to ISVs when the product must be marketed to non-Windows customers, particularly when the J2EE platform itself can be bundled with the ISV's product as an integrated offering.
If the primary customer base for the ISV is Windows customers, then the .NET platform should be chosen. It will provide much better performance at a much lower cost.

Client device independence
The major difference being that with Java, it is the presentation tier programmer that determines the ultimate HTML that will be delivered to the client, and with .NET, it is a Visual Studio.NET control.

This Java approach has three problems. First, it requires a lot of code on the presentation tier, since every possible thin client system requires a different code path. Second, it is very difficult to test the code with every possible thin client system. Third, it is very difficult to add new thin clients to an existing application, since to do so involves searching through, and modifying a tremendous amount of presentation tier logic.

The .NET Framework approach is to write device independent code that interacts with visual controls. It is the control, not the programmer, that is responsible for determining what HTML to deliver, based on the capabilities of the client device.. In the .NET Framework model, one can forget that such a thing as HTML even exists!

Conclusion

Sun's J2EE vision is based on a family of specifications that can be implemented by many vendors. It is open in the sense that any company can license and implement the technology, but closed in the sense that it is controlled by a single vendor, and a self contained architectural island with very limited ability to interact outside of itself. One of J2EE's major disadvantages is that the choice of the platform dictates the use of a single programming language, and a programming language that is not well suited for most businesses. One of J2EE's major advantages is that most of the J2EE vendors do offer operating system portability.

Microsoft's .NET platform vision is a family of products rather than specifications, with specifications used primarily to define points of interoperability. The major disadvantage of this approach is that if is limited to the Windows platform, so applications written for the .NET platform can only be run on .NET platforms. Their are several important advantages to the .NET platform:

  • The cost of developing applications is much lower, since standard business languages can be used and device independent presentation tier logic can be written.
  • The cost of running applications is much lower, since commodity hardware platforms (at 1/5 the cost of their Unix counterparts) can be used.
  • The ability to scale up is much greater, with the proved ability to support at least ten times the number of clients any J2EE platform has shown itself able to support.
  • Interoperability is much stronger, with industry standard eCollaboration built into the platform.
Read more On "Dot Net Framework FAQ - Part Five" >>>

RECENT POSTS

Related Posts with Thumbnails