Tuesday, December 30, 2008

Short Answer .NET Interview Questions

Q1. Explain the differences between Server-side
and Client-side code?

Ans. Server side code will
execute at server (where the website is hosted) end, & all
the business logic will execute at server end where as client
side code will execute at client side (usually written in
javascript, vbscript, jscript) at browser end.

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

Ans. Server side code.

Q3. How to
make sure that value is entered in an asp:Textbox
control?

Ans. Use a RequiredFieldValidator
control.

Q4. Which property of a validation control
is used to associate it with a server control on that
page?

Ans. ControlToValidate property.

Q5.
How would you implement inheritance using VB.NET & C#?

Ans. C# Derived Class : Baseclass
VB.NEt : Derived
Class Inherits Baseclass

Q6. Which method is
invoked on the DataAdapter control to load the generated
dataset with data?

Ans. Fill() method.

Q7.
What method is used to explicitly kill a user's session?

Ans. Session.Abandon()

Q8. What property
within the asp:gridview control is changed to bind columns
manually?

Ans. Autogenerated columns is set to false


Q9. Which method is used to redirect the user to
another page without performing a round trip to the
client?

Ans. Server.Transfer method.

Q10.
How do we use different versions of private assemblies in same
application without re-build?

Ans.Inside the
Assemblyinfo.cs or Assemblyinfo.vb file, we need to specify
assembly version.
assembly: AssemblyVersion


Q11. Is it possible to debug java-script in .NET
IDE? If yes, how?

Ans. Yes, simply write "debugger"
statement at the point where the breakpoint needs to be set
within the javascript code and also enable javascript
debugging in the browser property settings.

Q12. How
many ways can we maintain the state of a page?

Ans. 1.
Client Side - Query string, hidden variables, viewstate,
cookies
2. Server side - application , cache, context,
session, database

Q13. What is the use of a
multicast delegate?

Ans. A multicast delegate may be
used to call more than one method.

Q14. What is the
use of a private constructor?

Ans. A private
constructor may be used to prevent the creation of an instance
for a class.

Q15. What is the use of Singleton
pattern?

Ans. A Singleton pattern .is used to make
sure that only one instance of a class exists.

Q16.
When do we use a DOM parser and when do we use a SAX
parser?

Ans. The DOM Approach is useful for small
documents in which the program needs to process a large
portion of the document whereas the SAX approach is useful for
large documents in which the program only needs to process a
small portion of the document.

Q17. Will the finally
block be executed if an exception has not
occurred?

Ans.Yes it will execute.

Q18. What
is a Dataset?

Ans. A dataset is an in memory database
kindof object that can hold database information in a
disconnected environment.

Q19. Is XML a
case-sensitive markup language?

Ans. Yes.


Q20. What is an .ashx file?
Ans. It is a web
handler file that produces output to be consumed by an xml
consumer client (rather than a browser).

Short Answer .NET Interview Questions


Q21. What is encapsulation?
Ans.
Encapsulation is the OOPs concept of binding the attributes
and behaviors in a class, hiding the implementation of the
class and exposing the functionality.

Q22. What is
Overloading?

Ans. When we add a new method with the
same name in a same/derived class but with different
number/types of parameters, the concept is called overluoad
and this ultimately implements Polymorphism.

Q23.
What is Overriding?

Ans. When we need to provide
different implementation in a child class than the one
provided by base class, we define the same method with same
signatures in the child class and this is called overriding.


Q24. What is a Delegate?
Ans. A delegate is
a strongly typed function pointer object that encapsulates a
reference to a method, and so the function that needs to be
invoked may be called at runtime.

Q25. Is String a
Reference Type or Value Type in .NET?

Ans. String is a
Reference Type object.

Q26. What is a Satellite
Assembly?

Ans. Satellite assemblies contain resource
files corresponding to a locale (Culture + Language) and these
assemblies are used in deploying an application globally for
different languages.

Q27. What are the different
types of assemblies and what is their use?

Ans.
Private, Public(also called shared) and Satellite Assemblies.


Q28. Are MSIL and CIL the same thing?
Ans.
Yes, CIL is the new name for MSIL.

Q29. What is the
base class of all web forms?

Ans. System.Web.UI.Page


Q30. How to add a client side event to a server
control?

Ans. Example...
BtnSubmit.Attributes.Add("onclick","javascript:fnSomeFunctionInJavascript()");


Q31. How to register a client side script from
code-behind?

Ans. Use the
Page.RegisterClientScriptBlock method in the server side code
to register the script that may be built using a
StringBuilder.

Q32. Can a single .NET DLL contain
multiple classes?

Ans. Yes, a single .NET DLL may
contain any number of classes within it.

Q33. What
is DLL Hell?

Ans. DLL Hell is the name given to the
problem of old unmanaged DLL's due to which there was a
possibility of version conflict among the DLLs.


Q34. can we put a break statement in a finally
block?

Ans. The finally block cannot have the break,
continue, return and goto statements.

Q35. What is
a CompositeControl in .NET?

Ans. CompositeControl is an
abstract class in .NET that is inherited by those web controls
that contain child controls within them.

Q36. Which
control in asp.net is used to display data from an xml file
and then displayed using XSLT?

Ans. Use the asp:Xml
control and set its DocumentSource property for associating an
xml file, and set its TransformSource property to set the xml
control's xsl file for the XSLT transformation.


Q37. Can we run ASP.NET 1.1 application and ASP.NET
2.0 application on the same computer?

Ans. Yes, though
changes in the IIS in the properties for the site have to be
made during deployment of each.

Q38. What are the
new features in .NET 2.0?

Ans. Plenty of new controls,
Generics, anonymous methods, partial classes, iterators,
property visibility (separate visibility for get and set) and
static classes.

Q39. Can we pop a MessageBox in a
web application?

Ans. Yes, though this is done
clientside using an alert, prompt or confirm or by opening a
new web page that looks like a messagebox.

Q40.
What is managed data?

Ans. The data for which the
memory management is taken care by .Net runtime’s garbage
collector, and this includes tasks for allocation
de-allocation.

Q41. How to instruct the garbage collector to
collect unreferenced data?

Ans. We may call the garbage
collector to collect unreferenced data by executing the
System.GC.Collect() method.

Q42. How can we set the
Focus on a control in ASP.NET?

Ans. txtBox123.Focus();
OR Page.SetFocus(NameOfControl);

Q43. What are
Partial Classes in Asp.Net 2.0?

Ans. In .NET 2.0, a
class definition may be split into multiple physical files but
partial classes do not make any difference to the compiler as
during compile time, the compiler groups all the partial
classes and treats them as a single class.

Q44. How
to set the default button on a Web Form?

Ans.
<asp:form id="form1" runat="server"
defaultbutton="btnGo"/>

Q45.Can we force the
garbage collector to run?

Ans. Yes, using the
System.GC.Collect(), the garbage collector is forced to run in
case required to do so.

Q46. What is Boxing and
Unboxing?

Ans. Boxing is the process where any value
type can be implicitly converted to a reference type object
while Unboxing is the opposite of boxing process where the
reference type is converted to a value type.

Q47.
What is Code Access security? What is CAS in .NET?

Ans.
CAS is the feature of the .NET security model that determines
whether an application or a piece of code is permitted to run
and decide the resources it can use while running.


Q48. What is Multi-tasking?
Ans. It is a
feature of operating systems through which multiple programs
may run on the operating system at the same time, just like a
scenario where a Notepad, a Calculator and the Control Panel
are open at the same time.

Q49. What is
Multi-threading?

Ans. When an application performs
different tasks at the same time, the application is said to
exhibit multithreading as several threads of a process are
running.2

Q50. What is a Thread?
Ans. A
thread is an activity started by a process and its the basic
unit to which an operating system allocates processor
resources.

Q51. What does AddressOf in VB.NET
operator do?

Ans. The AddressOf operator is used in
VB.NET to create a delegate object to a method in order to
point to it.

Q52. How to refer to the current
thread of a method in .NET?

Ans. In order to refer to
the current thread in .NET, the Thread.CurrentThread method
can be used. It is a public static property.

Q53.
How to pause the execution of a thread in .NET?

Ans.
The thread execution can be paused by invoking the
Thread.Sleep(IntegerValue) method where IntegerValue is an
integer that determines the milliseconds time frame for which
the thread in context has to sleep.

Q54. How can we
force a thread to sleep for an infinite period?

Ans.
Call the Thread.Interupt() method.

Q55. What is
Suspend and Resume in .NET Threading?

Ans. Just like a
song may be paused and played using a music player, a thread
may be paused using Thread.Suspend method and may be started
again using the Thread.Resume method. Note that sleep method
immediately forces the thread to sleep whereas the suspend
method waits for the thread to be in a persistable position
before pausing its activity.

Q56. How can we
prevent a deadlock in .Net threading?

Ans. Using
methods like Monitoring, Interlocked classes, Wait handles,
Event raising from between threads, using the ThreadState
property.

Q57. What is Ajax?
Ans.
Asyncronous Javascript and XML - Ajax is a combination of
client side technologies that sets up asynchronous
communication between the user interface and the web server so
that partial page rendering occur instead of complete page
postbacks.

Q58. What is XmlHttpRequest in
Ajax?

Ans. It is an object in Javascript that allows
the browser to communicate to a web server asynchronously
without making a postback.

Q59. What are the
different modes of storing an ASP.NET session?

