Pages

Wednesday, December 8, 2010

Wrox Professional C# 3rd Edition

Wrox Professional C# 3rd Edition: "- Sent using Google Toolbar"

Sunday, November 14, 2010

Model View Controller in asp.net

1) http://www.asp.net/mvc/videos/aspnet-mvc-controller-overview
2) http://www.beansoftware.com/ASP.NET-Tutorials/MVC-Architecture-Model.aspx
3) http://www.dotnetuncle.com/wiki/ASPNET-MVC-Framework.aspx
4) http://www.slideshare.net/maartenba/msdn-aspnet-mvc
5) http://msdn.microsoft.com/en-us/library/dd394709.aspx
6) http://www.slideshare.net/jesschadwick/introduction-to-aspnet-mvc-3353914 
7) What is the difference between 3-tire architecture and MVC Architecture/Model? 
Ans: A fundamental rule in three-tier architecture is the client tier never communicates directly with the data tier; in a three-tier model all communication must pass through the middleware tier.

It’s liner architecture. This addresses the question of how to pass information between a user and a database. Where as MVC is a triangular architecture: the View sends updates to the Controller, the Controller updates the Model, and the View gets updated directly from the Model. This addresses questions of how a user interface manages the components on the screen.


Presentation layer(aspx, aspx.cs) = view and controller MVC (aspx, aspx.cs)
Application Layer = Model of MVC
Database layer = DB layer of MVC

Advantages of using MVC in ASP.NET

  • There's no duplicated code.
  • The business logic is encapsulated; hence the controller code is transparent and safer.
  • The business logic can be used in several front ends like Web pages, Web services, Windows applications, services, etc.
  • Exception handling is well managed showing the user only digested error messages.
  • Testing every part of an application is easier as it can be done separately using automated methods.
  • Application changes are easier to apply as they are focused in one part of the architecture only.

Tuesday, November 2, 2010

VisualStudioTeam System

1) http://letmeget.com/blog/microsoft-tfs-2010-microsoft-visual-studio-team-foundation-server-2010
2) http://www.microsoft.com/visualstudio/en-us/products/2010-editions/team-foundation-server/features
3) http://www.dotnetcurry.com/ShowArticle.aspx?ID=195
4) http://www.clemensreijnen.nl/post/2009/02/13/Visual-Studio-Team-System-2010-e28093-Episode-3-The-Lifecycle.aspx
5) http://dennisv.net/2009/01/14/test-driven-development-tdd-in-vsts-2010/

TFS

1) http://blogs.msdn.com/b/bharry/archive/2009/04/30/tfs-2010-admin-operations-setup-improvements.aspx

2) http://code.msdn.microsoft.com/TfsSdk (SDK)
3) http://blogs.msdn.com/b/bharry/archive/2009/04/19/team-foundation-server-2010-key-concepts.aspx
4) http://channel9.msdn.com/Blogs/pdc2008/TL52 Video
5) what is Team foundation server and Work Item tracking experience?
Ans: it's a microsoft product. The server-side component is team foundation server (commonly abbreviated tfs), which comprises two components: the application tier and the data tier. The application tier is a set of web services that provide access to tfs functionality, and a web portal and document repository facilitated by windows sharepoint services, whereas the data tier is essentially a microsoft sql server 2005 standard installation that warehouses all the information for tfs. Both tiers are required, but can be installed on the same or separate servers. Team foundation server contains one or more team projects, which consists of visual studio solutions, configuration files for team build and team load test agents, and a single sharepoint repository containing the pertinent documents for the project. It can be used as bug tracking tool, we can write test cases using tfs, we can publish the results of test cases in it, and we can use it as a source control repository.
6) http://bisherryli.wordpress.com/category/team-foundation-server-tfs/
7) http://blogs.msdn.com/b/jasonz/archive/2009/10/21/tutorial-getting-started-with-tfs-in-vs2010.aspx
8) http://blogs.msdn.com/b/aaronbjork/archive/2009/10/26/how-does-msf-agile-4-2-compare-to-msf-agile-5-0.aspx

Tuesday, October 19, 2010

.Net Interview Questions- 19Oct2010 - 7:00PM EST

The below questions are the phone screening questions before applying to the client.
1) What is abstract class
2) Inheritance
3) Difference between Interface and inheritance
4) Access specifiers private, protected, Public.
5) Try catch loop
6) Does try catch loop can contain multiple catch blocks
7) Try catch Finally
8) What are stored procedures
9) Joins (inner,outer, equi join, left outer join )
10) Difference between select stmt and stored procedure
 Ans:
