Tuesday, 4 November 2008

Use FMTONLY To Obtain an Query or stored procedure metadata

When executing a t-sql or stored procedure, if set FMTONLY value to ON, an zero-row resultset is produced with metadata information. The full query is not run. This feature is used for many report designers like Crystal Report and Reporting Service.

For example:

SET FMTONLY ON
select * from dbo.Items
SET FMTONLY OFF

The result is an empty row with column names and column data types.

Wednesday, 3 September 2008

Declare a local variable in T-Sql while loop

I have had some trouble to find a bug inside a sql server stored procedure.

I have a while loop in the stored procedure like this:

While Exists(…)
Begin
Declare @CategoryID int

// here I assign the value to @CategoryID with a CategoryID field by joining Category and Product tables, the join could return one record or no record with some where clause.

// then check value @CategoryID by printing it

// do something to make the while loop end
End

There is no problem with while loop itself, it ends as expected. The problem is the value of @CategoryID variable. I assume each time I declare the variable in the loop, a null value is assigned it by default. But the reality is not, if there is a value returned from the table join select, the value is assigned to the variable, this is how it should be. But if there is no value returned from the join, the value from the last loop is carried forward, instead of a null. This makes me thinking if the Declare command in a while loop only happen once and leave the variable available for the next loop.

Wednesday, 16 July 2008

Reporting Service security

I have a Reporting Service report which sits in a remote server. I need to display the report in a ReportViewer control in a dotnetnuke portal. The report was displayed fine when I test in a stand alone web page, but when I deploy the user control in the DNN portal, I got the following security message:

The permissions granted to user 'BIOLAB\AD_ALANZ$' are insufficient for performing this operation. (rsAccessDenied)

It turns out the account used in my local computer doesn't have enough permission to view the report.

I did a search through web and solved by the following steps:
Go to the report manager home page. Click on Properties tab.
Click on New Role Assignment button.
Add a new user BIOLAB\AD_ALANZ$, choose Browser role from the list and click Apply.

Then my report is showing in the ReportViewer successfully.

Tuesday, 17 June 2008

ASP.NET session state is not available in custom role provider

I have a custom role provider. In the method public override string[] GetRolesForUser(string username) I check the role name stored in a session variable. This didn't work, as when I put a break point in the code I found out the value of HttpContext.Current.Session is null.

I stumbled for a while and I came to this link http://forums.asp.net/p/967758/1214615.aspx. In the post ScottGu says "Unfortunately authentication and authorization happen before the session object is populated."

So I have to change to load user role from database by the user name.

Thursday, 8 May 2008

How to split a string in t-sql

If a list of values are concatenated by a character like '1,2,3,4,5', we need to split the string to a temp table so each value can be used in sql query. There are many tricks of doing this but the easiest one I have seen is below:


DECLARE @Parameter VARCHAR(8000)
SET @Parameter = 'Element01,Element02,Element03,Element04,Element05'

-- Create a table to store the results in
DECLARE @Elements TABLE
(
Number INT IDENTITY(1,1), --Order it appears in original string
Value VARCHAR(8000) --The string value of the element
)

--Decalre a variable to remember the position of the current delimiter
DECLARE @N INT
-- Add start and end commas to the Parameter so we can handle
-- single elements

SET @Parameter = ','+@Parameter +','

SET @N = 1

-- Loop through and find each comma, then insert the string value
-- found between the current comma and the next comma. @N is
-- the position of the current comma.
WHILE @N < LEN(@Parameter) --Don't include the last comma
BEGIN
INSERT INTO @Elements
VALUES (SUBSTRING(@Parameter, @N+1, CHARINDEX(',', @Parameter, @N+1) - @N-1))
-- Find the next comma
SELECT @N = CHARINDEX(',',@Parameter,@N+1)

END

SELECT * FROM @Elements

Monday, 18 February 2008

T-SQL alias play around

I noticed an interesting feature of T-SQL reagarding field alias in a sql statement. The field alias cannot be used in a WHERE clause but can be used in ORDER BY .

To test this I have created a table called Test with two columns: ID and TestDate. The ID is an identity column and TestDate is DateTime. I populated several ramdom records in the table.

First I run the following sql :
select ID, TestDate AS RealDate, Convert(varchar, TestDate, 103) AS DisplayDate from test
Where TestDate > '01/03/2006'
order by RealDate