Ans.
InProc (the session state is stored in the memory space of the
Aspnet_wp.exe process but the session information is lost when
IIS reboots), StateServer (the Session state is serialized and
stored in a separate process call Viewstate is an object in
.NET that automatically persists control setting values across
the multiple requests for the same page and it is internally
maintained as a hidden field on the web page though its hashed
for security reasons.

Q60. What is a delegate in
.NET?

Ans. A delegate in .NET is a class that can have
a reference to a method, and this class has a signature that
can refer only those methods that have a signature which
complies with the class.

Q61. Is a delegate a type-safe functions
pointer?

Ans. Yes

Q62. What is the return
type of an event in .NET?

Ans. There is No return type
of an event in .NET.

Q63. Is it possible to specify
an access specifier to an event in .NET?

Ans. Yes,
though they are public by default.

Q64. Is it
possible to create a shared event in .NET?

Ans. Yes,
but shared events may only be raised by shared
methods.

Q65. How to prevent overriding of a class
in .NET?

Ans. Use the keyword NotOverridable in VB.NET
and sealed in C#.

Q66. How to prevent inheritance of
a class in .NET?

Ans. Use the keyword NotInheritable in
VB.NET and sealed in C#.

Q67. What is the purpose of
the MustInherit keyword in VB.NET?

Ans. MustInherit
keyword in VB.NET is used to create an abstract
class.

Q68. What is the access modifier of a member
function of in an Interface created in .NET?

Ans. It is
always public, we cant use any other modifier other than the
public modifier for the member functions of an
Interface.

Q69. What does the virtual keyword in C#
mean?

Ans. The virtual keyword signifies that the
method and property may be overridden.

Q70. How to
create a new unique ID for a control?

Ans.
ControlName.ID = "ControlName" + Guid.NewGuid().ToString();
//Make use of the Guid class

Q71A. What is a
HashTable in .NET?

Ans. A Hashtable is an object that
implements the IDictionary interface, and can be used to store
key value pairs. The key may be used as the index to access
the values for that index.

Q71B. What is an
ArrayList in .NET?

Ans. Arraylist object is used to
store a list of values in the form of a list, such that the
size of the arraylist can be increased and decreased
dynamically, and moreover, it may hold items of different
types. Items in an arraylist may be accessed using an
index.

Q72. What is the value of the first item in
an Enum? 0 or 1?

Ans. 0

Q73. Can we achieve
operator overloading in VB.NET?

Ans. Yes, it is
supported in the .NET 2.0 version, the "operator" keyword is
used.

Q74. What is the use of Finalize method in
.NET?

Ans. .NET Garbage collector performs all the
clean up activity of the managed objects, and so the finalize
method is usually used to free up the unmanaged objects like
File objects, Windows API objects, Database connection
objects, COM objects etc.

Q75. How do you save all
the data in a dataset in .NET?

Ans. Use the
AcceptChanges method which commits all the changes made to the
dataset since last time Acceptchanges was
performed.

Q76. Is there a way to suppress the
finalize process inside the garbage collector forcibly in
.NET?

Ans. Use the GC.SuppressFinalize()
method.

Q77. What is the use of the dispose() method
in .NET?

Ans. The Dispose method in .NET belongs to
IDisposable interface and it is best used to release unmanaged
objects like File objects, Windows API objects, Database
connection objects, COM objects etc from the memory. Its
performance is better than the finalize()
method.

Q78. Is it possible to have have different
access modifiers on the get and set methods of a property in
.NET?

Ans. No we can not have different modifiers of a
common property, which means that if the access modifier of a
property's get method is protected, and it must be protected
for the set method as well.

Q79. In .NET, is it
possible for two catch blocks to be executed in one
go?

Ans. This is NOT possible because once the correct
catch block is executed then the code flow goes to the finally
block.

Q80. Is there any difference between
System.String and System.StringBuilder classes?

Ans.
System.String is immutable by nature whereas
System.StringBuilder can have a mutable string in which plenty
of processes may be performed.

Q81. What technique is used to figure out that
the page request is a postback?

Ans. The IsPostBack
property of the page object may be used to check whether the
page request is a postback or not. IsPostBack property is of
the type Boolean.

Q82. Which event of the ASP.NET
page life cycle completely loads all the controls on the web
page?

Ans. The Page_load event of the ASP.NET page life
cycle assures that all controls are completely loaded. Even
though the controls are also accessible in Page_Init event but
here, the viewstate is incomplete.

Q83. How is
ViewState information persisted across postbacks in an ASP.NET
webpage?

Ans. Using HTML Hidden Fields, ASP.NET creates
a hidden field with an ID="__VIEWSTATE" and the value of the
page's viewstate is encoded (hashed) for
security.

Q84. What is the ValidationSummary control
in ASP.NET used for?

Ans. The ValidationSummary control
in ASP.NET displays summary of all the current validation
errors.

Q85. What is AutoPostBack feature in
ASP.NET?

Ans. In case it is required for a server side
control to postback when any of its event is triggered, then
the AutoPostBack property of this control is set to
true.

Q86. What is the difference between Web.config
and Machine.Config in .NET?

Ans. Web.config file is
used to make the settings to a web application, whereas
Machine.config file is used to make settings to all ASP.NET
applications on a server(the server machine).

Q87.
What is the difference between a session object and an
application object?

Ans. A session object can persist
information between HTTP requests for a particular user,
whereas an application object can be used globally for all the
users.

Q88. Which control has a faster performance,
Repeater or Datalist?

Ans. Repeater.

Q89.
Which control has a faster performance, Datagrid or
Datalist?

Ans. Datalist.

Q90. How to we add
customized columns in a Gridview in ASP.NET?

Ans. Make
use of the TemplateField column.

Q91. Is it possible
to stop the clientside validation of an entire
page?

Ans. Set Page.Validate = false;

Q92. Is
it possible to disable client side script in
validators?

Ans. Yes. simply EnableClientScript =
false.

Q93. How do we enable tracing in .NET
applications?

Ans. <%@ Page Trace="true"
%>

Q94. How to kill a user session in
ASP.NET?

Ans. Use the Session.abandon()
method.

Q95. Is it possible to perform forms
authentication with cookies disabled on a browser?

Ans.
Yes, it is possible.

Q96. What are the steps to use
a checkbox in a gridview?

Ans.
<ItemTemplate>
<asp:CheckBox id="CheckBox1"
runat="server" AutoPostBack="True"

OnCheckedChanged="Check_Clicked"></asp:CheckBox>
</ItemTemplate>

Q97.
What are design patterns in .NET?

Ans. A Design pattern
is a repeatitive solution to a repeatitive problem in the
design of a software architecture.

Q98. What is
difference between dataset and datareader in
ADO.NET?

Ans. A DataReader provides a forward-only and
read-only access to data, while the DataSet object can carry
more than one table and at the same time hold the
relationships between the tables. Also note that a DataReader
is used in a connected architecture whereas a Dataset is used
in a disconnected architecture.

Q99. Can connection
strings be stored in web.config?

Ans. Yes, in fact this
is the best place to store the connection string information.


Q100. Whats the difference between web.config and
app.config?

Ans. Web.config is used for web based
asp.net applications whereas app.config is used for windows
based applications.

Sunday, December 28, 2008

ADO.NET Overview

ADO.NET is an evolution of the ADO data access model that directly addresses user requirements for developing scalable applications. It was designed specifically for the web with scalability, statelessness, and XML in mind.

ADO.NET uses some ADO objects, such as the Connection and Command objects, and also introduces new objects. Key new ADO.NET objects include the DataSet, DataReader, and DataAdapter.

The important distinction between this evolved stage of ADO.NET and previous data architectures is that there exists an object -- the DataSet -- that is separate and distinct from any data stores. Because of that, the DataSet functions as a standalone entity. You can think of the DataSet as an always disconnected recordset that knows nothing about the source or destination of the data it contains. Inside a DataSet, much like in a database, there are tables, columns, relationships, constraints, views, and so forth.

A DataAdapter is the object that connects to the database to fill the DataSet. Then, it connects back to the database to update the data there, based on operations performed while the DataSet held the data. In the past, data processing has been primarily connection-based. Now, in an effort to make multi-tiered apps more efficient, data processing is turning to a message-based approach that revolves around chunks of information. At the center of this approach is the DataAdapter, which provides a bridge to retrieve and save data between a DataSet and its source data store. It accomplishes this by means of requests to the appropriate SQL commands made against the data store.

The XML-based DataSet object provides a consistent programming model that works with all models of data storage: flat, relational, and hierarchical. It does this by having no 'knowledge' of the source of its data, and by representing the data that it holds as collections and data types. No matter what the source of the data within the DataSet is, it is manipulated through the same set of standard APIs exposed through the DataSet and its subordinate objects.

While the DataSet has no knowledge of the source of its data, the managed provider has detailed and specific information. The role of the managed provider is to connect, fill, and persist the DataSet to and from data stores. The OLE DB and SQL Server .NET Data Providers (System.Data.OleDb and System.Data.SqlClient) that are part of the .Net Framework provide four basic objects: the Command, Connection, DataReader and DataAdapter. In the remaining sections of this document, we'll walk through each part of the DataSet and the OLE DB/SQL Server .NET Data Providers explaining what they are, and how to program against them.

The following sections will introduce you to some objects that have evolved, and some that are new. These objects are:
Connections. For connection to and managing transactions against a database.
Commands. For issuing SQL commands against a database.
DataReaders. For reading a forward-only stream of data records from a SQL Server data source.
DataSets. For storing, remoting and programming against flat data, XML data and relational data.
DataAdapters. For pushing data into a DataSet, and reconciling data against a database.


Note When dealing with connections to a database, there are two different options: SQL Server .NET Data Provider (System.Data.SqlClient) and OLE DB .NET Data Provider (System.Data.OleDb). In these samples we will use the SQL Server .NET Data Provider. These are written to talk directly to Microsoft SQL Server. The OLE DB .NET Data Provider is used to talk to any OLE DB provider (as it uses OLE DB underneath).
Connections

Connections are used to 'talk to' databases, and are respresented by provider-specific classes such as SQLConnection. Commands travel over connections and resultsets are returned in the form of streams which can be read by a DataReader object, or pushed into a DataSet object.

The example below shows how to create a connection object. Connections can be opened explicitly by calling the Open method on the connection, or will be opened implicitly when using a DataAdapter.






Commands

Commands contain the information that is submitted to a database, and are represented by provider-specific classes such as SQLCommand. A command can be a stored procedure call, an UPDATE statement, or a statement that returns results. You can also use input and output parameters, and return values as part of your command syntax. The example below shows how to issue an INSERT statement against the Northwind database.





DataReaders

The DataReader object is somewhat synonymous with a read-only/forward-only cursor over data. The DataReader API supports flat as well as hierarchical data. A DataReader object is returned after executing a command against a database. The format of the returned DataReader object is different from a recordset.For example, you might use the DataReader to show the results of a search list in a web page.


C# AdoOverview3.aspx



DataSets and DataAdapters

DataSets
The DataSet object is similar to the ADO Recordset object, but more powerful, and with one other important distinction: the DataSet is always disconnected. The DataSet object represents a cache of data, with database-like structures such as tables, columns, relationships, and constraints. However, though a DataSet can and does behave much like a database, it is important to remember that DataSet objects do not interact directly with databases, or other source data. This allows the developer to work with a programming model that is always consistent, regardless of where the source data resides. Data coming from a database, an XML file, from code, or user input can all be placed into DataSet objects. Then, as changes are made to the DataSet they can be tracked and verified before updating the source data. The GetChanges method of the DataSet object actually creates a second DatSet that contains only the changes to the data. This DataSet is then used by a DataAdapter (or other objects) to update the original data source.

The DataSet has many XML characteristics, including the ability to produce and consume XML data and XML schemas. XML schemas can be used to describe schemas interchanged via XML Web services. In fact, a DataSet with a schema can actually be compiled for type safety and statement completion.

DataAdapters (OLEDB/SQL)
The DataAdapter object works as a bridge between the DataSet and the source data. Using the provider-specific SqlDataAdapter (along with its associated SqlCommand and SqlConnection) can increase overall performance when working with a Microsoft SQL Server databases. For other OLE DB-supported databases, you would use the OleDbDataAdapter object and its associated OleDbCommand and OleDbConnection objects.

The DataAdapter object uses commands to update the data source after changes have been made to the DataSet. Using the Fill method of the DataAdapter calls the SELECT command; using the Update method calls the INSERT, UPDATE or DELETE command for each changed row. You can explicitly set these commands in order to control the statements used at runtime to resolve changes, including the use of stored procedures. For ad-hoc scenarios, a CommandBuilder object can generate these at run-time based upon a select statement. However, this run-time generation requires an extra round-trip to the server in order to gather required metadata, so explicitly providing the INSERT, UPDATE, and DELETE commands at design time will result in better run-time performance.

C# VB C++


SqlConnection myConnection = new SqlConnection("server=(local)\SQLExpress;Integrated Security=SSPI;database=northwind");
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter("select * from customers", myConnection);

mySqlDataAdapter.InsertCommand.CommandText = "sp_InsertCustomer";
mySqlDataAdapter.InsertCommand.CommandType = CommandType.StoredProcedure;
mySqlDataAdapter.DeleteCommand.CommandText = "sp_DeleteCustomer";
mySqlDataAdapter.DeleteCommand.CommandType = CommandType.StoredProcedure;
mySqlDataAdapter.UpdateCommand.CommandText = "sp_UpdateCustomers";
mySqlDataAdapter.UpdateCommand.CommandType = CommandType.StoredProcedure;


Dim myConnection As SqlConnection = New SqlConnection("server=(local)\SQLExpress;Integrated Security=SSPI;database=northwind")
Dim mySqlDataAdapter As SqlDataAdapter = New SqlDataAdapter("select * from customers", myConnection)

mySqlDataAdapter.InsertCommand.CommandText = "sp_InsertCustomer"
mySqlDataAdapter.InsertCommand.CommandType = CommandType.StoredProcedure
mySqlDataAdapter.DeleteCommand.CommandText = "sp_DeleteCustomer"
mySqlDataAdapter.DeleteCommand.CommandType = CommandType.StoredProcedure
mySqlDataAdapter.UpdateCommand.CommandText = "sp_UpdateCustomers"
mySqlDataAdapter.UpdateCommand.CommandType = CommandType.StoredProcedure


SqlConnection * myConnection = new SqlConnection("server=(local)\SQLExpress;Integrated Security=SSPI;database=northwind");
SqlDataAdapter * mySqlDataAdapter = new SqlDataAdapter("select * from customers", myConnection);

mySqlDataAdapter->InsertCommand->CommandText = "sp_InsertCustomer";
mySqlDataAdapter->InsertCommand->CommandType = CommandType.StoredProcedure;
mySqlDataAdapter->DeleteCommand->CommandText = "sp_DeleteCustomer";
mySqlDataAdapter->DeleteCommand->CommandType = CommandType.StoredProcedure;
mySqlDataAdapter->UpdateCommand->CommandText = "sp_UpdateCustomers";
mySqlDataAdapter->UpdateCommand->CommandType = CommandType.StoredProcedure;



C# VB C++

mySqlDataAdapter.Update(myDataSet);

mySqlDataAdapter.Update(myDataSet)

mySqlDataAdapter->Update(myDataSet);



The records are appropriately mapped to the given commands accordingly.


Figure: DataAdapters and DataSets

The sample below illustrates loading a DataAdapter via a SELECT statement. Then it updates, deletes and adds some records within the DataSet. Finally, it returns those updates to the source database via the DataAdapter. The constructed DeleteCommand, InsertCommand and UpdateCommand are shown in the page. It also illustrates using multiple DataAdapter objects to load multiple tables (Customers and Orders) into the DataSet.




Section Summary

ADO.NET is the next evolution of ADO for the .Net Framework.
ADO.NET was created with n-Tier, statelessness and XML in the forefront. Two new objects, the DataSet and DataAdapter, are provided for these scenarios.
ADO.NET can be used to get data from a stream, or to store data in a cache for updates.
There is a lot more information about ADO.NET in the documentation.
Remember, you can execute a command directly against the database in order to do inserts, updates, and deletes. You don't need to first put data into a DataSet in order to insert, update, or delete it.
Also, you can use a DataSet to bind to the data, move through the data, and navigate data relationships.

How to Encrypt and Decrypt a file?

The CryptoStream class in the System.Security.Cryptography namespace is used to easily define cryptographic transforms on any data stream. The constructor is defined as the following: CryptoStream (Stream argument, ICryptoTransform transform, CryptoStreamMode mode).

Stream argument - Defines the stream on which the cryptographic transform is to be performed. Any stream that derives from System.IO.Stream can be plugged in here. For example, pass in an instance of System.IO.FileStream to perform a cryptographic transform on a file. Because CryptoStream derives from Stream, it is possible to use CryptoStream to define cryptographic transforms on other cryptographic streams. This makes it possible to chain objects that implement CryptoStream together, for example encrypting a file and computing the hash for the encryption in a single operation.

ICrypto Transformtransform - Defines the cryptographic transform that is to be performed on the stream. Because every class that derives from HashAlgorithm implements the ICryptoTransform interface, an instance of a hash algorithm can be passed in here to take the hash of a stream. All symmetric encryption or decryption algorithms that derive from the SymmetricAlgorithm class have CreateEncryptor() and CreateDecryptor() functions that return an instance of an ICryptoTransform implementation. To define a TripleDES encryption on a given stream, call the CreateEncryptor() function on an instance of a TripleDES implementation and pass the result into the CryptoStream constructor. Generally, any class that implements ICryptoTransform can be passed into the CryptoStream constructor.

CryptoStreamMode mode - Defines whether you are reading from or writing to the stream. To write to a CryptoStream you must pass CryptoStreamMode.Write into the CryptoStream constructor. To read from the stream, CryptoStreamMode.Read must be passed into the constructor.

The CryptoStream class contains the standard stream member functions to either read a byte array from the stream or write a byte array to the stream. The CryptoStream class handles the buffering internally when reading from or writing to the stream. Application code needs only to provide the byte buffer and call the appropriate read or write method on the stream.

The following sample code shows the creation of a CryptoStream to encrypt a file using the DES algorithm. First, the FileStream that will contain the encrypted file is created. Then, an instance of a DES implementation is created. If an instance of a symmetric or asymmetric algorithm is created without explicit constructor arguments, a random key (or public or private key pair) is generated and default properties are set that cover most encryption or decryption scenarios. A DES encryptor object is created on the DES instance. Next, a CryptoStream is created by passing the FileStream instance and the DES encryptor into the CryptoStream constructor; the stream is set to write mode. Finally, we write a byte array of plain text to the stream and close the stream. The result is a file named "EncryptedFile.txt" which contains the DES encryption of bytearrayinput.

C#
FileStream fs = new FileStream("EncryptedFile.txt",FileMode.Create,FileAccess.Write);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
ICryptoTransform desencrypt = des.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fs,desencrypt,CryptoStreamMode.Write);
cryptostream.Write(bytearrayinput,0,bytearrayinput.Length);
cryptostream.Close();