When I first started using SQL Server as a novice, I was initially confused as to the differences between the SELECT statement, views, and stored procedures. They all seemed to perform more or less the same task (retrieve data), and I wanted to know the pros and cons of using each.
Why would SQL Server offer three different options to retrieve data from database? As a developer and new DBA, I took it upon myself to learn everything I could about these options, why they may be required, and when they should be used. This article is a result of my learning and experience, and explains the differences between SELECT statements, views, and stored procedures for the DBA or developer new to SQL Server. I hope you find this article useful.
As you read this article, if you choose, you can cut and paste the code into Query Analyzer I have provided in order to more fully understand and appreciate the differences between the SELECT statement, views, and stored procedures. I have divided this article into three parts to better explain this information.

Starting Notes
To get us started on learning the differences between the SELECT statement, views, and stored procedures, I need to mention the syscacheobjects system table. It is used to store information about compiled objects and their execution plans. The reason for this is because compiled SELECT statements, views, and stored procedures are stored here, and I have used this table to experiment and learn more about how these three different objects are stored and used by SQL Server. If you are not familiar with this system table, you might want to take a peek at it. It is stored in the master database, and can be viewed with Enterprise Manager or Query Analyzer.
If you choose to follow along with the examples in this article, you will want to run the DBCC FREEPROCCACHE command before each run. This command clears the syscacheobjects table of any current cached objects, and allows us to perform more accurate tests.
Now, let’s create a table and input a few rows in the table before we commence at taking a look at the  differences between the SELECT statement, views, and stored procedures.

Create Sample Table
I assume you have a database you can use for this. If not, you will want to create one at this time. Now, we need to create a table for our experimentation.
Create Table DummyTable1
(
             EmpId Int,
             EmpName Varchar(8000)
)
Now, let’s add a few records in this table using this script:

Insert Into DummyTable1 Values (1, Replicate ('a',20))
GO
Insert Into DummyTable1 Values (2, Replicate ('b',20))
GO
Insert Into DummyTable1 Values (3, Replicate ('c',20))
GO
Insert Into DummyTable1 Values (4, Replicate ('d',20))
GO
Insert Into DummyTable1 Values (5, Replicate ('e',20))
GO
Insert Into DummyTable1 Values (6, Replicate ('f',20))
GO
Insert Into DummyTable1 Values (7, Replicate ('g',20))
GO
Insert Into DummyTable1 Values (8, Replicate ('h',20))
GO
Insert Into DummyTable1 Values (9, Replicate ('i',20))
GO
Insert Into DummyTable1 Values (10, Replicate ('j',20))
GO

DummyTable1 has contains sufficient rows to experiment with the differences between the SELECT statement, views, and stored procedures.
Let us begin with the SELECT statement and see how it is different from views and stored procedures.

SELECT Statement
Now, let’s view the contents of the table by EXECuting the following command in Query Analyzer for our new table.
SELECT EmpId, EmpName FROM DummyTable1
GO
EmpID EmpName
1
aaaaaaaaaaaaaaaaaaaa
2
bbbbbbbbbbbbbbbbbbbb
3
cccccccccccccccccccc
4
dddddddddddddddddddd
5
eeeeeeeeeeeeeeeeeeee
6
ffffffffffffffffffff
7
gggggggggggggggggggg
8
hhhhhhhhhhhhhhhhhhhh
9
iiiiiiiiiiiiiiiiiiii
10
jjjjjjjjjjjjjjjjjjjj
As you would expect, the data we inserted earlier has been displayed.
Now, let’s execute the following commands to clear the cache.
DBCC FREEPROCCACHE
GO
Freeing the procedure cache prevents an ad-hoc SQL statement from being reused, assuming that it is currently in the cache. This means that the next time we run the same ad-hoc statement, that it must be newly recompiled.
11) Difference between truncate and delete table
Ans: The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to
COMMIT or ROLLBACK the transaction to make the change permanent or to undo it.
TRUNCATE removes all rows from a table. The operation cannot be rolled back. As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.
The DROP command removes a table from the database. All the tables' rows,
indexes and privileges will also be removed. The operation cannot be rolled back.
DROP and TRUNCATE are DDL commands, whereas DELETE is a DML command. Therefore DELETE operations can be rolled back (undone), while DROP and TRUNCATE operations cannot be rolled back.
From Oracle 10g a table can be "undropped". Example:
SQL> FLASHBACK TABLE emp TO BEFORE DROP;
Flashback complete.

