Friday, October 12, 2007

.net Interview Questions


(A) What is Manifest?

Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following things (See Figure Manifest View for more details):
· Version of assembly
· Security identity
· Scope of the assembly
· Resolve references to resources and classes.
· The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a stand-alone PE file that contains only assembly manifest information.

(B)Where is version information stored of an assembly ?

Version information is stored in assembly in manifest.

(I)Is versioning applicable to private assemblies?

Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in their individual folders.

(B) What is GAC ?

Twist :- What are situations when you register .NET assembly in GAC ?

GAC (Global Assembly Cache) is used where shared .NET assembly reside. GAC is used in the following situations :-
· If the application has to be shared among several application.
· If the assembly has some special security requirements like only administrator scan remove the assembly. If the assembly is private then a simple delete of assembly the assembly file will remove the assembly. Note :- Registering .NET assembly in GAC can lead to the old problem of DLL hell, where COM version was stored in central registry. So GAC should be used when absolutely necessary.

(I) What is the concept of strong names ?

Twist :- How do we generate strong names ?
Twist :- What is use the of SN.EXE ?
Twist :- How do we apply strong names to assembly?
Twist :- How do you sign an assembly?

Strong name is similar to GUID(It is supposed to be unique in space and time) in COM components. Strong Name is only needed when we need to deploy assembly in GAC. Strong Names helps GAC to differentiate between two versions. Strong names use public key cryptography (PKC) to ensure that no one can spoof it. PKC use public key and private key concept. Following are the step to generate a strong name and sign a assembly :-

Go to “Visual Studio Command Prompt”. See below figure “Visual studio Command Prompt”. Note the samples are compiled in 2005 but 2003 users do ot have to worry about it. Same type of command prompt will be seen in2003 also.

After you are in command prompt type sn.exe -k “c:\test.snk”.

After generation of the file you can view the SNK file in a simple notepad.

After the SNK file is generated its time to sign the project with this SNK file

Click on project -- properties and the browse the SNK file to the respective folder and compile the project.

Click on Use a key file to sign the assembly with strong name

(I)How to add and remove an assembly from GAC?There are two ways to install .NET assembly in GAC:-vUsing Microsoft Installer Package. You can get download of installer fromhttp://www.microsoft.com.vUsing Gacutil. Goto “Visual Studio Command Prompt” and type “gacutil –i(assembly_name)”, where (assembly_name) is the DLL name of the project.

(B) What is Delay signing ?During development process you will need strong name keys to be exposed to developer whichis not a good practice from security aspect point of view.In such situations you can assign the keylater on and during development you an use delay signingFollowing is process to delay sign an assembly:vFirst obtain your string name keys using SN.EXE.vAnnotate the source code for the assembly with two custom attributes fromSystem.Reflection: AssemblyKeyFileAttribute, which passes the name of the filecontaining the public key as a parameter to its constructor. AssemblyDelaySignAttribute,which indicates that delay signing, is being used by passing true as a parameter to itsconstructor. For example as shown below:[Visual Basic] [C#] [assembly:AssemblyKeyFileAttribute("myKey.snk")] [assembly:AssemblyDelaySignAttribute(true)]The compiler inserts the public key into the assembly manifest and reserves space in the PE file forthe full strong name signature. The real public key must be stored while the assembly is built sothat other assemblies that reference this assembly can obtain the key to store in their own assemblyreference.vBecause the assembly does not have a valid strong name signature, the verification ofthat signature must be turned off. You can do this by using the –Vr option with theStrong Name tool.The following example turns off verification for an assembly calledmyAssembly.dll.Sn –Vr myAssembly.dll80vJust before shipping, you submit the assembly to your organization's signing authorityfor the actual strong name signing using the –R option with the Strong Name tool.Thefollowing example signs an assembly called myAssembly.dll with a strong nameusingthe sgKey.snk key pair.Sn -R myAssembly.dll sgKey.snk


(B)What is garbage collection?Garbage collection is a CLR feature which automatically manages memory. Programmers forgetto release the objects while coding ..... Laziness (Remember in VB6 where one of the goodpractices is to set object to nothing). CLR automatically releases objects when they are no longer inuse and refernced. CLR runs on non-deterministic to see the unused objects and cleans them. Oneside effect of this non-deterministic feature is that we cannot assume an object is destroyed whenit goes out of the scope of a function.we should avoid using destructors because before GCdestroys the object it first executes destructor in that case it will have to wait for code to releasethe umanaged resource. resultin in additional delays in GC. So its recommended to implementIDisposable interface and write cleaup code in Dispose method and call GC.SuppressFinalizemethod so instructing GC not to call your constructor. For more details read Why is it preferredto not use finalize for clean up? in OOPS chapter..

(I) Can we force garbage collector to run ?System.GC.Collect() forces garbage collector to run. This is not recommended but can be used ifsituations arises.

(B)What is reflection?All .NET assemblies have metadata information stored about the types defined in modules. Thismetadata information can be accessed by mechanism called as “Reflection”.System. Reflectioncan be used to browse through the metadata information.Using reflection you can also dynamically invoke methods using System.Type.Invokemember.Below is sample source code if needed you can also get this code from CD provided, go to“Source code” folder in “Reflection Sample” folder.Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e AsSystem.EventArgs) Handles MyBase.Load Dim Pobjtype As Type Dim PobjObject As Object Dim PobjButtons As New Windows.Forms.Button() Pobjtype = PobjButtons.GetType()81 For Each PobjObject In Pobjtype.GetMembers LstDisplay.Items.Add(PobjObject.ToString()) Next End SubEnd ClassNote :- Sample source code are compiled using VB.NET 2005.Figure:- 1.9 Sample reflection displaySample source code uses reflection to browse through “Button” class of “Windows.Forms”. Ifyou compile and run the program following is output as shown in “Sample Reflection Display”.Using reflection you can also dynamically invoke a method using “System.Type.InvokeMember”.Note :- System.Type.InvokeMember is left as homework for readers. Believe me you willenjoy doing it yourself and the concept of reflection will be clearer.