VB

Dim fs As New FileStream("EncryptedFile.txt", FileMode.Create, FileAccess.Write)
Dim des As New DESCryptoServiceProvider()
Dim desencrypt As ICryptoTransform = des.CreateEncryptor()
Dim cryptostream As New CryptoStream(fs, desencrypt, CryptoStreamMode.Write)
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Close()

Friday, December 26, 2008

Silverlight Features

Feature Count Comments
Web camera and/or microphone input 33 Includes requests for just microphone as well
Bitmap APIs 26 Support get/set pixels and/or rendering a XAML scene to a bitmap.
Full 3D 24 Full 3D support (full 3D models)
Printing 20 Printing APIs
Offline and/or out of browser support 16 Support running Silverlight when not online (or completely out of the browser)
Bi-directional text and/or complex script 9
UDP/P2P 9 UDP APIs generally for Peer to Peer support
Rich text support 8 Editing and display
Right mouse button 8 Ability to configure the right click
Text quality 8 Improved text quality
HTML Integration 7 Support HTML hosting (live HTML documents) and/or HTML translation
Interactive designer 7 Support an interactive designer in Visual Studio
Support more than BasicHttpBinding 7 Most common request is for WSHttpBinding
Improve Silverlight/WPF compatibility 6 Mostly feature requests for either Silverlight and/or WPF
More controls 6 Random/general requests
SaveFileDialog 6
Data and/or property triggers 5
Reporting services 5
Synchronous web service calls 5
ADO.NET DataSet/DataTable 4
Alpha video 4 Chroma key support
Clipboard support 4
Drawing APIs (immediate mode) 4
Element name binding 4
Improved DataGrid 4 Several different requests
Local relational database (SQL) 4
Modal dialog 4
Mouse wheel 4 API and support in existing controls
Selectable text 4
Assembly caching 3 Want a framework for downloading/managing assemblies
Credentials/auth 3 Requests for networking stack and ASP.NET type integration
Custom markup extensions 3
Multi-target DLLs for .NET/SL 3 Build a business object DLL once for both .NET and Silverlight
Multi-touch support 3
Path Animation 3
Speech and better audio decoder 3
VisualBrush 3
9 Grid 2
Better keyboard APIs 2 Platform independent keycode
Better SEO 2
Binding support to anonymous types 2
Direct database access 2 OLEDB/ODBC equivalent
Flow panel 2
GIF support 2
Global/dynamic styles (skinning) 2
Integrated CTRL+F (in page search) 2
Sound APIs (equalizer) 2 Includes looping
TileBrush (Image Tiling) 2
XPS Support 2
64-bit platform support 1
Android support 1
Better N-tier support 1 Improved data access
Better SharePoint integration 1
Block style text 1 Bulleted lists, paragraphs
Cell based animation 1
CollectionView 1
Color management 1
Digital/XAP signing 1
Double Click event 1
Drag and Drop 1 Between the desktop and Silverlight
Full 5.1 sound 1 Currently fold down to stereo
IDataErrorInfo 1
Inverse kinematics (bones) 1 Flash 10 feature
MediaTimeline 1
Multi-binding 1
Navigation model 1 Includes browser history integration
Validation controls 1
XPATH support for data binding 1