5 2006-02-01 00:00:00.000 01/02/2006
3 2006-02-10 00:00:00.000 10/02/2006
1 2006-02-23 00:00:00.000 23/02/2006
2 2006-02-25 00:00:00.000 25/02/2006
4 2006-04-08 00:00:00.000 08/04/2006

The result shows the date time field is sorted properly and alias RealDate is used for sorting.

Then I run this:
select ID, TestDate AS RealDate, Convert(varchar, TestDate, 103) AS DisplayDate from test
Where TestDate > '01/03/2006'
order by DisplayDate

5 2006-02-01 00:00:00.000 01/02/2006
4 2006-04-08 00:00:00.000 08/04/2006
3 2006-02-10 00:00:00.000 10/02/2006
1 2006-02-23 00:00:00.000 23/02/2006
2 2006-02-25 00:00:00.000 25/02/2006

The result shows the sorting is by the varchar field and this is what I have expected.

Then I run this:
select ID, TestDate AS RealDate, Convert(varchar, TestDate, 103) AS DisplayDate from test
Where DisplayDate > '01/03/2006'
order by DisplayDate

Msg 207, Level 16, State 1, Line 1
Invalid column name 'DisplayDate'.

And this:
select ID, TestDate AS RealDate, Convert(varchar, TestDate, 103) AS DisplayDate from test
Where RealDate > '01/03/2006'
order by DisplayDate

Msg 207, Level 16, State 1, Line 1
Invalid column name 'RealDate'.

The two error messages above show we can't use alias in a where clause.

Wednesday, 23 January 2008

Schedule a SSIS package job by dtexec command

It has been a pain to schedule a Sql Agent Job for SSIS packages by using the new SSIS package step type. The security and permission problems are so complex that we can't figured out how to setup the proxy or account permissions. I have read the MSDN help and some step by step instructions but I have no luck by doing that.

Finally I decided to change the job step type to Operating System (CmdExec) and using the dtexec command to run the package directly. And this solved the permission problem immediately. The Job runs more than happy and we don't have the pain anymore.

Tuesday, 15 January 2008

Setup configuration file for a unit test project

It's a common scenario when we need to have a configuration file when doing unit testing, especially for testing a database access object. If the project tested is a Windows application, the configuration in the project is app.config, for a web project it's web.config. The configuration file must be copied to the testing bin folder to read configuration data, with the file name AssemblyFile.dll.config. We could copy the config file to the bin\debug or bin\release folder in the testing project, but then we are maintaining multiple copies manually.

To avoid this, we can take advantage of the Post-build event of Visual Studio. First we need to copy app.config file from testing Windows application project to the root folder of the testing project, or web.config file from the Web project and rename it to app.config. Secondly in the testing project property window, click on Build Events tab, we can then enter the following into the Post-build event command line box:

copy /Y "$(ProjectDir)App.config" "$(TargetDir)$(TargetFileName).config"

This command will copy and rename the configuration file to the target folder automaticallty.

Thursday, 10 January 2008

Reg-less Com component deployment

I was developing a Windows application which uses an Activex control from a third party vendor. I registered the control, made a reference to the component in my project, and the application run very well. I made a ClickOnce deployment for my application and try to run the application from a web page in another computer which doesn't have the activex control registered, I didn't find any luck. The application failed to start.

I noticed after I register the activex control in that computer manually, the application run immediately. It turns out the deployment package doesn't register the activex control automatically. I don't want to register the activex control in every computer of our clients, because the maintenance will become a nightmare.

Then I came across this page when I did some gooling:

http://msdn.microsoft.com/msdnmag/issues/05/04/RegFreeCOM/default.aspx

It talks about how to deploy an activex control without registering it. This is page is just what I need.

I followed the procedure by changing the Isolated property of the COM reference to true. When I run the application locally, I saw the dll file containing the COM component was copied to the bin folder of my project.


After I deploy the application to my website again with the change, I run the application successfully even without the activex control registered.

Wednesday, 9 January 2008

Define a prerequisites download location for Windows ClickOnce deployment

In a .NET Windows application, we can publish the application in a Internet web site and ask users to install it from a web page. One of the prerequisites of my application is .NET Framework 2.0. When I publish the installation files, I initially chose to download prerequisites files from vendors web site, but it didn't work.

Then I chose to download from a specific location, and the download was successful. Is there anything wrong with Microsoft's supporting website? The Microsoft website may be working fine, but our firewall setting could prevent us from downloading from an external website.

This makes me upload the .net Framwork installation package into our own website and then I am sure the downloading is guaranteed.

Tuesday, 8 January 2008

Use Application.ThreadException event to catch unhandled exceptions in a Windows Forms application

Application.ThreadException event occurs when an unhandled exception is thrown, based on MSDN. To avoid your Windows application from crashing when an exception is not caught by your code, you should attach your own event handler to this event in program.cs file.

The following code shows how this works:

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(UnHandledException);

Application.Run(new MainForm());
}

static void UnHandledException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
}

Note the event handler should be attached before the Application.Run method.

Monday, 7 January 2008

Scroll a Windows Form DataGridView to a specific row

I have a Windows Form which contains a TextBox and a DataGridView. When a user enters anything I need to do a search and make the grid scroll to the row matched.

I was struggling for a while for the scrolling until I came across this property: FirstDisplayedScrollingRowIndex. It's simple, just assign the row index value to this property and the grid will scroll to the row and show the row as the first row in the visible area.

Friday, 4 January 2008

.NET Interview Questions (6)

Developers using XML


· What is the purpose of XML Namespaces?
XML Namespaces remove conflicts between different documents from different sources.

· When is the DOM appropriate for use? When is it not? Are there size limitations?
Dom is appropriate for small document and the document needs to be modified. It’s not appropriate for big document because of performance issue. There is no size limitation as long as there is enough physical memory.

· What is the WS-I Basic Profile and why is it important?

· Write a small XML document that uses a default namespace and a qualified (prefixed) namespace. Include elements from both namespace.

· What is the one fundamental difference between Elements and Attributes?
Element can contain another elements and attributes. Attributes can only reside inside an element.

· What is the difference between Well-Formed XML and Valid XML?
Well-Formed XML follows xml grammar. Valid XML is validated against xml schema or dtd. A valid xml is well-formed. A well-formed xml might not be valid.

· How would you validate XML using .NET?
Using XmlValidatingReader class.

· Why is this almost always a bad idea? When is it a good idea? myXmlDocument.SelectNodes("//mynode");
This statement returns all elements under mynode. This could return a large amount of data. It’s more efficient to use SelectSingleNode method and pass a full path, or use SelectNodes with a relatively deeper path.

· Describe the difference between pull-style parsers (XmlReader) and eventing-readers (Sax)
In XmlReader you control the parsing and define which element to go to. Sax parses the Xml internally, and raises events whenever it find something interesting.

· What is the difference between XPathDocument and XmlDocument? Describe situations where one should be used over the other.
XpathDocument is not editable. XmlDocument is editable. XpathDocument is used for fast readonly situation. XmlDocument is used when the document needs to be changed.

· What is the difference between an XML "Fragment" and an XML "Document."
XML Fragment is not a full xml document. It doesn’t have element.

· What does it meant to say “the canonical” form of XML?
The purpose of Canonical XML is to define a standard format for an XML document. Canonical XML is a very strict XML syntax, which lets documents in canonical XML be compared directly.
Using this strict syntax makes it easier to see whether two XML documents are the same. For example, a section of text in one document might read Black & White, whereas the same section of text might read Black & White in another document, and even in another. If you compare those three documents byte by byte, they’ll be different. But if you write them all in canonical XML, which specifies every aspect of the syntax you can use, these three documents would all have the same version of this text (which would be Black & White) and could be compared without problem. This Comparison is especially critical when xml documents are digitally signed. The digital signal may be interpreted in different way and the document may be rejected. Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSet attempt to solve?

· Contrast DTDs versus XSDs. What are their similarities and differences? Which is preferred and why?
Both are used for defining the rules of an xml document. DTDs are written in regex, XSDs are written using xml.
Document Type Definition (DTD) describes a model or set of rules for an XML document. XML Schema Definition (XSD) also describes the structure of an XML document but XSDs are much more powerful. The disadvantage with the Document Type Definition is it doesn’t support data types beyond the basic 10 primitive types. It cannot properly define the type of data contained by the tag. An Xml Schema provides an Object Oriented approach to defining the format of an xml document. The Xml schema support most basic programming types like integer, byte, string, float etc., We can also define complex types of our own which can be used to define a xml document. Xml Schemas are always preferred over DTDs as a document can be more precisely defined using the XML Schemas because of its rich support for data representation.

· Does System.Xml support DTDs? How?
Yes, in addition to XDR and XSD schema validation, .NET continues to support the DTD to validate the XML documents. The System.Xml namespace contains a class named XmlValidatingReader that can be used to validate the XML documents.

· Can any XML Schema be represented as an object graph? Vice versa?
Yes.

.NET Interview Questions (5)

ASP.NET (UI) Developers


· Describe how a browser-based Form POST becomes a Server-Side event like Button1_OnClick.
In ASP.NET, a button server control is rendered as a HTML submit control and an unique name is assigned to the submit control. In the client side, when a button is clicked, the page is posted to itself, ASP.Net uses the id value of the submit control to match the button server control and raises the OnClick event of the button control on the server side.

· What is a PostBack?
A web page post is submitted to itself on the web server when some client events occur, like a button is clicked.

· What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?
ViewState is a encoded string stored in a hidden page field. The data in the ViewState preserves the value of form controls between page round trips. Web server uses ViewState to re-populate value of form controls when a page is posted back.

· What is the element and what two ASP.NET technologies is it used for?
Machinekey element configures key to use for encryption and decryption. Forms authentication cookie and viewstate data uses it to encrypt and decrypt. It’s also used to verify out-of-process session state in a clustered server environment.

· What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each?
InProc – session is stored in the memory of same worker process of asp.net (aspnet_wp.exe or w3wp.exe). It’s fast but takes extra memory and not scalable.
StateServer – session is stored in another process (aspnet_state.exe) and can be another server. It’s slower but more robust and easier to manage.
SQLServer – session is serialized and stored in a Sql Server database. It’s slowest but very robust.

· What is Web Gardening? How would using it affect a design?
Web Garden model enables multiple worker process to run at the same time on a multiprocessor machine. ASP.NET launches multiple worker processes, and incoming requests are partitioned among running processes to balance the workload. Each process has its own copy of application state, in-process session state, ASP.NET cache and static data.
The web garden model is configurable through a section of machine.config, which affects all applications running on the server.
Side effects: Web Gardening is not suitable for heavy stateful applications.
Session state must be configured to an out-of-process provider – an NT Service or SQL Server.
Application state is per process not per computer.
Caching is per process not per computer.

· Given one ASP.NET application, how many application objects does it have on a single proc box? A dual? A dual with Web Gardening enabled? How would this affect a design?
For worker process - One worker process per CPU. On a dual CPU machine without Web Gardening enabled, it’s still one worker process. If Web Gardening is enabled on a dual CPU machine, it’s two worker prcesses.
For HttpApplication objects – asp.net creates an AppDomain for each virtual directory. Each AppDomain has an HttpApplication object pool. An individual HttpApplication object is created for each Http request. The number of HttpApplication objects is not configurable.

· Are threads reused in ASP.NET between reqeusts? Does every HttpRequest get its own thread? Should you use Thread Local storage with ASP.NET?
Threads are reused between requests. Each HttpRequest is served by an HttpApplication object, which is pooled.
We shouldn’t use Tread Local Storage. TLS is a mechanism to store data that is unique to a thread. Using TLS in a thread-pooling environment is tricky because you don’t know which thread is called as they are pooled.

· Is the [ThreadStatic] attribute useful in ASP.NET? Are there side effects? Good or bad?
[TreadStatic] attribute is not useful in ASP.NET. static fields marked with this attribute are not shared between threads. Each thread has a separate set of value. If a field is accessed in a different thread, it will have different value. ASP.NET uses thread pooling, different threads may be used for different requests. So the value of the static fields may be different.

· Give an example of how using an HttpHandler could simplify an existing design that serves Check Images from an .aspx page.
Just like .aspx page is an HttpHandler that handles Http Request. You can implement your own HttpHandler to return other MEMI type (image, download file, pdf etc) to browser. Then register your HttpHandler in the web.config (or you can register it in machine.config or IIS Application Configuration properties page if implements IHttpHandlerFactory).

· What kinds of events can an HttpModule subscribe to? What influence can they have on an implementation? What can be done without recompiling the ASP.NET Application?
An HttpMoudle can subscribe to following events:
AcquireRequestState When ASP.NET acquires the current state (for example, session state) associated with the current request.
AuthenticateRequest When a security module has established the identity of the user
AuthorizeRequest When a security module has verified user authorization
BeginRequest When the first event in the HTTP pipeline chain of execution responds to a request
Disposed When ASP.NET completes the chain of execution when responding to a request
EndRequest When the last event in the HTTP pipeline chain of execution responds to a request
Error When an unhandled exception is thrown
PostRequestHandlerExecute When the ASP.NET handler (page, XML Web Service) finishes execution
PreRequestHandlerExecute Just before ASP.NET begins executing a handler such as a page or XML Web Service
PreSendRequestContent Just before ASP.NET sends content to the client
PreSendRequestHeaders Just before ASP.NET sends HTTP headers to the client
ReleaseRequestState After ASP.NET finishes executing all request handlers; also causes state modules to save the current state data
ResolveRequestCache When ASP.NET completes an authorization event to let the caching modules serve requests from the cache, bypassing execution of the handler (the page or XML Web Service, for example)
UpdateRequestCache When ASP.NET finishes executing a handler in order to let caching modules store responses that will be used to serve subsequent requests from the cache
The ASP.NET runtime calls the module's Init and Dispose methods. Init is called when the module attaches itself to the HttpApplication object and Dispose is called when the module is detached from HttpApplication. The Init and Dispose methods represent the module's opportunity to hook into a variety of events exposed by HttpApplication.

· Describe ways to present an arbitrary endpoint (URL) and route requests to that endpoint to ASP.NET.


· Explain how cookies work. Give an example of Cookie abuse.
Cookie is a text file that contains a collection of values and an expiry date. Cookie data is sent to client browser from web server, and sent back to the web server by client browser later to identify the client.
Cookie abuse means a web server using cookie to collect personal information of a user without user consent.

· Explain the importance of HttpRequest.ValidateInput()?
ValicateInput() checks QueryString, Form and Cookie data for HTML markup tags to prevent potentially dangerous data.
The ValidateInput is called during the page’s ProcessRequest process stage if configured in page’s directive with validation=”true”. And this method can be called by code manually if not configured in the page.

· What kind of data is passed via HTTP Headers?
HTTP Headers contain metadata about the document. Eg.
HTTP/1.1 200 OK
Date: Wed, 13 Aug 1997 02:35:50 GMT
Server: IIS
Last-Modified: Fri, 04 Jul 1997 22:18:24 GMT
Content-Length: 2064
Accept-Ranges: bytes
Connection: close
Content-Type: text/html

· Juxtapose the HTTP verbs GET and POST. What is HEAD?
HTTP-Get passes information to the web server through URL parameter. The total length of the url is limited.
HTTP-Post send data to the web server through an input stream, the length of data is not limited.
HEAD – contains information of a HTML document. The server only returns header information like last modified date, file size, and the type of document.
One use of header information is to enable search engine to retrieve information of a document by defining additional metadata element.

· Name and describe at least a half dozen HTTP Status Codes and what they express to the requesting client.
100: Continue; 101: Switch protocols

200: OK; 201 Created; 202 Accepted

300 Multiple Choices; 301 Moved Permanently; 302: Redirect request found;

400: Bad request; 401:Unauthorized; 403: Forbidden; 404: Resource Not Found;

500: Internal Server Error; 501 Not Implemented; 502 Bad Gateway; 503 Service Unavailable.

· How does if-not-modified-since work? How can it be programmatically implemented with ASP.NET?
If-not-modified-since header allows the server to send 304 reponse (not modified) and not the full content of the page. You implement this by capturing the headers, checking for the presence of if-not-modified-since value, and then returning 304 status code

· Explain <@OutputCache%> and the usage of VaryByParam, VaryByHeader, VaryByCustom.
<@OutputCache%> Declaratively controls the output caching policies of an ASP.NET page or a user control contained in a page. Cached page/control is placed in memory.

VaryByParam: VaryByParam means that the cache hold different copies of the page for different parameters, and the same is true for different header for VaryByHeader. Different versions of the page are stored based on the query string values.
If there are one thousand different ids are queried in 30 sec, there will be one thousand pages cached. On the other hand queries page.aspx?id=1, page.aspx?id=1&Num=1, and page.aspx?id=1&Num=2 will receive the same cached page.

VaryByHeader: Different versions of the page are stored based on the specified HTTP header values.

Four requests arrive for the page with the following Accept-Language headers: 1) de-lu; 2) en-us; 3) fr; 4) en-us, three cached pages is created and the second en-us request reads from cache.

VaryByCustom: Different versions of the page are stored based on browser type and major version. Additionally, you can extend output caching by defining custom strings.

Then override the HttpApplication.GetVaryByCustomString method in the Global.asax file. This string is built by you and used as a key to store and retrieve a cached version of your page. The key can be anything and build from anything. You can create a composite key from other pieces of information available to you like cookies, user-languages, browser capabilities, whatever.

public override string GetVaryByCustomString(HttpContext context, string arg){
if(arg.ToLower() == "mycustomstring"){
HttpCookie cookie = context.Request.Cookies["ID"];
if(cookie != null)
return cookie.Value;
}
return base.GetVaryByCustomString (context, custom);
}

· How would one implement ASP.NET HTML output caching, caching outgoing versions of pages generated via all values of q= except where q=5 (as in http://localhost/page.aspx?q=5)?
Use AddValidationCallBack. It provides a mechanism to programmatically check the validity of an item in the cache before the item is returned from the cache. Before the response is served from the Web server cache, all registered handlers are queried to ensure resource validity. If any handler sets a flag indicating that the resource is invalid, the entry is marked invalid and evicted from the cache. The request is then handled as if it were a cache miss.

.NET Interview Questions (4)


C# Component Developers


· Juxtapose the use of override with new. What is shadowing?
Override modifier is used to a method signature in a derived class to provide a new implementation to the same method signature in the base class. The base method must have a modifier override, virtual or abstract.
If there is no such modifier in the base class method, then the method is not overridable. To provide a new implementation in the derived class, a “new” modifier is required. This is called shadowing. The implementation of derived class hide the implementation of base class.

· Explain the use of virtual, sealed, override, and abstract.
Virtual – a method with virtual modifier can be overridden in a derived class.
Sealed – a sealed class cannot be derived.
Override – a method with override modifier provide a new implementation of a same method name in the base class.
Abstract – an abstract class cannot be instantiated and must be inherited. An abstract method or property cannot be used directly, they must be overridden in derived class.

· Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d
The string shows a reference to a strongly named assembly.
Foo.Bar –Filename without extension, file containing the manifest.
Version – assembly version, used to resolver version problem
Culture – assembly culture, used to specify assemblies for various cultures.
PublicKeyToken – used to verify if assemblies have been tampered after publishing. And to differentiate assemblies from multiple publishers with the same name.

· Explain the differences between public, protected, private and internal.
Public – class or method is accessible to everyone who use it.
Protected – class or method is visible to derived class.
Private – class or method is visible to other members within the same class.
Internal – class or method is visible to other members within the same assembly.
Protected Internal – class or method is visible to member with the same assembly and to derived classes outside the assembly.

· What benefit do you get from using a Primary Interop Assembly (PIA)?
A primary interop assembly is a unique, vendor-supplied assembly that contains type definitions of types implemented with COM. There is only one primary interop assembly, which is signed with a strong name by the publisher of the COM type library.
A single primary interop assembly can wrap more than one version of the same type library. A COM type library that is imported as an assembly and signed by someone other than the publisher of the original type library cannot be a primary interop assembly. Only the publisher of a type library can produce a true primary interop assembly, which becomes the unit of official type definitions for interoperating with the underlying COM types. PIAs provide a single place for.NET apps to interop with existing COM objects.

· By what mechanism does NUnit know what methods to test?
By using [Test] attribute to decorate a method.

· What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;}
Throw e – the original stack trace is lost.
Throw - the original stack trace is kept.

· What is the difference between typeof(foo) and myFoo.GetType()?
Typeof – get the object type at compile time.
GetType() – get the object type at runtime using reflection.

· Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?
The first constructor calls base constructor.

· What is this? Can this be used within a static method?The this is the reference to the current instance of an object. This keyword cannot be used in a static method because it doesn’t have an instance.

.NET Interview Questions (3)

Senior Developers/Architects


· What’s wrong with a line like this? DateTime.Parse(myString);
This call doesn’t specify culture information. So a string like ‘12/06/2007’ would be parsed as 06 December 2007 or 12 June 2007 depending on the computer culture setting.

· What are PDBs? Where must they be located for debugging to work?
PDBs are program database files. They contain debugging information for a dll or exe file linking back to the source file.

· What is cyclomatic complexity and why is it important?
Cyclomatic complexity is a software measurement. It is used to measure the amount of decision login within a software module. It is important to measure the complexity of a software module and decide wether refactor a module into smaller ones or not.

· Write a standard lock() plus “double check” to create a critical section around a variable access.
Bool isLocked = false;
If(!isLocked)
{
Lock(lockingObject)
{
If(!isLocked)
{
isLocked = true;
// do something with lockingObject.
isLocked = false;
}
}
}

· What is FullTrust? Do GAC’ed assemblies have FullTrust?
FullTrust is a permission set in .NET framework. There are several predefined permission sets in .net: FullTrust, SkipVerification, Execution, Nothing, LocalIntranet, Internet, Nothing. When FullTrust is granted to a code then the code can access all resources the current user has access to.
GAC assemblies have FullTrust permission set. We can change the permission set of GAC assemblies through .net Configuration Tool.

· What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?
By decorating a method or assembly with security permissions, we can prevent the code from being used in a situation where beyond the permission it requires. And we can fail the code if the permissions it requires are not granted.

· What does this do? gacutil /l | find /i "Corillian" This command lists all assemblies in GAC with the name contains Corillian.

· What does this do? sn -t foo.dll
This command shows the token for the public key in the file foo.dll.

· What ports must be open for DCOM over a firewall? What is the purpose of Port 135?
DCOM uses Port 135 for transmission. Port 135 is to allow client application to locate a DCOM service.

· Contrast OOP and SOA. What are tenets of each? OOP – Application is built on objects, with inheritance, abstraction, polymorphism, encapsulation concepts.
SOA – In SOA we create an abstract layer to define a contract and rules. The client application doesn’t need to know how the service is implemented. The service layer will handle all the details of the implementation.

· How does the XmlSerializer work? What ACL permissions does a process using it require?
XmlSerializer find property values of an object by reflection and output values. ReflectionPermission is required to use it.

· Why is catch(Exception) almost always a bad idea?
This statement hides the error and do nothing about the error. This makes the application development and maintenance very difficult. And we shouldn’t try to catch a generic Exception because we shouldn’t treat system generated fatal errors the same as application generated non-fatal errors.

· What is the difference between Debug.Write and Trace.Write? When should each be used? Debug.Write works on debug mode only. It doesn’t work in a release build. Trace.Write works in both debug and release mode.

· What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?
A debug build contains debugging information for debugging purpose. A release build doesn’t contain debugging information and cannot be debugged. Release build is faster than debug build but the speed difference is not significant.

· Does JITting occur per-assembly or per-method? How does this affect the working set?
Per-method. Methods are not called are not compiled, this reduces the working set.

· Contrast the use of an abstract base class against an interface?
An abstract base class can contains some code but an interface cannot contain code. Abstract classes are useful when some default actions are provided. Classes inherit from an interface must implement all methods.

· What is the difference between a.Equals(b) and a == b?
The first method compares if the value of a and b are equal. The second way checks if the object reference of a and b are the same. For string objects, the second way has the same effect as the first.

· In the context of a comparison, what is object identity versus object equivalence?
Object identity means two objects points to a same memory address. Object equivalence means two objects may point to different memory address but the values in them are equal.

· How would one do a deep copy in .NET?
We can implement the Iclonalbe interface and call Clone() method of an object.

· Explain current thinking around IClonable.
The Clone() method in the IClonable interface doesn’t have a parameter to indicate how the object is cloned. It could be a full value clone or just reference clone depending on how a class is implemented.

· What is boxing?
Take a value type like int in stack and put it to reference type (object) in heap.

· Is string a value type or a reference type?
It’s a reference type.

· What is the significance of the "PropertySpecified" pattern used by the XmlSerializer? What problem does it attempt to solve?

· Why are out parameters a bad idea in .NET? Are they?
An out parameter may be leave as unsigned if the method throws an exception before the parameter is assigned a value.

· Can attributes be placed on specific parameters to a method? Why is this useful?Yes. It’s useful if you want to call COM objects and the types in .net need to be marshalled to types in COM.

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!