12) types of triggers
Ans:  Before Trigger, After Trigger, before Insert Trigger, After Insert Trigger, Before Update Trigger and After Update trigger.
http://en.wikipedia.org/wiki/Database_trigger
http://www.sqlteam.com/article/an-introduction-to-triggers-part-i
http://www.aspfree.com/c/a/MS-SQL-Server/Brief-Introduction-to-Triggers-in-SQL-Server-2000/
13) Primary Key, Foreign Key

SQL

1) http://www.1keydata.com/sql/sqltruncate.html
2) http://www.sourcecodeonline.com/list?q=sql_for_banking_system
3) http://www.blueclaw-db.com/accessquerysql/
4) http://www.databasejournal.com/scripts/

Redirect a SharePoint site by using the Content Editor Web Part

http://www.endusersharepoint.com/2010/01/20/redirect-a-sharepoint-site-by-using-the-content-editor-web-part/

SharePoint Gradual Upgrade – Random Page Error ‘This Page is Redirecting…’

http://cregan.wordpress.com/2007/11/16/sharepoint-gradual-upgrade-random-page-error-this-page-is-redirecting/

Sharepoint 2007 How to redirect the url from http://servername to http:/intranet

http://social.technet.microsoft.com/Forums/en-US/sharepointadmin/thread/96ae27c7-7ec6-4a30-9c9a-0ba6b940477b

SharePoint Customization Tip: Redirect to a custom page after completing a list form

http://www.graphicalwonder.com/?p=666

Redirect Pages on SharePoint

Replicated for archival retrieval purposes only!

Redirection options in SharePoint
I see questions about redirecting users in SharePoint all the time. Usually they're in the context of "I want to redirect users, can I do this with an Alternate Access Mapping?" SharePoint admins know that if they don't set their AAMs up correctly that SharePoint will bounce their users around like a SuperBall, so they hope they can harness that power for good, instead of evil. While you can in certain circumstances most likely you will want to use a different approach. In this blog post I will show you several different to redirect users in SharePoint. Then when you find yourself needing to, you can use the method best suited for your situation.
When deciding which redirection method to employ, you need to determine what you're redirecting from and what you're redirecting to. That will determine which method to use. For each of the methods I discuss below I will provide examples of the situation you would use it in. Enough with the introduction, let's get down to it.

Vanity URLs

One of the most common requests I see is for vanity URLs. SharePoint URLs can get long and unmanageable and admins want URLs that their users can remember. They want to use something like http://software and have it forwarded to http://team/sites/software/development. To set expectations correctly, you should just come to terms with the fact that you aren't going to write SharePoint URLs down, you'll pass them along via or IM. If you do want short URLs you can have them forward to deep SharePoint sites. Of course the URL your users will eventually get to will be the long URL, but the jumping off point will be easy to remember. To do this kind of redirection I use IIS directly, I don't get SharePoint involved at all. Create a new virtual server in IIS Manager and give it a descriptive name like "Software Redirect." When you're walking through the wizard you'll take the defaults. You'll have to point it to a local directory. This is only temporary, so you can point it anywhere. After the virtual server is created, edit the properties. Open the "Home Directory" tab and click "A redirection to a URL" then type your SharePoint URL in the "Redirect to:" box. It should look like this:

Figure 1 – Redirection settings
This method works pretty well and is easy for users. It does have a couple of drawbacks you should know about. Each virtual server running takes up RAM on your IIS server. You can take steps to mitigate this. I create a new App Pool and use it strictly for the redirect virtual servers. Then I set that App Pool to timeout if idle for 1 minute. Since this App Pool does not really do much, it does not use much RAM, but this reduces that memory footprint liability to only a minute or two on your web server each time someone uses the redirect. In my experience the App Pool only used 5 or 10 MB of RAM each time someone hit it. With today's machines that's not much of a hit. Overall I've been very happy with this approach.

Figure 2 - App Pool memory settings

Server URL has changed and users have bookmarks

This can happen from time to time, a server name changes or you move your site from HTTP to HTTPS. If your users have bookmarks to the old URLs this can cause problems. One option is to tell your users they're out of luck, but this is a great opportunity to look like a SharePoint Hero. You may be able to use AAMs to work this type of redirection, but they don't work consistently. For instance, the AAM will redirect a URL without a page, but will not redirect one that does. So http://oldserver would redirect but http://oldserver/default.aspx would not. Because most bookmarks will have the page included we can't rely on this. To handle this I employ a technique similar to how I handle Vanity URLs. First you'll need to make sure your existing SharePoint virtual server no longer responds to the old URL. Normally I just change the port to an used port like 8080, so that it's easy to change back. Next create a new virtual server and make sure it responds to the old URL, so you may need to add a host header or adjust the port. Like above, after you've created the redirect virtual server edit its Home Directory property. Instead of feeding it a static URL we're going to employ some redirect variables. Before I explain them, here's what your redirect URL will look like:

Figure 3 - Redirection variables
Two changes should jump out at you. First, the URL ends in $V$Q. The $V represents the original URL the user is trying to access, but without the protocol, servername or parameters. The $Q represents any parameters the URL included. Here's a crude drawing of how the URL breaks down:

Figure 4 - URL breakdown
Since all we want from the old URL is the path and the parameters, $V$Q works well for us. You can find a list of all the supported redirection parameters here. You'll also want to check the "A permanent redirection for this resource." This gives the client back an http 301 reponse which tells it the redirect is permanent. Some clients can understand this and will fix the Bookmark to the new URL. Other clients can't understand 300 level responses at all and will fail completely regardless. Full documentation on this switch and the rest can be found in the IIS Manager help. Once the screen is up you can hit F1 to open the help. After you have this all configured any requests this virtual server handles will be forwarded with path and parameters to the URL you specified.

Redirect from Deep URL

Sometimes you aren't redirecting an entire URL, or even just the servername. Sometimes you're just moving a web and you want users to be redirected to the new location. Since you don't want to redirect the entire web application you can't use either of the previous techniques. Fortunately there is a way. There is much magic in the Content Editor Web Part (CEWP) and this is another example. You can use a CEWP to insert HTML code to send your users wherever you want them. To utilize it add a CEWP to your web part page, usually the default.aspx at the root of your web. Edit the web part properties. Click Source Editor and add a Meta Refresh tag to send your users to the new site. It will look like this:

Figure 5 - CEWP Properties
The "10" in the content tag means the page wait 10 seconds before it refreshes. A longer time is handy if you want to put a message alerting your users to the new location before you forward them. The URL is the URL your users will be sent to. Of course this will only work on the page you put it on, so you may need place it on multiple pages in your web, like your Shared Document library pages. Fortunately since it is just a web part you can export it and import on additional pages, you don't need to recreate it each time.
There are some drawbacks to this approach, and it's generally considered bad form to use a refresh tag to forward users. For one it breaks your users' Back button in their browsers. It can also confuse your users, especially if the redirect is fast and there isn't a note on the page explaining that the site has moved. Finally, make very sure the URL you're redirecting them to is valid. If not they get stuck on a dead page and no way to use Back to get out. Sometimes it is your only option though.
This blog post wouldn't be complete without a mention of MOSS' Redirect Page content type. If you're using MOSS and you're on a Publishing Site you can access to it. Go to your Pages document library and Click new. It will be in your list.

Figure 6 - Redirect Page content type
Once the Redirect Page is created you'll need to Edit its Properties and enter the URL you want it to redirect to. You'll also need to preview the page and check it in before it will work. Unfortunately this solution only works on Publishing sites.
As you can see, SharePoint and IIS provide many ways to redirect users. Each method has its benefits and drawbacks. Hopefully this blog post will provide you with one method that will work for your situation.

Monday, October 18, 2010

MVC Architecture Model In ASP.NET

When developing ASP.NET applications the need of reducing code duplication increases along with their complexity. This is because testing and performing changes become very difficult tasks when having many different sources of code with the same functionality.

Model View Controller architecture (or pattern) allows us to separate different parts of our applications into tiers to fulfill this need.

MVC Overview

Model View Controller architecture aims to separate an application into three parts:
Model: It is the business logic of an application. From an object oriented perspective it would consist of a set of classes that implement the critical functionality of an application from a business point of view.
View: It can consist of every type of interface given to the user. In ASP.NET the view is the set of web pages presented by a web application.
Controller: This part of the architecture is the most difficult to explain, hence the most difficult to implement in many platforms. The controller is the object that allows the manipulation of the view. Usually many applications implement Model-Controller tiers that contain the business logic along with the necessary code to manipulate a user interface. In an ASP.NET application the controller is implicitly represented by the code-behind or the server side code that generates the HTML presented to the user.

Implementing MVC in ASP.NET

A basic diagram that would help us understand perfectly the specific parts that implement the Model View Controller architecture in an ASP.NET application is presented below:
MVC implementation in ASP.NET

MVC Model Implementation

When implementing the business logic of an application it is a must to use a Class Library project in order to generate a .dll file that will encapsulate all the functionality. This is critical as we as professional developers would not like to jeopardize the source code of a software product by placing the actual .cs files as a reference in a web application.
This type of project can be easily created in Visual Studio 2005 under the Visual C# or Visual Basic tabs:
Creating a Class Library Project
As a tutorial example we will develop a simple calculator under a new namespace we will call "Math".
Once the project is created we will add a class called Calculator:
Adding Calculator class
As the code is very simple and a sample is provided in this tutorial we will not get into much detail as far as how it is developed. The only important thing we need to mention is the way errors have to be handled in this class. Take a look at the following code:
1. protected float Divide(float fNumber1, float fNumber2)
2. {
3.   if (fNumber2 == 0)
4.  {
5.           throw new Exception( "Second number cannot be equal to zero.");
6.    }

7.   return (fNumber1 / fNumber2);
8. }

When implementing the Divide function we need to ensure that the user would not be able to set the "fNumber2" parameter (line 1) to zero as a division between zero does not exist. The validation statement in lines 3-6 takes care of this case but the important fact we need to notice is that this class will NEVER use specific methods to present errors like message boxes or writing into labels. Errors captured in the model part of the architecture ALWAYS have to be presented in the form of exceptions (line 5). This will allow us to use this object in several types of applications like ASP.NET applications, Windows applications, Web services, etc.
Once we have finished coding our Calculator class the project has to be built in order to get the .dll file we will use in our Web application.

MVC View-Controller Implementation

The View and the Controller objects will be implemented by using a common ASP.NET Website. Once we have created our project we need to add the reference to the .dll file we created before.
The option to do this can be found in the context menu when right-clicking the project in the solution explorer:
Adding the a reference
We can find the file in the path "\bin\Release" (or "\bin\Debug" depending on how you build your class library) inside our main folder containing the math class library project:
Adding Math.dll reference
Once we have referenced our library we will create a simple web page that will allow us to choose between the four basic arithmetic operations and type two different numbers to operate.
The web page will look like this:
Calculator Web page
In the code behind we need to reference the Math namespace in order to use our Calculator class. The following statement will do that:
using Math;
As the code for this application is also simple we will only explain the method called when the "Operate!" button is clicked:
1. protected void btnOperate_Click(object sender, EventArgs e)
2. {
3.   if (pbValidateNumbers())
4.   {
5.        Calculator cOperator = new Calculator();
6.         try
7.         {
8.               txtResult.Text = cOperator.Operate(float.Parse(txtNumber1.Text.Trim()), float.Parse(txtNumber2.Text.Trim()), Convert.ToInt16(rblOperations.SelectedValue)).ToString();
9.               lbError.Text = "";
10.        }
11.        catch (Exception ex)

12.        {
13.              txtResult.Text = "";
14.              lbError.Text = ex.Message;
15.        }
16.  }
17.}
In line 3 we call the bool function "pbValidateNumbers" that will return true if the numbers typed in both textboxes are valid. These types of validations have to be performed by the controller object as they allow the interface to work properly and have nothing to do with the business logic.
In line 5 we create an instance of our Calculator class so we can perform the arithmetic operation. We call the method "Operate" (line 8) and return the value in another textbox. An important thing to mention is that we have to use a try-catch statement (lines 6-15) to handle any exception that could be thrown by our method "Operate" as every error caught in our Calculator class is handled by throwing a "digested" exception that is readable to the user.
In the code above we can appreciate how well encapsulated the business logic is, hence it can be reused in several applications without having to code it again.

Advantages of using MVC in ASP.NET

  • There's no duplicated code.
  • The business logic is encapsulated; hence the controller code is transparent and safer.
  • The business logic can be used in several front ends like Web pages, Web services, Windows applications, services, etc.
  • Exception handling is well managed showing the user only digested error messages.
  • Testing every part of an application is easier as it can be done separately using automated methods.
  • Application changes are easier to apply as they are focused in one part of the architecture only.
Click here to download the example project, used in this tutorial.

Saturday, July 3, 2010

Sample code programs from asp.net site

http://www.asp.net/community/projects#jm_starter_kits_and_samples

Button controls code from asp.net site

http://www.asp.net/community/control-gallery/browse.aspx?category=32&Page=3

Wednesday, May 19, 2010

CVS Version Control for Web Site Projects

cvs (concurrent versions system) is a freely available tool designed to help programmers implement version control and configuration management of software projects. we've found that cvs can be helpful in the design, development, care and feeding of our web site code and content as well. for more information about cvs, visit the Ximbiot CVS Wiki.

This writeup describes use of cvs version control for web development, quality assurance, and maintenance, originally developed at inter@ctivate consulting group (1997), and later applied to engineering processes at SavvySearch Limited (1998-1999) and CNET Search.com (1999-2010).

CVS Documentation Hosted Here

Wednesday, April 28, 2010

ASP.NET Interview Questions

ASP.NET Interview Questions
This is a list of questions I have gathered and created over a period of time from my experience, many of which I felt where incomplete or simply wrong.  I have finally taken the time to go through each question and correct them to the best of my ability.  However, please feel free to post feedback to challenge, improve, or suggest new questions.  I want to thank those of you that have contributed quality questions and corrections thus far.
There are some questions in this list that I do not consider to be good questions for an interview.  However, they do exist on other lists available on the Internet so I felt compelled to keep them here for easy access.
  1. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.
    inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.
     
  2. What’s the difference between Response.Write() andResponse.Output.Write()?Response.Output.Write() allows you to write formatted output.
     
  3. What methods are fired during the page load?Init() - when the page is instantiated
    Load() - when the page is loaded into server memory
    PreRender() - the brief moment before the page is displayed to the user as HTML
    Unload() - when page finishes loading.
     
  4. When during the page processing cycle is ViewState available?
    After the Init() and before the Page_Load(), or OnLoad() for a control.
     
  5. What namespace does the Web page belong in the .NET Framework class hierarchy?System.Web.UI.Page
     
  6. Where do you store the information about the user’s locale?System.Web.UI.Page.Culture
     
  7. What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?CodeBehind is relevant to Visual Studio.NET only.
     
  8. What’s a bubbled event?When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.
     
  9. Suppose you want a certain ASP.NET function executed on MouseOver for a certain button.  Where do you add an event handler?Add an OnMouseOver attribute to the button.  Example: btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");
     
  10. What data types do the RangeValidator control support?Integer, String, and Date.
     
  11. Explain the differences between Server-side and Client-side code?Server-side code executes on the server.  Client-side code executes in the client's browser.
     
  12. What type of code (server or client) is found in a Code-Behind class?The answer is server-side code since code-behind is executed on the server.  However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser.  But just to be clear, code-behind executes on the server, thus making it server-side code.
     
  13. Should user input data validation occur server-side or client-side?  Why?All user input data validation should occur on the server at a minimum.  Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user.
     
  14. What is the difference between Server.Transfer and Response.Redirect?  Why would I choose one over the other?Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser.  This provides a faster response with a little less overhead on the server.  Server.Transfer does not update the clients url history list or current url.  Response.Redirect is used to redirect the user's browser to another page or site.  This performas a trip back to the client where the client's browser is redirected to the new page.  The user's browser history list is updated to reflect the new address.
     
  15. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?Valid answers are:
    · 
    A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.·  A DataSet is designed to work without any continuing connection to the original data source.·  Data in a DataSet is bulk-loaded, rather than being loaded on demand.·  There's no concept of cursor types in a DataSet.·  DataSets have no current record pointer You can use For Each loops to move through the data.·  You can store many edits in a DataSet, and write them to the original data source in a single operation.·  Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
     
  16. What is the Global.asax used for?The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.
     
  17. What are the Application_Start and Session_Start subroutines used for?This is where you can set the specific variables for the Application and Session objects.
     
  18. Can you explain what inheritance is and an example of when you might use it?When you want to inherit (use the functionality of) another class.  Example: With a base class named Employee, a Manager class could be derived from the Employee base class.
     
  19. Whats an assembly?Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN
     
  20. Describe the difference between inline and code behind.Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.
     
  21. Explain what a diffgram is, and a good use for one?The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML.  A good use is reading database data to an XML file to be sent to a Web Service.
     
  22. Whats MSIL, and why should my developers need an appreciation of it if at all?MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL.  MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.
     
  23. Which method do you invoke on the DataAdapter control to load your generated dataset with data?The Fill() method.
     
  24. Can you edit data in the Repeater control?No, it just reads the information from its data source.
     
  25. Which template must you provide, in order to display data in a Repeater control?ItemTemplate.
     
  26. How can you provide an alternating color scheme in a Repeater control?Use the AlternatingItemTemplate.
     
  27. What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control?You must set the DataSource property and call the DataBind method.
     
  28. What base class do all Web Forms inherit from?The Page class.
     
  29. Name two properties common in every validation control?ControlToValidate property and Text property.
     
  30. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?DataTextField property.
     
  31. Which control would you use if you needed to make sure the values in two different controls matched?CompareValidator control.
     
  32. How many classes can a single .NET DLL contain?It can contain many classes.
     
Web Service Questions
  1. What is the transport protocol you use to call a Web service?SOAP (Simple Object Access Protocol) is the preferred protocol.
     
  2. True or False: A Web service can only be written in .NET?False
     
  3. What does WSDL stand for?Web Services Description Language.
     
  4. Where on the Internet would you look for Web services?http://www.uddi.org
     
  5. True or False: To test a Web service you must create a Windows application or Web application to consume this service?False, the web service comes with a test page and it provides HTTP-GET method to test.
     
State Management Questions
  1. What is ViewState?ViewState allows the state of objects (serializable) to be stored in a hidden field on the page.  ViewState is transported to the client and back to the server, and is not stored on the server or any other external source.  ViewState is used the retain the state of server-side objects between postabacks.
     
  2. What is the lifespan for items stored in ViewState?Item stored in ViewState exist for the life of the current page.  This includes postbacks (to the same page).
     
  3. What does the "EnableViewState" property do?  Why would I want it on or off?It allows the page to save the users input on a form across postbacks.  It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser.  When the page is posted back to the server the server control is recreated with the state stored in viewstate.
     
  4. What are the different types of Session state management options available with ASP.NET?
    ASP.NET provides In-Process and Out-of-Process state management.  In-Process stores the session in memory on the web server.  This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server.  Out-of-Process Session state management stores data in an external data source.  The external data source may be either a SQL Server or a State Server service.  Out-of-Process state management requires that all objects stored in session are serializable.

Monday, April 26, 2010

3-Tire Architecture Overview

Introduction

As a developer, the .NET framework and Visual Studio present many choices for choosing the right architecture, from placing the data access code directly in the UI through datasets and data source controls, to creating a data access layer that talks to the database, all the way to creating an n-tier architecture approach that consists of multiple layers, and use data-transfer objects to pass data back and forth.
If you’ve ever wondered why you should use layers and what the benefits are, this article is for you. This article delves into the use of layers and how they can benefit any application.

What is a Layer?

A layer is a reusable portion of code that performs a specific function. In the .NET environment, a layer is usually setup as a project that represents this specific function. This specific layer is in charge of working with other layers to perform some specific goal. In an application where the presentation layer needs to extract information from a backend database, the presentation would utilize a series of layers to retrieve the data, rather than having the database calls embedded directly within itself. Let’s briefly look at the latter situation first.

Two-Tier Architecture

When the .NET 2.0 framework became available to the world, there were some neat features that allowed the developer to connect the framework’s GUI controls directly to the database. This approach is very handy when rapidly developing applications. However, it’s not always favorable to embed all of the business logic and data access code directly in the web site, for several reasons:
  • Putting all of the code in the web site (business logic and data access) can make the application harder to maintain and understand.
  • Reusing database queries in the presentation layer often isn’t done, because of the typical data source control setup in the ASP.NET framework.
  • Relying on the data source controls can make debugging more difficult, often due to vague error messages.
So in looking for an alternative, we can separate the data access code and business logic into separate “layers”, which we’ll discuss next.

The Data Layer

The key component to most applications is the data. The data has to be served to the presentation layer somehow. The data layer is a separate component (often setup as a separate single or group of projects in a .NET solution), whose sole purpose is to serve up the data from the database and return it to the caller. Through this approach, data can be logically reused, meaning that a portion of an application reusing the same query can make a call to one data layer method, instead of embedding the query multiple times. This is generally more maintainable.
But the question is how is the data returned? Multiple frameworks employ different techniques, and below is a summary:
  • ADO.NET – Built into the .NET framework, ADO.NET contains a mechanism to query data out of the database and return it to the caller in a connected or disconnected fashion. This is the most common approach to working with data, because it’s already readily available. See more at: http://en.wikipedia.org/wiki/ADO.NET.
  • Table Adapters/Strongly-Typed Datasets – Strongly-typed datasets and table adapters provide a similar means to querying the data through ADO.NET, but add strong-typing features, meaning custom objects are generated for you to work with. See more here.
  • Enterprise Library – Enterprise library Data Access Application Block provides a flexible way to connect to databases of multiple types, without having to know anything about that database, through an abstract approach. See more at: http://msdn2.microsoft.com/en-us/magazine/cc188705.aspx (read part one first).
  • LINQ-to-SQL – LINQ to SQL is an ORM tool that uses a DataContext object as the central point to query data from the database. See more here. (read parts one through eight first).
  • Auto-Generated Code – Tools like CodeSmith Studio automatically generate the code for you based upon a database schema. Simply writing a script to output the code you want to use and the backend is generated in a short amount of time. See more at: http://community.codesmithtools.c om/blogs/tutorials/archive/2006/02/13/nettiers.aspx.
Most (if not all) options above take advantage of the CRUD (create, read, update, or delete) operations that databases support, so all of that is available as shown above. There are plenty of resources online to help you get started. To see an overview of some of the options, please read this.

Business Layer

Though a web site could talk to the data access layer directly, it usually goes through another layer called the business layer. The business layer is vital in that it validates the input conditions before calling a method from the data layer. This ensures the data input is correct before proceeding, and can often ensure that the outputs are correct as well. This validation of input is called business rules, meaning the rules that the business layer uses to make “judgments” about the data.
However, business rules don’t only apply to data validation; these rules apply to any calculations or any other action that takes place in the business layer. Normally, it’s best to put as much logic as possible in the business layer, which makes this logic reusable across applications.
One of the best reasons for reusing logic is that applications that start off small usually grow in functionality. For instance, a company begins to develop a web site, and as they realize their business needs, they later decide to add a smart client application and windows service to supplement the web site. The business layer helps move logic to a central layer for “maximum reusability.”

Presentation Layer

The ASP.NET web site or windows forms application (the UI for the project) is called the presentation layer. The presentation layer is the most important layer simply because it’s the one that everyone sees and uses. Even with a well structured business and data layer, if the presentation layer is designed poorly, this gives the users a poor view of the system.
It’s best to remove as much business logic out of the UI and into the business layer. This usually involves more code, but in my mind, the excess time (which ranges from minimal to moderate, depending on the size of the application) pays off in the end.
However, a well-architected system leaves another question: how do you display it in an ASP.NET or windows application? This can be more of a problem in ASP.NET, as the controls are more limited to the type of inputs they can receive. If you use certain architectures, like passing datasets from the data to the presentation layer, this isn’t as much of a challenge; however, the challenge can come with business objects that support drill-through business object references.

Why Separating Logic Is Useful

You may wonder why it is important to move as much logic outside the presentation layer and into the business layer. The biggest reason is reuse: logic placed in a business layer increases the reusability of an application. As applications grow, applications often grow into other realms. Applications may start out as a web application, but some of the functionality may later be moved to a smart client application. Portions of an application may be split between a web site and a web or windows service that runs on a server. In addition, keeping logic helps aid in developing a good design (sometimes code can get sloppier in the UI).
However, there are some caveats to this: it takes a little longer to develop applications when most of the logic resides in the business layer. The reason is this often involves creating several sets of objects (data layer and access code, plus business objects) rather than embedding it in the application. The extra time that it takes to do this can be a turnoff for some managers and project leads, especially because it often requires you to be knowledgeable about object-oriented programming, more than most people are comfortable with.
Although embedding code in the UI is easier, in most cases I don’t believe it’s the best approach. A layered approach is often a better approach because it pays dividends down the road. This is because as more and more code is developed, the following happens:
  • Code is copied and pasted frequently, or code is reused in classes that could easily be moved to a business layer.
  • Code that is very similar is often copied and pasted with slight modification, making duplication harder to track down.
  • It’s harder to maintain; even though applications with business objects are larger applications, they usually are structured better.
  • Code is harder to unit test, if unit testing is available at all. Web applications and windows forms projects are hard to use unit testing with.
A good architecture is often harder to implement, but is easier to maintain because it often reduces the volume of code. This means that hours spent supporting an application are reduced.

Distributed Applications

Using a separation of layers can aid in development of distributed applications. Because the code is broken up into layers, a layer that facilitates the use of remoting or web services can be added to the project, with a minimal amount of work.

Development Techniques

When developing a business object architecture, it’s good to know about the many design patterns that are out there. There are many websites, blogs, and books related to the subject of design patterns. One of the more well-known books on the subject is titled “Design Patterns,” whom the authors are often referred to as the Gang of Four.
Another useful development technique is called Refactoring, or improving the quality of your code by making small changes to the way it works. This involves moving code into a method, or moving a method from one object to another, in a systematic, logical way. Martin Fowler has written a great book on this subject, called “Refactoring, Improving the Design of Existing Code.” There are plenty of books on the subject; this one is the source that helped me to understand refactoring the most.
There are also tools on the market that can help you refactor in a faster way. One of those tools is Resharper by Jet Brains, which looks for a lot of code patterns and refactors them in a way that is useful. Some of the other refactoring tools that I heard about are Refactor Pro by DevExpress (free for VB.NET and ASP.NET), Visual Assist X by Whole Tomato Software, and Just Code by OmniCore.

Conclusion

This article reviewed the use of layers in an application, and discussed the fundamentals of their use. It also discussed the purpose of each layer, why using layers is important, and some other techniques useful for developing applications.