Silverlight Features

Feature Count Comments
Web camera and/or microphone input 33 Includes requests for just microphone as well
Bitmap APIs 26 Support get/set pixels and/or rendering a XAML scene to a bitmap.
Full 3D 24 Full 3D support (full 3D models)
Printing 20 Printing APIs
Offline and/or out of browser support 16 Support running Silverlight when not online (or completely out of the browser)
Bi-directional text and/or complex script 9
UDP/P2P 9 UDP APIs generally for Peer to Peer support
Rich text support 8 Editing and display
Right mouse button 8 Ability to configure the right click
Text quality 8 Improved text quality
HTML Integration 7 Support HTML hosting (live HTML documents) and/or HTML translation
Interactive designer 7 Support an interactive designer in Visual Studio
Support more than BasicHttpBinding 7 Most common request is for WSHttpBinding
Improve Silverlight/WPF compatibility 6 Mostly feature requests for either Silverlight and/or WPF
More controls 6 Random/general requests
SaveFileDialog 6
Data and/or property triggers 5
Reporting services 5
Synchronous web service calls 5
ADO.NET DataSet/DataTable 4
Alpha video 4 Chroma key support
Clipboard support 4
Drawing APIs (immediate mode) 4
Element name binding 4
Improved DataGrid 4 Several different requests
Local relational database (SQL) 4
Modal dialog 4
Mouse wheel 4 API and support in existing controls
Selectable text 4
Assembly caching 3 Want a framework for downloading/managing assemblies
Credentials/auth 3 Requests for networking stack and ASP.NET type integration
Custom markup extensions 3
Multi-target DLLs for .NET/SL 3 Build a business object DLL once for both .NET and Silverlight
Multi-touch support 3
Path Animation 3
Speech and better audio decoder 3
VisualBrush 3
9 Grid 2
Better keyboard APIs 2 Platform independent keycode
Better SEO 2
Binding support to anonymous types 2
Direct database access 2 OLEDB/ODBC equivalent
Flow panel 2
GIF support 2
Global/dynamic styles (skinning) 2
Integrated CTRL+F (in page search) 2
Sound APIs (equalizer) 2 Includes looping
TileBrush (Image Tiling) 2
XPS Support 2
64-bit platform support 1
Android support 1
Better N-tier support 1 Improved data access
Better SharePoint integration 1
Block style text 1 Bulleted lists, paragraphs
Cell based animation 1
CollectionView 1
Color management 1
Digital/XAP signing 1
Double Click event 1
Drag and Drop 1 Between the desktop and Silverlight
Full 5.1 sound 1 Currently fold down to stereo
IDataErrorInfo 1
Inverse kinematics (bones) 1 Flash 10 feature
MediaTimeline 1
Multi-binding 1
Navigation model 1 Includes browser history integration
Validation controls 1
XPATH support for data binding 1

Wednesday, December 10, 2008

DotNet

.NET is Microsoft's Internet and Web strategy
.NET is NOT a operating system
.NET is a Internet and Web based infrastructure
.NET delivers software as Web Services
.NET is a framework for universal services
.NET is a server centric computing model
.NET will run in any browser on any platform
.NET is based on the newest Web standards

Tuesday, December 9, 2008

ASP .NET Security

Understanding Security
Authentication
Authorization
Users and Roles
Impersonation
Authentication
Determines the identity of the requesting entity
It answers the question “Who is this user?”
The entity presents credentials usually in the form of user id/Password
Authorization
For any identified entity, it determines the access rights to a resource
It answers the question “Do you have rights to this? If so, then what kind of rights?”
Usually managed through the operating system or a database
Users and Roles
Users are the entities that make the request to access resources
Roles are the “HATS” users wear once they are authenticated
Each entity has a single user profile, but can have multiple roles
Impersonation
Allows the ASP .Net application to take on the user’s identity when the request is passed to the application from IIS
Access is granted or denied based on the impersonated identity
Authentication
ASP .Net supports the following authentication providers:
Windows authentication
Form-based authentication
Passport authentication
Windows authentication
Define the security scheme in config.web
Validates user against every web request
Use Application_AuthenticateRequest() in global.asax to capture user info through Context.User.Identity object

Windows authentication
Advantages
OS based integrated policy management
Easy to manage complex security
More familiar to admins and developers
Disadvantages
OS dependent
Unable to secure URLs
Settings in config.web
Authenticate using windows
Deny all un-authorized users
Form-based authentication
Define the security scheme in config.web
Identify the resources (files, folders) to protect and create entries in config.web
Add proper users and roles to the protected resource entries
Specify a login form for users that can handle cookies
From-based authentication
Advantages
Does not require users specified in OS
Easy to implement and start
Disadvantages
Requires some coding
Settings in config.web
Authenticate using form-based (cookies)
Deny all un-authorized users
Passport authentication
Install Microsoft Passport SDK
Define the security scheme in config.web
Identify the resources (files, folders) to protect and create entries in config.web
Specify a “no rights” page for the app (redirecturl = “AccessDenied.aspx”)
Add code to inspect the User.Identity values
Passport authentication
Advantages
User Management and authorization is handled by someone else
Can be integrated with many other online services
You still get to control the policy details through config files and code
Disadvantages
Internet connected solutions
Only handles authentication
Settings in config.web
Authenticate using passport
Deny all un-authorized users
Authorization
ASP .Net can perform two types of authorization
File authorization
URL authorization
File authorization
Performed when Windows authentication is used
Does an ACL check to determine whether the user should have access
ACL (Access Control List) checks the resource itself for proper permissions
URL authorization
URL authorization checks configuration data store (config.web) in ASP .Net for proper permissions
Implements both positive and negative authorization assertions through and elements in
Allows us to control access to GET, POST and HEAD for each user/role
Setting up authorizations
Allow access to all except snoopy
Setting up authorizations
Allow everyone access to do a GET but only Snoopy and Admins can do a POST
Config.web ( settings)
Is there a Catch?ASP .Net configuration system only applies to ASP .Net resources; Those registered to be handled by xspisapi.dll
So, it does not provide authorization for TXT, GIF, JPG, ASP, HTML etc.
Can be fixed by mapping such files to xspisapi.dll
The problem – Possibility that there could be a performance impact
Review
Windows authentication
Uses ACL checks to authorize access to resources
Additionally, URL authorization can be specified in config.web
Form-based (cookie) authentication
Setup authentication in config.web and create a default login form
Uses authorization specified in config.web ONLY
Passport authentication
Download Passport SDK and setup config.web

Learning Design Patterns

• Informal Design Patterns—such as the use of standard code constructs, best practice, well structured code, common sense, the accepted approach, and evolution over time
• Formal Design Patterns—documented with sections such as "Context", "Problem", "Solution", and a UML diagram
Formal patterns usually have specific aims and solve specific issues, whereas informal patterns tend to provide guidance that is more general. As Brad Appleton, author of the book "Software Configuration Management Patterns: Effective Teamwork, Practical Integration", describes design patterns, pattern languages, and the need for them in software engineering and development:


Design patterns fall into several groups based on the type and aims of the pattern. For example, some patterns provide presentation logic for displaying specific views that make up the user interface. Others control the way that the application behaves as the user interacts with it. There are also groups of patterns that specify techniques for persisting data, define best practices for data access, and indicate optimum approaches for creating instances of objects that the application uses. The following list shows some of the most common design patterns within these groups:


Basic Design Patterns and Groups
Design patterns fall into several groups based on the type and aims of the pattern. For example, some patterns provide presentation logic for displaying specific views that make up the user interface. Others control the way that the application behaves as the user interacts with it. There are also groups of patterns that specify techniques for persisting data, define best practices for data access, and indicate optimum approaches for creating instances of objects that the application uses. The following list shows some of the most common design patterns within these groups:

• Presentation Logic
• Model-View-Controller (MVC)
• Model-View-Presenter (MVP)
• Use Case Controller
• Host or Behavioral
• Command
• Publish-Subscribe / Observer
• Plug-in / Module / Intercepting Filter
• Structural
• Service Agent / Proxy / Broker
• Provider / Adapter
• Creational
• Factory / Builder / Injection
• Singleton
• Persistence
• Repository
The Model-View-Controller and Model-View-Presenter Patterns
The Model-View-Controller (MVC) and Model-View-Presenter (MVP) patterns improve code reusability by separating the three components required to generate and manage a specific user interface (such as a single web page). The Model contains the data that the View (the web page) will display and allow the user to manipulate. The Controller or Presenter links the Model and the View, and manages all interaction and processing of the data in the Model (see Figure 1).

In the MVC pattern, user interaction with the View raises events in the Controller, which updates the Model. The Model then raises events to update the View. However, this introduces a dependency between the Model and the View. To avoid this, the MVP pattern uses a Presenter that both updates the Model and receives update events from it, using these updates to update the View. The MVP pattern improves testability, as all the logic and processing occurs within the Presenter, but it does add some complexity to the implementation because updates must pass from the Presenter to the View.


The Model-View-Controller and Model-View-Presenter Patterns: These patterns separate the data held by the Model from the View, linking them via a Controller or Presenter.


The Provider and Adapter Patterns
The Provider and Adapter patterns allow otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the other. In more practical terms, these patterns provide separation between components that allows behavioral changes to occur without prior knowledge of requirements. The application and any data sources it uses, outputs it generates, or classes it must interact with, can be created independently yet still work together (see Figure 2).

The Provider pattern separates source data from data processing objects and the application. It allows application code to be independent of the data source type and data format. A Provider component or service exposes standard methods that the application can call to read and write data. Internally, it converts these calls to the equivalents that match the data source, letting the application work with any source data type (such as any kind of database, XML document, disk file, or data repository) for which a suitable provider is available.

The Adapter pattern has the same advantages, and works in a similar way. Often, the target of an Adapter is some kind of output. For example, a printer driver is an example of an Adapter. ASP.NET itself, and other frameworks such as Enterprise Library, make widespread use of the Provider and Adapter patterns.



The Provider and Adapter Patterns: These patterns provide ways for otherwise incompatible components to interact.



The Service Agent, Proxy, and Broker Patterns
Various patterns exist that remove dependencies between a client and a service by using intermediate brokers. There are many different implementations of the basic pattern, some of which use an extra service-agent logic component to connect the client with the local proxy or gateway interface (see Figure 3).

The aim of all these patterns is to allow remote connection to, and use of, a service without the client having to know how the service works. The service exposes a contract that defines its interface, such as a Web Service Description Language (WSDL) document for a Web service. A client-side proxy or gateway interface uses the contract to create a suitably formatted request, and passes this to the service interface. The service sends the formatted response back through its gateway interface to the client proxy, which exposes it to the client. In effect, the client just calls the service methods on the client proxy, which returns the results just as if the service itself were a local component.

In the Service Agent pattern, an extra component on the client can perform additional processing and logic operations to further separate the client from the remote service. For example, the Service Agent may perform service address lookup, manipulate or format the client data to match the proxy requirements, or carry out any other kind of processing requirements common to different clients that use the service.



The Service Agent, Proxy, and Broker Patterns: These patterns remove dependencies between a service and a client by using intermediate brokers.


The Repository Pattern
The Repository pattern virtualizes storage of entities in a persistent medium, such as in a database or XML file. For example, a repository may expose database table data as strongly typed Customer and Order objects rather than data sets or data rows. It effectively hides the storage implementation from the application code, and lets applications use a common set of methods without requiring knowledge of the storage mechanism or format. Often, the repository uses a series of providers to connect to the source data (see Figure 4).


The Repository Pattern
The Repository pattern virtualizes storage of entities in a persistent medium, such as in a database or XML file. For example, a repository may expose database table data as strongly typed Customer and Order objects rather than data sets or data rows. It effectively hides the storage implementation from the application code, and lets applications use a common set of methods without requiring knowledge of the storage mechanism or format. Often, the repository uses a series of providers to connect to the source data (see Figure 4).



The Repository Pattern: This pattern connects applications to data repositories, isolating the applications from having to know the storage mechanism or format.


The Singleton Pattern
The Singleton pattern defines the creation of a class for which only a single instance can exist. It is useful for exposing read-only data, and static methods that do not rely on instance data. Rather than creating an instance of the class each time, the application obtains a reference to an existing instance using a static method of the class that implements the Singleton pattern.

If this is the first call to the method that returns the instance, the Singleton creates an instance, populates it with any required data, and returns that instance. Subsequent calls to the method simply return this instance. The instance lifetime is that of the application domain—in ASP.NET this is usually the lifetime of the domain Application object.


Implementing the Basic Patterns in ASP.NET
The previous sections briefly describe five common and simple types of design pattern. While they are not generally explained in terms of ASP.NET, they are all applicable to ASP.NET and reasonably easy to implement. In fact, ASP.NET and the .NET Framework automatically implement several of them. Figure 5 shows schematically how these patterns relate to ASP.NET applications.



ASP.NET Design Patterns: The schematic shows how ASP.NET implements some basic design patterns.


ASP.NET and the Model-View-Presenter Pattern
The ASP.NET code-behind technology, which uses partial classes, provides a natural implementation of the MVP pattern. The code-behind file (the Presenter) contains all the logic and processing code, and populates the page (the View). Event handlers within the code-behind file handle events raised by controls or by the page itself to perform actions when a postback to the server occurs. To complete this pattern, the code-behind file can use a separate data access layer or component (the Model) to read from, write to, and expose the source data—usually accessed through built-in providers that are part of the .NET Framework.

For example, a page might use a separate class that exposes methods to read and update a database table. This class might use the SqlClient, OleDb, or another data provider to connect to the database and execute dynamic SQL queries or stored procedures. The code in the code-behind file uses this class to retrieve the data, and populates the controls defined in the ASPX file that generates the user interface. When the user interacts with controls in the page, perhaps changing values in the data, code in the code-behind file executes during the postback and uses the data access class to push the changes back into the database.


Figure 6. MVP Implementation: The View shown here (the Default.aspx HTML page) gets its data from the Presenter (the ASP.NET page), which collates and formats the data from the Model (the data access layer and database).
The sample application uses the code-behind model throughout, thereby implementing the MVP pattern on each page. The default page (Default.aspx) demonstrates the ASP.NET application of the MVP pattern by displaying a View that contains a series of controls that allow users to execute any of a range of functions that fetch and display data (see Figure 6).

Clicking one of the buttons causes a postback to the server and raises the event that corresponds to that button. For example, the interface component for the second button shown in Figure 6 is an ASP.NET Button control, declared within the View (the ASPX page), which initiates an event handler named btn_CustModel_Click in the Presenter (the code-behind file) to handle the Click event:
Text="   "
OnClick="btn_CustModel_Click" />
Get name for customer
Text="ALFKI" Columns="3" />
from CustomerModel


The Presenter (the code-behind file) contains the declaration of the btn_CustModel_Click method, which creates an instance of the Model (a class file named CustomerModel.cs in the App_Code folder) and calls one of its methods to get the name of the customer identified by the customer ID users enter into the text box next to that button:
protected void btn_CustModel_Click(object sender, EventArgs e)
// display the name of the specified customer
{
try
{
// use method of the CustomerModel class
CustomerModel customers = new CustomerModel();
Label1.Text += "Customer Name from CustomerModel class: ";
Label1.Text += customers.GetCustomerName(
txtID_CustModel.Text);
}
catch (Exception ex)
{
Label1.Text += "PAGE ERROR: " + ex.Message;
}
Label1.Text += "

";
}
You can view the contents of the files Default.aspx (the View), Default.aspx.cs (the Presenter), and CustomerModel.cs (the Model) that implement the MVP pattern in this example to see all the UI control declarations and code they contain. As you saw in Figure 6, there are buttons to execute a range of CustomerModel methods, as well as methods of the Repository, Web Reference, and Service Agent implementations discussed in the following sections.
Notice that the Default.aspx page (see Figure 6) contains a drop-down list where you can select a page or view you want to see. The application loads the selected page using an implementation of the Front Controller pattern, described in more detail in the next article in this series. For now, it's sufficient to explain that you can use the drop-down list to navigate to other pages to see the examples, such as the Use Case Controller example page or the Publish-Subscribe example page.

ASP.NET and the Provider Pattern
ASP.NET uses the Provider pattern in a number of places. These include providers for the Membership and Role Management system (such as the SqlMembershipProvider and SqlRoleProvider), the Site Navigation system (the XmlSiteMapProvider), and the user profile management system (such as the SqlProfileProvider). The various data access components provided with ASP.NET, such as the SqlDataSource, also rely on providers. These providers are part of the .NET Framework data-access namespaces, and include SqlClient, OleDb, Odbc, and OracleClient.

Each provider is configured in the web.config file, with the default settings configured in the server's root web.config file. Developers can create their own providers based on an interface that defines the requirements, or by inheriting from a base class containing common functionality for that type of provider. For example, developers can extend the DataSourceControl class to create their own data source controls that interface with a non-supported or custom data store.

ASP.NET and the Adapter Pattern
ASP.NET uses adapters to generate the output from server controls. By default, server controls use adapters such as the webControlAdapter or DataBoundControlAdapter to generate the markup (such as HTML) and other content output by the control. Each adapter provides methods such as Render and CreateChildControls that the server controls call to create the appropriate output.

Alternative adapters are available, for example the CSS Friendly Control Adapters provide more flexibility for customizing the rendered HTML. Developers can also create their own adapters to provide custom output from the built-in controls, or from custom controls.


Visual Studio and the Service Agent and Proxy Patterns
The Proxy and Broker patterns provide a natural technique for connecting to and using remote services without forcing the use of O/S or application-specific protocols such as DCOM. In particular, they are ideal for use with Web services. In Visual Studio, when developers add a Web Reference to a project, Visual Studio automatically collects the Web service description (including a WSDL contract file). This lets the code generate a suitable proxy class that exposes the methods of the remote service to code in the application. Code in the application can then use the remote service by creating an instance of the proxy class and calling the exposed methods defined in the contract. For example, here's the code used in the sample application to call the CustomerName method of the DemoService service:

protected void btn_WSProxy_Click(object sender, EventArgs e)
// display name of specified customer using the web service
{
try
{
// get details from web service
// use 'using' construct to ensure disposal after use
using (LocalDemoService.Service svc = new
LocalDemoService.Service())
{
Label1.Text += "Customer name from web service: "
+ svc.CustomerName(txtID_WSProxy.Text);
}
}
catch (Exception ex)
{
Label1.Text += "PAGE ERROR: " + ex.Message;
}
Label1.Text += "

";
}
One issue with using Web services is the difficulty in raising exceptions that the client can handle. The usual approach is to return a specific value that indicates the occurrence of an exception or failure. Therefore, one useful feature that a Service Agent (which wraps the Web Reference to add extra functionality) can offer is detecting exceptions by examining the returned value and raising a local exception to the calling code.

The following code, from the ServiceAgent.cs class in the sample application, contains a constructor that instantiates the local proxy for the service and stores a reference to it. Then the GetCustomerName method can call the CustomerName method of the Web service and examine the returned value. If the return value starts with the text "ERROR:" the code raises an exception that the calling routine can handle.

The GetCustomerName method also performs additional processing on the value submitted to it. The Web service only matches on a complete customer ID (five characters in the example), and supports partial matches only if the customer ID ends with a wildcard character. The GetCustomerName method in the Service Agent checks for partial customer ID values and adds the wildcard character so that the service will return a match on this partial value:
// wraps the Web Reference and calls to web service
// to perform auxiliary processing
public class ServiceAgent
{
LocalDemoService.Service svc = null;

public ServiceAgent()
{
// create instance of remote web service
try
{
svc = new LocalDemoService.Service();
}
catch (Exception ex)
{
throw new Exception(
"Cannot create instance of remote service", ex);
}
}

public String GetCustomerName(String custID)
{
// add '*' to customer ID if required
if (custID.Length < 5)
{
custID = String.Concat(custID, "*");
}
// call web service and raise a local exception
// if an error occurs (i.e. when the returned
// value string starts with "ERROR:")
String custName = svc.CustomerName(custID);
if (custName.Substring(0,6) == "ERROR:")
{
throw new Exception(
"Cannot retrieve customer name - " + custName);
}
return custName;
}
}
To use this simple example of a Service Agent, code in the Default.aspx page of the sample application instantiates the Service Agent class and calls its GetCustomerName method. It also traps any exception that the Service Agent might generate, displaying the message from the InnerException generated by the agent:
protected void btn_WSAgent_Click(object sender, EventArgs e)
// display name of specified customer using the Service Agent
// extra processing in Agent allows for match on partial ID
{
try
{
// get details from Service Agent
ServiceAgent agent = new ServiceAgent();
Label1.Text += "Customer name from Service Agent: "
+ agent.GetCustomerName(txtID_WSAgent.Text);
}
catch (Exception ex)
{
Label1.Text += "PAGE ERROR: " + ex.Message + "
";
if (ex.InnerException != null)
{
Label1.Text += "INNER EXCEPTION: " +
ex.InnerException.Message;
}
}
Label1.Text += "

";
}


Implementing the Repository Pattern
A data repository that implements the Repository pattern can provide dependency-free access to data of any type. For example, developers might create a class that reads user information from Active Directory, and exposes it as a series of User objects—each having properties such as Alias, EmailAddress, and PhoneNumber. The repository may also provide features to iterate over the contents, find individual users, and manipulate the contents.


Third-party tools are available to help developers build repositories, such as the CodeSmith tools library. Visual Studio includes the tools to generate a typed DataSet that can expose values as properties, rather than as data rows, and this can form the basis for building a repository.

As a simple example, the sample application uses a typed DataSet (CustomerRepository.xsd in the App_Code folder), which is populated from the Customers table in the Northwind database. The DataSet Designer in Visual Studio automatically implements the Fill and GetData methods within the class, and exposes objects for each customer (CustomersRow) and for the whole set of customers (CustomersDataTable).

The class CustomerRepositoryModel.cs in the App_Code folder exposes data from the typed DataSet, such as the GetCustomerList method that returns a populated CustomersDataTable instance, and the GetCustomerName method that takes a customer ID and returns that customer's name as a String:
public class CustomerRepositoryModel
{

public CustomerRepository.CustomersDataTable GetCustomerList()
{
// get details from CustomerRepository typed DataSet
try
{
CustomersTableAdapter adapter = new
CustomersTableAdapter();
return adapter.GetData();
}
catch (Exception ex)
{
throw new Exception(
"ERROR: Cannot access typed DataSet", ex);
}
}

public String GetCustomerName(String custID)
{
// get details from CustomerRepository typed DataSet
try
{
if (custID.Length < 5)
{
custID = String.Concat(custID, "*");
}
CustomerRepository.CustomersDataTable customers =
GetCustomerList();
// select row(s) for this customer ID
CustomerRepository.CustomersRow[] rows =
(CustomerRepository.CustomersRow[])customers.Select(
"CustomerID LIKE '" + custID + "'");
// return the value of the CompanyName property
return rows[0].CompanyName;
}
catch (Exception ex)
{
throw new Exception(
"ERROR: Cannot access typed DataSet", ex);
}
}
}
Implementing the Singleton Pattern
The sample application uses the Front Controller pattern to allow users to specify the required View using a short and memorable name. The Front Controller, described in detail in a later section, relies on an XML file that maps the visible short and memorable names to the actual URLs for this view. To expose the XML document's content to the Front Controller code, the application uses a Singleton instance of the class named TransferUrlList.cs (in the App_Code folder).

This approach provides good performance, because the class is loaded at all times and the Front Controller has only to call a static method to get a reference to the single instance, then call the method that translates the memorable name into a URL.

To implement the Singleton pattern, the class contains a private default constructor (a constructor that takes no parameters), which prevents the compiler from adding a default public constructor. This also prevents any classes or code from calling the constructor to create an instance.

The TransferUrlList class also contains a static method that returns the single instance, creating and populating it from the XML file if there is no current instance. The class uses static local variables to store a reference to the instance, and—in this example—to hold a StringDictionary containing the list of URLs loaded from the XML file:
// Singleton class to expose a list of URLs for
// Front Controller to use to transfer to when
// special strings occur in requested URL
public class TransferUrlList
{
private static TransferUrlList instance = null;
private static StringDictionary urls;

private TransferUrlList()
// prevent code using the default constructor by
// making the construtor private
{ }

public static TransferUrlList GetInstance()
// public static method to return single instance of class
{
// see if instance already created
if (instance == null)
{
// create the instance
instance = new TransferUrlList();
urls = new StringDictionary();
String xmlFilePath = HttpContext.Current.Request.MapPath(
@"~/xmldata/TransferURLs.xml");
// read list of transfer URLs from XML file
try
{
using (XmlReader reader =
XmlReader.Create(xmlFilePath))
{
while (reader.Read())
{
if (reader.LocalName == "item")
{
// populate StringDictionary
urls.Add(reader.GetAttribute("name"),
reader.GetAttribute("url"));
}
}
}
}
catch (Exception ex)
{
throw new Exception(
"Cannot load URL transfer list", ex);
}
}
return instance;
}
...
}
A StringDictionary provides good performance, as the method that searches for a matching name and URL in the list can use the ContainsKey method, and then access the matching value using an indexer. If there is no match, the code returns the original value without translating it. The following code shows the GetTransferUrl method that performs the URL translation:
public String GetTransferUrl(String urlPathName)
// public method to return URL for a specified name
// returns original URL if not found
{
if (urls.ContainsKey(urlPathName))
{
return urls[urlPathName];
}
else
{
return urlPathName;
}
}
To use the TransferUrlList Singleton class, code in the Front Controller just has to get a reference to the instance, and then call the GetTransferUrl method with the URL to translate as the value of the single parameter:
...
// get Singleton list of transfer URLs
TransferUrlList urlList = TransferUrlList.GetInstance();
// see if target value matches a transfer URL
// by querying the list of transfer URLs
// method returns the original value if no match
String transferTo = urlList.GetTransferUrl(reqTarget);
...
That completes this installment. Part 2 will discuss Controller Patterns for ASP.NET.




Sharing Code Between Pages
Although you can place code inside each page within your site (using the inline or code-behind separation models described in the previous section), there are times when you will want to share code across several pages in your site. It would be inefficient and difficult to maintain this code by copying it to every page that needs it. Fortunately, ASP.NET provides several convenient ways to make code accessible to all pages in an application.
The Code Directory New in 2.0
Just as pages can be compiled dynamically at runtime, so can arbitrary code files (for example .cs or .vb files). ASP.NET 2.0 introduces the App_Code directory, which can contain standalone files that contain code to be shared across several pages in your application. Unlike ASP.NET 1.x, which required these files to be precompiled to the Bin directory, any code files in the App_Code directory will be dynamically compiled at runtime and made available to the application. It is possible to place files of more than one language under the App_Code directory, provided they are partitioned in subdirectories (registered with a particular language in Web.config). The example below demonstrates using the App_Code directory to contain a single class file called from the page.
VB App_Code Folder Example


By default, the App_Code directory can only contain files of the same language. However, you may partition the App_Code directory into subdirectories (each containing files of the same language) in order to contain multiple languages under the App_Code directory. To do this, you need to register each subdirectory in the Web.config file for the application.









The following example demonstrates an App_Code directory partitioned to contain files in both the VB and C# languages.
VB Partitioned App_Code Folder Example

The Bin Directory
Supported in ASP.NET version 1, the Bin directory is like the Code directory, except it can contain precompiled assemblies. This is useful when you need to use code that is possibly written by someone other than yourself, where you don't have access to the source code (VB or C# file) but you have a compiled DLL instead. Simply place the assembly in the Bin directory to make it available to your site. By default, all assemblies in the Bin directory are automatically loaded in the app and made accessible to pages. You may need to Import specific namespaces from assemblies in the Bin directory using the @Import directive at the top of the page.
<@ Import Namespace="MyCustomNamespace" >
The Global Assembly Cache
The .NET Framework 2.0 includes a number of assemblies that represent the various parts of the Framework. These assemblies are stored in the global assembly cache, which is a versioned repository of assemblies made available to all applications on the machine (not just a specific application, as is the case with Bin and App_Code). Several assemblies in the Framework are automatically made available to ASP.NET applications. You can register additional assemblies by registration in a Web.config file in your application.







Note that you still need to use an @Import directive to make the namespaces in these assemblies available to individual pages.

C# Coding Standards and Best Programming Practices

1. Introduction

Anybody can write code. With a few months of programming experience, you can write 'working applications'. Making it work is easy, but doing it the right way requires more work, than just making it work.

Believe it, majority of the programmers write 'working code', but not ‘good code'. Writing 'good code' is an art and you must learn and practice it.

Everyone may have different definitions for the term ‘good code’. In my definition, the following are the characteristics of good code.

• Reliable
• Maintainable
• Efficient

Most of the developers are inclined towards writing code for higher performance, compromising reliability and maintainability. But considering the long term ROI (Return On Investment), efficiency and performance comes below reliability and maintainability. If your code is not reliable and maintainable, you (and your company) will be spending lot of time to identify issues, trying to understand code etc throughout the life of your application.

2. Purpose of coding standards and best practices

To develop reliable and maintainable applications, you must follow coding standards and best practices.

The naming conventions, coding standards and best practices described in this document are compiled from our own experience and by referring to various Microsoft and non Microsoft guidelines.

There are several standards exists in the programming industry. None of them are wrong or bad and you may follow any of them. What is more important is, selecting one standard approach and ensuring that everyone is following it.

3. How to follow the standards across the team

If you have a team of different skills and tastes, you are going to have a tough time convincing everyone to follow the same standards. The best approach is to have a team meeting and developing your own standards document. You may use this document as a template to prepare your own document.

Distribute a copy of this document (or your own coding standard document) well ahead of the coding standards meeting. All members should come to the meeting prepared to discuss pros and cons of the various points in the document. Make sure you have a manager present in the meeting to resolve conflicts.

Discuss all points in the document. Everyone may have a different opinion about each point, but at the end of the discussion, all members must agree upon the standard you are going to follow. Prepare a new standards document with appropriate changes based on the suggestions from all of the team members. Print copies of it and post it in all workstations.

After you start the development, you must schedule code review meetings to ensure that everyone is following the rules. 3 types of code reviews are recommended:

1. Peer review – another team member review the code to ensure that the code follows the coding standards and meets requirements. This level of review can include some unit testing also. Every file in the project must go through this process.
2. Architect review – the architect of the team must review the core modules of the project to ensure that they adhere to the design and there is no “big” mistakes that can affect the project in the long run.
3. Group review – randomly select one or more files and conduct a group review once in a week. Distribute a printed copy of the files to all team members 30 minutes before the meeting. Let them read and come up with points for discussion. In the group review meeting, use a projector to display the file content in the screen. Go through every sections of the code and let every member give their suggestions on how could that piece of code can be written in a better way. (Don’t forget to appreciate the developer for the good work and also make sure he does not get offended by the “group attack”!)

4. Naming Conventions and Standards

Note :
The terms Pascal Casing and Camel Casing are used throughout this document.
Pascal Casing - First character of all words are Upper Case and other characters are lower case.
Example: BackColor
Camel Casing - First character of all words, except the first word are Upper Case and other characters are lower case.
Example: backColor

1. Use Pascal casing for Class names

public class HelloWorld
{
...
}

2. Use Pascal casing for Method names

void SayHello(string name)
{
...
}


3. Use Camel casing for variables and method parameters

int totalCount = 0;
void SayHello(string name)
{
string fullMessage = "Hello " + name;
...
}

4. Use the prefix “I” with Camel Casing for interfaces ( Example: IEntity )

5. Do not use Hungarian notation to name variables.

In earlier days most of the programmers liked it - having the data type as a prefix for the variable name and using m_ as prefix for member variables. Eg:

string m_sName;
int nAge;

However, in .NET coding standards, this is not recommended. Usage of data type and m_ to represent member variables should not be used. All variables should use camel casing.

Some programmers still prefer to use the prefix m_ to represent member variables, since there is no other easy way to identify a member variable.


6. Use Meaningful, descriptive words to name variables. Do not use abbreviations.

Good:

string address
int salary

Not Good:

string nam
string addr
int sal

7. Do not use single character variable names like i, n, s etc. Use names like index, temp

One exception in this case would be variables used for iterations in loops:

for ( int i = 0; i < count; i++ )
{
...
}

If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.

8. Do not use underscores (_) for local variable names.

9. All member variables must be prefixed with underscore (_) so that they can be identified from other local variables.

10. Do not use variable names that resemble keywords.

11. Prefix boolean variables, properties and methods with “is” or similar prefixes.

Ex: private bool _isFinished

12. Namespace names should follow the standard pattern

...

13. Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables.

There are 2 different approaches recommended here.

a. Use a common prefix ( ui_ ) for all UI elements. This will help you group all of the UI elements together and easy to access all of them from the intellisense.

b. Use appropriate prefix for each of the ui element. A brief list is given below. Since .NET has given several controls, you may have to arrive at a complete list of standard prefixes for each of the controls (including third party controls) you are using.


Control Prefix
Label Lbl
TextBox Txt
DataGrid Dtg
Button Btn
ImageButton Imb
Hyperlink Hlk
DropDownList Ddl
ListBox Lst
DataList Dtl
Repeater Rep
Checkbox Chk
CheckBoxList Cbl
RadioButton Rdo
RadioButtonList Rbl
Image Img
Panel Pnl
PlaceHolder Phd
Table Tbl
Validators Val



14. File name should match with class name.

For example, for the class HelloWorld, the file name should be helloworld.cs (or, helloworld.vb)

15. Use Pascal Case for file names.



5. Indentation and Spacing

1. Use TAB for indentation. Do not use SPACES. Define the Tab size as 4.

2. Comments should be in the same level as the code (use the same level of indentation).

Good:

// Format a message and display

string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );

Not Good:

// Format a message and display
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );

3. Curly braces ( {} ) should be in the same level as the code outside the braces.


4. Use one blank line to separate logical groups of code.

Good:
bool SayHello ( string name )
{
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;

string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();

MessageBox.Show ( message );

if ( ... )
{
// Do something
// ...

return false;
}

return true;
}

Not Good:

bool SayHello (string name)
{
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
if ( ... )
{
// Do something
// ...
return false;
}
return true;
}

5. There should be one and only one single blank line between each method inside the class.

6. The curly braces should be on a separate line and not in the same line as if, for etc.

Good:
if ( ... )
{
// Do something
}

Not Good:

if ( ... ) {
// Do something
}

7. Use a single space before and after each operator and brackets.

Good:
if ( showResult == true )
{
for ( int i = 0; i < 10; i++ )
{
//
}
}

Not Good:

if(showResult==true)
{
for(int i= 0;i<10;i++)
{
//
}
}


8. Use #region to group related pieces of code together. If you use proper grouping using #region, the page should like this when all definitions are collapsed.



9. Keep private member variables, properties and methods in the top of the file and public members in the bottom.

6. Good Programming practices

1. Avoid writing very long methods. A method should typically have 1~25 lines of code. If a method has more than 25 lines of code, you must consider re factoring into separate methods.

2. Method name should tell what it does. Do not use mis-leading names. If the method name is obvious, there is no need of documentation explaining what the method does.

Good:
void SavePhoneNumber ( string phoneNumber )
{
// Save the phone number.
}

Not Good:

// This method will save the phone number.
void SaveDetails ( string phoneNumber )
{
// Save the phone number.
}

3. A method should do only 'one job'. Do not combine more than one job in a single method, even if those jobs are very small.

Good:
// Save the address.
SaveAddress ( address );

// Send an email to the supervisor to inform that the address is updated.
SendEmail ( address, email );

void SaveAddress ( string address )
{
// Save the address.
// ...
}

void SendEmail ( string address, string email )
{
// Send an email to inform the supervisor that the address is changed.
// ...
}

Not Good:

// Save address and send an email to the supervisor to inform that
// the address is updated.
SaveAddress ( address, email );

void SaveAddress ( string address, string email )
{
// Job 1.
// Save the address.
// ...

// Job 2.
// Send an email to inform the supervisor that the address is changed.
// ...
}

4. Use the c# or VB.NET specific types (aliases), rather than the types defined in System namespace.

int age; (not Int16)
string name; (not String)
object contactInfo; (not Object)


Some developers prefer to use types in Common Type System than language specific aliases.

5. Always watch for unexpected values. For example, if you are using a parameter with 2 possible values, never assume that if one is not matching then the only possibility is the other value.

Good:

If ( memberType == eMemberTypes.Registered )
{
// Registered user… do something…
}
else if ( memberType == eMemberTypes.Guest )
{
// Guest user... do something…
}
else
{
// Un expected user type. Throw an exception
throw new Exception (“Un expected value “ + memberType.ToString() + “’.”)

// If we introduce a new user type in future, we can easily find
// the problem here.
}

Not Good:

If ( memberType == eMemberTypes.Registered )
{
// Registered user… do something…
}
else
{
// Guest user... do something…

// If we introduce another user type in future, this code will
// fail and will not be noticed.
}

6. Do not hardcode numbers. Use constants instead. Declare constant in the top of the file and use it in your code.

However, using constants are also not recommended. You should use the constants in the config file or database so that you can change it later. Declare them as constants only if you are sure this value will never need to be changed.

7. Do not hardcode strings. Use resource files.

8. Convert strings to lowercase or upper case before comparing. This will ensure the string will match even if the string being compared has a different case.

if ( name.ToLower() == “john” )
{
//…
}

9. Use String.Empty instead of “”

Good:

If ( name == String.Empty )
{
// do something
}

Not Good:

If ( name == “” )
{
// do something
}


10. Avoid using member variables. Declare local variables wherever necessary and pass it to other methods instead of sharing a member variable between methods. If you share a member variable between methods, it will be difficult to track which method changed the value and when.

11. Use enum wherever required. Do not use numbers or strings to indicate discrete values.

Good:
enum MailType
{
Html,
PlainText,
Attachment
}

void SendMail (string message, MailType mailType)
{
switch ( mailType )
{
case MailType.Html:
// Do something
break;
case MailType.PlainText:
// Do something
break;
case MailType.Attachment:
// Do something
break;
default:
// Do something
break;
}
}


Not Good:

void SendMail (string message, string mailType)
{
switch ( mailType )
{
case "Html":
// Do something
break;
case "PlainText":
// Do something
break;
case "Attachment":
// Do something
break;
default:
// Do something
break;
}
}
12. Do not make the member variables public or protected. Keep them private and expose public/protected Properties.

13. The event handler should not contain the code to perform the required action. Rather call another method from the event handler.

14. Do not programmatically click a button to execute the same action you have written in the button click event. Rather, call the same method which is called by the button click event handler.

15. Never hardcode a path or drive name in code. Get the application path programmatically and use relative path.

16. Never assume that your code will run from drive "C:". You may never know, some users may run it from network or from a "Z:".

17. In the application start up, do some kind of "self check" and ensure all required files and dependancies are available in the expected locations. Check for database connection in start up, if required. Give a friendly message to the user in case of any problems.

18. If the required configuration file is not found, application should be able to create one with default values.

19. If a wrong value found in the configuration file, application should throw an error or give a message and also should tell the user what are the correct values.

20. Error messages should help the user to solve the problem. Never give error messages like "Error in Application", "There is an error" etc. Instead give specific messages like "Failed to update database. Please make sure the login id and password are correct."

21. When displaying error messages, in addition to telling what is wrong, the message should also tell what should the user do to solve the problem. Instead of message like "Failed to update database.", suggest what should the user do: "Failed to update database. Please make sure the login id and password are correct."

22. Show short and friendly message to the user. But log the actual error with all possible information. This will help a lot in diagnosing problems.

23. Do not have more than one class in a single file.

24. Have your own templates for each of the file types in Visual Studio. You can include your company name, copy right information etc in the template. You can view or edit the Visual Studio file templates in the folder C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\ItemTemplatesCache\CSharp\1033. (This folder has the templates for C#, but you can easily find the corresponding folders or any other language)

25. Avoid having very large files. If a single file has more than 1000 lines of code, it is a good candidate for refactoring. Split them logically into two or more classes.

26. Avoid public methods and properties, unless they really need to be accessed from outside the class. Use “internal” if they are accessed only within the same assembly.

27. Avoid passing too many parameters to a method. If you have more than 4~5 parameters, it is a good candidate to define a class or structure.

28. If you have a method returning a collection, return an empty collection instead of null, if you have no data to return. For example, if you have a method returning an ArrayList, always return a valid ArrayList. If you have no items to return, then return a valid ArrayList with 0 items. This will make it easy for the calling application to just check for the “count” rather than doing an additional check for “null”.

29. Use the AssemblyInfo file to fill information like version number, description, company name, copyright notice etc.

30. Logically organize all your files within appropriate folders. Use 2 level folder hierarchies. You can have up to 10 folders in the root folder and each folder can have up to 5 sub folders. If you have too many folders than cannot be accommodated with the above mentioned 2 level hierarchy, you may need re factoring into multiple assemblies.

16. Make sure you have a good logging class which can be configured to log errors, warning or traces. If you configure to log errors, it should only log errors. But if you configure to log traces, it should record all (errors, warnings and trace). Your log class should be written such a way that in future you can change it easily to log to Windows Event Log, SQL Server, or Email to administrator or to a File etc without any change in any other part of the application. Use the log class extensively throughout the code to record errors, warning and even trace messages that can help you trouble shoot a problem.

17. If you are opening database connections, sockets, file stream etc, always close them in the finally block. This will ensure that even if an exception occurs after opening the connection, it will be safely closed in the finally block.

18. Declare variables as close as possible to where it is first used. Use one variable declaration per line.

19. Use StringBuilder class instead of String when you have to manipulate string objects in a loop. The String object works in weird way in .NET. Each time you append a string, it is actually discarding the old string object and recreating a new object, which is a relatively expensive operations.

Consider the following example:

public string ComposeMessage (string[] lines)
{
string message = String.Empty;

for (int i = 0; i < lines.Length; i++)
{
message += lines [i];
}

return message;
}

In the above example, it may look like we are just appending to the string object ‘message’. But what is happening in reality is, the string object is discarded in each iteration and recreated and appending the line to it.

If your loop has several iterations, then it is a good idea to use StringBuilder class instead of String object.

See the example where the String object is replaced with StringBuilder.

public string ComposeMessage (string[] lines)
{
StringBuilder message = new StringBuilder();

for (int i = 0; i < lines.Length; i++)
{
message.Append( lines[i] );
}

return message.ToString();
}


7. Architecture

1. Always use multi layer (N-Tier) architecture.

2. Never access database from the UI pages. Always have a data layer class which performs all the database related tasks. This will help you support or migrate to another database back end easily.

3. Use try-catch in your data layer to catch all database exceptions. This exception handler should record all exceptions from the database. The details recorded should include the name of the command being executed, stored proc name, parameters, connection string used etc. After recording the exception, it could be re thrown so that another layer in the application can catch it and take appropriate action.

4. Separate your application into multiple assemblies. Group all independent utility classes into a separate class library. All your database related files can be in another class library.

8. ASP.NET

1. Do not use session variables throughout the code. Use session variables only within the classes and expose methods to access the value stored in the session variables. A class can access the session using System.Web.HttpCOntext.Current.Session

2. Do not store large objects in session. Storing large objects in session may consume lot of server memory depending on the number of users.

3. Always use style sheet to control the look and feel of the pages. Never specify font name and font size in any of the pages. Use appropriate style class. This will help you to change the UI of your application easily in future. Also, if you like to support customizing the UI for each customer, it is just a matter of developing another style sheet for them

9. Comments

Good and meaningful comments make code more maintainable. However,

1. Do not write comments for every line of code and every variable declared.

2. Use // or /// for comments. Avoid using /* … */

3. Write comments wherever required. But good readable code will require very less comments. If all variables and method names are meaningful, that would make the code very readable and will not need many comments.

4. Do not write comments if the code is easily understandable without comment. The drawback of having lot of comments is, if you change the code and forget to change the comment, it will lead to more confusion.

5. Fewer lines of comments will make the code more elegant. But if the code is not clean/readable and there are less comments, that is worse.

6. If you have to use some complex or weird logic for any reason, document it very well with sufficient comments.

7. If you initialize a numeric variable to a special number other than 0, -1 etc, document the reason for choosing that value.

8. The bottom line is, write clean, readable code such a way that it doesn't need any comments to understand.

9. Perform spelling check on comments and also make sure proper grammar and punctuation is used.

10. Exception Handling

1. Never do a 'catch exception and do nothing'. If you hide an exception, you will never know if the exception happened or not. Lot of developers uses this handy method to ignore non significant errors. You should always try to avoid exceptions by checking all the error conditions programmatically. In any case, catching an exception and doing nothing is not allowed. In the worst case, you should log the exception and proceed.

2. In case of exceptions, give a friendly message to the user, but log the actual error with all possible details about the error, including the time it occurred, method and class name etc.

3. Always catch only the specific exception, not generic exception.

Good:


void ReadFromFile ( string fileName )
{
try
{
// read from file.
}
catch (FileIOException ex)
{
// log error.
// re-throw exception depending on your case.
throw;
}
}

Not Good:


void ReadFromFile ( string fileName )
{
try
{
// read from file.
}
catch (Exception ex)
{
// Catching general exception is bad... we will never know whether
// it was a file error or some other error.
// Here you are hiding an exception.
// In this case no one will ever know that an exception happened.

return "";
}
}


4. No need to catch the general exception in all your methods. Leave it open and let the application crash. This will help you find most of the errors during development cycle. You can have an application level (thread level) error handler where you can handle all general exceptions. In case of an 'unexpected general error', this error handler should catch the exception and should log the error in addition to giving a friendly message to the user before closing the application, or allowing the user to 'ignore and proceed'.

5. When you re throw an exception, use the throw statement without specifying the original exception. This way, the original call stack is preserved.

Good:

catch
{
// do whatever you want to handle the exception

throw;
}

Not Good:

catch (Exception ex)
{
// do whatever you want to handle the exception

throw ex;
}

6. Do not write try-catch in all your methods. Use it only if there is a possibility that a specific exception may occur and it cannot be prevented by any other means. For example, if you want to insert a record if it does not already exists in database, you should try to select record using the key. Some developers try to insert a record without checking if it already exists. If an exception occurs, they will assume that the record already exists. This is strictly not allowed. You should always explicitly check for errors rather than waiting for exceptions to occur. On the other hand, you should always use exception handlers while you communicate with external systems like network, hardware devices etc. Such systems are subject to failure anytime and error checking is not usually reliable. In those cases, you should use exception handlers and try to recover from error.

7. Do not write very large try-catch blocks. If required, write separate try-catch for each task you perform and enclose only the specific piece of code inside the try-catch. This will help you find which piece of code generated the exception and you can give specific error message to the user.

8. Write your own custom exception classes if required in your application. Do not derive your custom exceptions from the base class SystemException. Instead, inherit from ApplicationException.