(P)What are different types of JIT ?Note :- This question can only be asked when the interviewer does not know what he wants.It was asked to me in one of interview and for 15 minutes he was roaming around the82same question in order to get answer from me (requirement was for a simple databaseproject). Beware of such companies and interviewers you can land up no where.JIT compiler is a part of the runtime execution environment.In Microsoft .NET there are three types of JIT compilers:vPre-JIT :- Pre-JIT compiles complete source code into native code in a singlecompilationcycle. This is done at the time of deployment of the application.vEcono-JIT :- Econo-JIT compiles only those methods that are called at runtime.However, these compiled methods are removed when they are not required.vNormal-JIT :- Normal-JIT compiles only those methods that are called at runtime.These methods are compiled the first time they are called, and then they are stored incache. When the same methods are called again, the compiled code from cache isused for execution.

(B) What are Value types and Reference types ?Value types directly contain their data which are either allocated on the stack or allocated in-line ina structure.Reference types store a reference to the value's memory address, and are allocated on the heap.Reference types can be self-describing types, pointer types, or interface types.Variables that are value types each have their own copy of the data, and therefore operations onone variable do not affect other variables. Variables that are reference types can refer to the sameobject; therefore, operations on one variable can affect the same object referred to by anothervariable. All types derive from the System.Object base type.


(B) What is concept of Boxing and Unboxing ?Boxing permits any value type to be implicitly converted to type object or to any interface typeimplemented by value type. Boxing is a process in which object instances are created and copyvalues in to that instance.Unboxing is vice versa of boxing operation where the value is copied from the instance in toappropriate storage location.Below is sample code of boxing and unboxing where integer data type is converted in to objectand then vice versa.Dim x As Integer83Dim y As Objectx = 10‘ boxing processy = x‘ unboxing processx = y

(B) What is the difference between VB.NET and C# ?Well this is the most debatable issue in .NET community and people treat there languages likereligion. Its a subjective matter which language is best. Some like VB.NET’s natural style and somelike professional and terse C# syntaxes. Both use the same framework and speed is also very muchequivalents. But still let’s list down some major differences between them :-Advantages VB.NET :-vHas support for optional parameters which makes COM interoperability much easy.vWith Option Strict off late binding is supported.Legacy VB functionalities can beused by using Microsoft.VisualBasic namespace.vHas the WITH construct which is not in C#.vThe VB.NET part of Visual Studio .NET compiles your code in the background.While this is considered an advantage for small projects, people creating very largeprojects have found that the IDE slows down considerably as the project gets larger.Advantages of C#vXML documentation is generated from source code but this is now been incorporatedin Whidbey.vOperator overloading which is not in current VB.NET but is been introduced inWhidbey.v Use of this statement makes unmanaged resource disposal simple.vAccess to Unsafe code. This allows pointer arithmetic etc, and can improveperformance in some situations. However, it is not to be used lightly, as a lot of thenormal safety of C# is lost (as the name implies).This is the major difference that youcan access unmanaged code in C# and not in VB.NET.84* How much ever this book tries it can not match the huge variations of questions that havebeen asked in.NET interviews.But note there will be variations and they will map to somequestion of this book.

(I)What is the difference between System exceptions and Applicationexceptions?All exception derives from Exception Base class. Exceptions can be generated programmaticallyor can be generated by system. Application Exception serves as the base class for all application-specific exception classes. It derives from Exception but does not provide any extended functionality.You should derive your custom application exceptions from Application Exception.Application exception is used when we want to define user defined exception, while systemexception is all which is defined by .NET.Figure :- 1.10 Exception Hierarchy85Note:- Frankly I have always relied on using Microsoft exception application blocks. Assuch I have never used application exception; I think most of the work is done using Systemexception classes.

(I)What is CODE Access security?CAS is part of .NET security model that determines whether or not a piece of code is allowed torun and what resources it can use while running. Example CAS will allow an application to readbut not to write and delete a file or a resource from a folder..


(A)How to prevent my .NET DLL to be decompiled?By design .NET embeds rich Meta data inside the executable code using MSIL. Any one can easilydecompile your DLL back using tools like ILDASM (owned by Microsoft) or Reflector for.NET which is a third party. Secondly there are many third party tools which make this decompilingprocess a click away. So any one can easily look in to your assemblies and reverse engineer themback in to actual source code and understand some real good logic which can make it easy tocrack your application.The process by which you can stop this reverse engineering is using “obfuscation”. It’s a techniquewhich will foil the decompilers. There are many third parties (XenoCode, Demeanor for .NET)which provide .NET obfuscation solution. Microsoft includes one that is Dotfuscator CommunityEdition with Visual Studio.NET.Note: - I leave this as homework to reader’s compile, a DLL obfuscate it using“Dotfuscator Community Edition” which comes with Visual Studio.NET and try viewingthe same using ILDASM.

(I) What is the difference between Convert.toString and .toString()method ?Just to give an understanding of what the above question means seethe below code.int i =0;MessageBox.Show(i.ToString());MessageBox.Show(Convert.ToString(i));86We can convert the integer “i” using “i.ToString()” or “Convert.ToString” so what’s the difference.The basic difference between them is “Convert” function handles NULLS while “i.ToString()”does not it will throw a NULL reference exception error. So as good coding practice using“convert” is always safe.


No comments: