Thursday, 3 January 2008

.NET Interview Questions (2)

The following list is the second part:

Mid-Level .NET Developer



  • Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.
    Interface-oriented programming – an interface is created to define the contract and rules, without caring about the implementation. All parties follow the contract and rules and communicate through the contract. One example is Web Service.
    Object-oriented programming – classes implements the concept of abstraction, encapsulation, polymorphism and inheritance. Abstraction means loose coupling between components by providing interfaces. Encapsulation means hiding details of class implementation. Polymorphism means different implementation of a same function name in different classes. Inheritance means functionalities of a base class can be shared by child classes.
    Aspect-oriented programming – AOP complements object-oriented programming. It allows a developer to dynamically change or adding behaviour to a static OO model without changing the original code.


  • Describe what an Interface is and how it’s different from a Class.
    An interface is a contract defining the properties and methods should be implemented without implementation. A class holds both properties and member functions and their implementation.
    In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.

  • What is Reflection?
    Reflection is the ways to gather object information at runtime.

  • What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?
    XML Web Services is an open standard technology, working with HTTP/SOAP protocol for communication. .NET Remoting is a .NET proprietary technology working only with .NET Framework. .NET Remoting is usually used in internal network and provide a higher speed than web service.


  • Are the type system represented by XmlSchema and the CLS isomorphic?
    XmlSchema is a set of rules to define an xml document should meet. The types in XmlSchema include xs:Decimal, xs:Boolean, xs:Int and so on. CLS is Common Language Runtime, which defines a set of data types a .net application should use. These types include System.Decimal, System.Boolean and so on. The data types in XmlSchema and CLS have some difference so we have IXmlSerializable interface to help transfer data between an XML file and CLS objects. When implement IxmlSerializable interface, we write our own code to implement WriteXml() and ReadXml() functions to handle data transfer between xml and CLS objects.


  • Conceptually, what is the difference between early-binding and late-binding?
    Early binding – The call of a function can be resolved at compile time. Late binding – the actual code to call of a function can only be resolved at run time. Example: person.DoSomething() is a early binding.
    Type t; t.InvokeMember("DoSomething") is late binding.


  • Is using Assembly.Load a static reference or dynamic reference?
    This function loads an assembly dynamically at runtime.


  • When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?
    Assembly.LoadFrom() takes an assembly name as parameter, Assembly.LoadFile() takes an assembly file name as parameter. The two functions are appropriate when building dynamic applications with no dependency on dll files.


  • What is an Asssembly Qualified Name? Is it a filename? How is it different?
    A Qualified Name include Assembly Name, Public Key Token, Culture and Version number. It’s not a file name. File name is a physical name in the file system.


  • Is this valid? Assembly.Load("foo.dll");
    No. Assembly.Load() only takes assembly name as parameter, not file name.


  • How is a strongly-named assembly different from one that isn’t strongly-named?

  • Can DateTimes be null?
    DateTime is non-nullable value type. It can’t be null.


  • What is the JIT? What is NGEN? What are limitations and benefits of each?
    JIT – Just In Time compilation. The compiler produces the portable executable assembly called MSIL. This MSIL is compiled into native code by .NET JIT for the first time the assembly is called. The benefit of JIT is one assembly can be ported to different systems with different JIT compiler. The limitation is it takes some time to compile for the first run.
    NGEN – NGEN creates true CPU native code from the MSIL on the client machine. It simply calls JIT compiler to produce native images from assembly and store them in the native image cache. The benefit of NGEN is the client application is fast to start up. The limitation of NGEN is it’s not recommended for asp.net applications because the assembly created cannot be shared across app domains.


  • How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?
    There are three generations defined by CLR. .NET Garbage Collector determines the life time of an object by the time it is created. The shorter lived objects are more likely to be freed than longer lived objects.
    Non-deterministic finalization means an object’s finalizer function is called by Garbage Collector when it’s freed. The time when the object is freed is not known by the application.


  • What is the difference between Finalize() and Dispose()?
    Finalize() function is non-public and called by GC, it’s unknown when the function is called. Dispose() function is public and called by the application, a developer is responsible to call this function.


  • How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?
    Using pattern ensures the Dispose() function of an object created with the statement is forced to be called at the end of scope. IDisposable is the interface defines Dispose() function. If a class implement IDisposable interface, then the Dispose() method is implemented and forced to be called at the end of the using scope.


  • What does this useful command line do? tasklist /m "mscor*"
    This command displays all current running processes that loaded the dlls with the name matching the string pattern.


  • What is the difference between in-proc and out-of-proc?
    In-proc procedure calls happen within one process. Out-of-proc procedure calls happen between different processes, thus requires object marshalling and slower.

  • What technology enables out-of-proc communication in .NET?
    .NET remoting enables out-of-proc communications.

  • When you are running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?

    In Windows XP and 2000, asp.net is running within aspnet_wp.exe worker process. In Windows 2003, IIS 6 is running. The process is w3wp.exe in IIS 6.

.NET Interview Questions (1)

Scott Hanselman has a popular list of "What Great .NET Developers Ought To Know" questions that have many answers on the Internet. I collected these answers and organized them with some of my own words. This post is the first part.


Everyone who writes code


  • Describe the difference between a Thread and a Process?
    A Process is a block of executable program bounded by its virtual address space. A Thread is a part of a process, it can only execute within the address space of a process. A process must have at lease one thread, or have multiple threads running simultaneously to improve efficiency. In .Net classes under System.Threading namespace are mainly used for multi-threading and asynchronous programming.

  • What is a Windows Service and how does its lifecycle differ from a "standard" EXE?
    A Windows Service is an application running in the background without a visual user interface. Typically a Windows Service is started by Windows automatically when the system is started, or started manually through Control Panel->Services shortcut. A standard exe application is started and closed by a login user, and has a user interface to respond user interaction events. A Windows Service must be installed in order to run. A Windows Service runs in its own security context with a specific user account. A standard application runs under the security context of current login user.

  • What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?
    In a 32-bit system, the maximum memory available is 232 = 4GB. Because the operating system takes up 50% of available memory, a single process can only take maximum 2GB.
    This memory limitation affect those applications take large amount of memory like database management servers. To have more memory available for applications, we can set /3GB switch to the system start up line in c:\boot.ini file.

  • What is the difference between an EXE and a DLL?
    An EXE file has an entry point (in C# is main() function) and can run independently by itself, a DLL contains functions and can only be loaded within an EXE.

  • What is strong-typing versus weak-typing? Which is preferred? Why?
    A strong type checks object type at compile time. A weak type checks object type at run time. For example, Person p = new Person(); p is a strong type. Object o = new Person(); o is a weak type.
    Strong types can reduce bugs at run time. Weak types are more flexible to program. The preference is dependent on the type of application. For quick and small jobs like VBScript, weak-typing is preferred because it’s quicker to write code. For large projects strong-typing is preferred because most errors can be trapped at compile time.

  • Corillian's product is a "Component Container." Name at least 3 component containers that ship now with the Windows Server Family.
    A container is a class implement System.ComponentModel.IContainer interface, and can hold controls. Three containers are: System.Web.UI.Page, System.Windows.Forms.Form and System.ComponentModel.Container.

  • What is a PID? How is it useful when troubleshooting a system?
    PID is process ID. It’s an integer to identity a process running in the operating system. It can be used to identify a process, start and kill a process in a multi-tasking system for troubleshooting. Also in Visual Studio .NET, a process running in the operating system can be attached to the debugger to debug into the process.

  • How many processes can listen on a single TCP/IP port?
    Only one.

  • What is the GAC? What problem does it solve?
    A GAC stands for global assembly cache. It’s a machine-wide code cache. An assembly deployed in GAC has a strong name, which contains a digital signature, publisher information, version number and culture information.
    It solves “DLL Hell” problem.


  • What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

    The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.


  • Explain ACID rule of thumb for transactions.

    A transaction must be:
    1. Atomic - it is one unit of work and does not dependent on previous and following transactions.
    2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.
    3. Isolated - no transaction sees the intermediate results of the current transaction).
    4. Durable - the values persist if the data had been committed even if the system crashes right after.

How to debug VB Script in Visual Studio 2005

It has been a biggest pain to maintain a bunch of VB Script files since I work for this company. We have many daily tasks that were developed in early years when Sql Server SSIS hasn't been available. At the time of development it looked like VB Script was a good choice. And then the previous developer wrote many VB Script files sitting there for some business critical daily processes like sending invoices to customers, extracting data from our ERP system and running some stored procedures.

Some script files are very simple and contain less than 50 lines of code. For simple script files I have no problem of maintaining them, but I was horified by some monster script files like the one sending invoices to customers. There are pages of code in a file. They are definitely not for faint-hearted.

One of the major problem I had was unable to debug into script files. If we have some problems to fix I had to read each line of code and guess what was happening. And there is not enough comment in code for me to understand.

This situation lasted for several months. And some day when I was struggling again with them, I suddenly got this idea: I could put these VB Script inside ASP files and debug with ASP! Yes it's possible to do it because both Windows Script and ASP script use the same Windows Script Host.

Then I made a testing ASP page and copy it to local wwwroot folder. In the page I copied code from one of script files and inclosed the script with the <% %> symbol. Then I opened my IE and browsed to the address and I got problem with file permission immediately. This was resolved by setting proper permission to the folder under Windows. Then the ASP page run successfully!

This was a big step. Then I decided to debug the asp page using Visual Studio 2005. To debug in Visual Studio is simple. I just need to open the asp file, and attach to the process that loading the asp application.

Then the final step was to identify the process that loading the ASP script. When I browse to the ASP page and there was a bug in the file, I got this dialogue asking me which debugger to use:



When I selected a new instance of Visual Studio 2005 and click OK. The I got this security alert box:



This dialogue box told me the process is c:\windows\system32\dllhost.exe. I don't need this so I just clicked Don't Attach button.

Then I opened the asp file in Visual Studio 2005 and attached the process in menu Debug\Attach to Process and all worked fine with break points and variable value watching!

Saturday, 29 December 2007

Improve web service efficiency by using SoapDocumentMethod(OneWay = true)

Sometimes we have a long running process in a web method but we don't want our client application to wait until the process is finished. We can decorate our web method with this attribute:
[SoapDocumentMethod(OneWay = true)]

This setting tells web service client not to wait for the web server to finish the process of the web method. This is ideal for logging client events because client application doesn't care if the web server is sucessfull with doing logging.

Friday, 28 December 2007

Custom SoapExtension, SoapHeader and Web Method authentication

Currently I am working on a project which involves Web Service and Windows Client. The web service will be public and we are going to give the Windows client application to our suppliers across the Internet. The communication between client and our server is through Web Service.

To make our Web Service secure, login is required. Users provide their user name and password in the initial Web Service call through a login web method. In the subsequent calls, the user name and password are provided all the time. By doing this an anounimous user will fail when making a call to our secured methods.

This makes me think how I am going to transfer login information. In my previous project for another client, I used to concatenate user name and password into one string and pass to each web method through an extra parameter. And we validate the user in each web method. I feel this is tedious and not quite right. Fortunately I came across SoapHeader and SoapExtention when I read the book: .NET Framework 2.0 Distributed Application Development published by Microsoft Press. And I realized this is what I need to implement web method authentication.

According to SOAP specification, a SOAP message contains a Header, an Envelope, and a Body element. The Header is optional, but if included, it's inside the Envelope element and usually contains authentication information.

.NET we can have our custom header class which inherits from SoapHeader class. Here is my example:

public class ServiceAuthHeader : SoapHeader
{
private string userName;

public string UserName
{
get { return userName; }
set { userName = value; }
}
private string password;

public string Password
{
get { return password; }
set { password = value; }
}
}


In the client side consuming code, we must pass user data through Header as below:

RemoteService.RemoteService service = new RemoteService.RemoteService();
RemoteService.ServiceAuthHeader authHeader = new RemoteService.ServiceAuthHeader();
authHeader.UserName = userName;
authHeader.Password = password;
service.ServiceAuthHeaderValue = authHeader;

DataSet ds = service.GetMasterData();

In the Web Service class, we declare a public ServiceAuthHeader property.

private ServiceAuthHeader authSoapHeader;
public ServiceAuthHeader AuthSoapHeader
{
get { return authSoapHeader; }
set { authSoapHeader = value; }
}


And decorate the web method with SoapHeaderAttribute, as below:

[SoapHeader("AuthSoapHeader")]
[WebMethod]
public DataSet GetMasterData()
{
string userName = string.Empty;
if (AuthSoapHeader != null)
{
userName = AuthSoapHeader.UserName;
// then do business with userName.
}
}

Note there is nothing related with Authentication so far. Authentication is implemented through SoapExtension as discussed below.

SoapExtension privides a powful way of allowing developers to add additional functionalities to standard web methods. In another project we used SoapExtension to provide data compression for communication between a Windows Mobile device and a web server through GPRS network.

We simply inherit our custom extension class from SoapExtension as below:
public class AuthSoapExtension : SoapExtension

There are several abstract methods from SoapExtension, we are only interested in ProcessMessage(SoapMessage message) method. This method gives developers a chance to handle the SOAP message in each stage. There are four stages during the processing of a SOAP message in the web server: BeforeSerialize, AfterSerialize, BeforeDeserialize, and AfterDeserialize. The Stage property of message parameter indicates which stage the current message is in. The Header object is available in the AfterDeserialize stage because the SOAP message is deserialized into .NET objects.

The following code is used to get user information from header and validate.

public override void ProcessMessage(SoapMessage message)
{
if (message.Stage == SoapMessageStage.AfterDeserialize)
{
ServiceAuthHeader header = message.Headers[0] as ServiceAuthHeader;
if (header != null)
{
bool valid = ServiceValidation.ValidateUser(header.UserName, header.Password);
if (!valid)
{
throw new Exception("Invalid username or password.");
}
}else{
throw new ArgumentNullException("No ServiceAuthHeader provided in SoapMessage.");
}
}
}

To apply this custom soap extension to our web method, we need another attribute inherits from SoapExtensionAttribute.

[AttributeUsage(AttributeTargets.Method)]
public class AuthExtensionAttribute : SoapExtensionAttribute
{
private int _priority;

public override Type ExtensionType
{
get { return typeof(AuthSoapExtension); }
}

public override int Priority
{
get
{
return _priority;
}
set
{
_priority = value;
}
}
}


Then in our web method, we decorate it with this attribute:

[SoapHeader("AuthSoapHeader")]
[WebMethod]
[AuthExtension]
public DataSet GetMasterData()

The decoration tells the web method to use our custom AuthSoapExtension. Each time this web method is called, the ProcessMessage method in AuthSoapExtension is triggered, and the username and password information is retrieved from our custom SoapHeader and validated against a database.

Friday, 1 June 2007

Pass a list of values as a parameter to stored procedure

I encountered this problem long time ago and I used some complex approach to solve it. Today I come across a excellent approach by converting delimited string into a table return as an table-value function.

The original article is here:

http://www.codeproject.com/cs/database/TableValuedFnsAsArrays.asp

The function is as below.

CREATE FUNCTION [dbo].[StringToTable]
(
@string VARCHAR(MAX),
@delimiter CHAR(1)
)
RETURNS @output TABLE(
data VARCHAR(256)
)
BEGIN

DECLARE @start INT, @end INT
SELECT @start = 1, @end = CHARINDEX(@delimiter, @string)

WHILE @start <= LEN(@string) + 1 BEGIN
IF @end = 0
SET @end = LEN(@string) + 1

INSERT INTO @output (data)
VALUES(SUBSTRING(@string, @start, @end - @start))
SET @start = @end + 1
SET @end = CHARINDEX(@delimiter, @string, @start)
END

RETURN

END

Sunday, 1 April 2007

Use Mutex class to ensure only one instance of an application is running

Mutex class is an operating system level class to provide a data locking mechanism in multi-threading application. It works by locking data across AppDomain and process boundaries. Thus this class is ideal to ensure only one instance of an application is running.

In the Main() function of Progam.cs, add this piece of code will ensure one instance of an application, because the MutexName is shared across application domains.

Mutex one = null;
const string MutexName = "RunOnce";
try
{
one = Mutex.OpenExisting(MutexName);
}
catch (WaitHandleCannotBeOpenedException)
{
}

if (one == null)
{
one = new Mutex(true, MutexName);
}
else
{
one.Close();
return;
}