Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » LINQ » How to create 3 tier application using LINQ

How to create 3 tier application using LINQ

This article describes how to create 3 tire architecture project in LINQ to SQL.

Total page views :  10367
Total downloads :  272
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Project.zip
 
Become a Sponsor



As you know that in 3 tier architecture there are three layers

  1. User interface layer. (Is our Form in Windows application and .aspx page in Web application)
  2. Data Access layer. (Which provides interface between Business logic layer and Database)
  3. Business Logic layer.(Which stores your application logic)

1.gif

Fig. 3 Tier Architecture 

Now we start how to create 3 tire architecture.

Step 1:
Create blank Solution name 'test'.

Step 2:
Add new Class Library project. Write name like 'BusinessLogiclayer'.

Step 3:
Add new website. Write name like 'UserInterfacelayer'.

Step 4:
Add new Class Library project. Write name like 'DataAccesslayer'.





Step 5:
Now add reference in to BusinessLogiclayer  

2.gif

Step 6:
And last Add reference to UserInterfacelayer

3.gif

Here we add two references Businesslogiclayer and DataAccesslayer. So your window will look like this,

4.gif

Now create Database name testLINQ and create a table name REGISTER.

CREATE TABLE
[dbo].[REGISTER](
          [ID] [int] IDENTITY(1,1) NOT NULL,
          [FNAME] [nvarchar](50) NOT NULL,
          [LNAME] [nvarchar](50) NOT NULL,
          [EMAILID] [nvarchar](max) NOT NULL,
          [PASSWORD] [nvarchar](50) NOT NULL,
 CONSTRAINT [PK_REGISTER] PRIMARY KEY CLUSTERED
(
          [ID] ASC
) WITH (PAD_INDEX = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

Step 7:
Create a form Register.aspx

<%
@ Page Language="C#" AutoEventWireup="true" CodeFile="Register.aspx.cs" Inherits="Register" %>
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
    <title>Untitled Page</title>  

</
head>
<
body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                 <table align="center">
                         <tr>
                           <td>
                    <asp:Label ID="lblfname" runat="server" Text="First Name:"></asp:Label></td>
                           <td>
                    <asp:TextBox ID="txtfname" runat="server"></asp:TextBox>
                               <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                                   ControlToValidate="txtfname" ErrorMessage="Firstname Required !">*</asp:RequiredFieldValidator>
           
               </td>
                         </tr>
                         <tr>
                              <td>
                    <asp:Label ID="lbllname" runat="server" Text="Last Name:"></asp:Label>
                </td>
                              <td>
                    <asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
                                  <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
                                      ControlToValidate="txtlname" ErrorMessage="Last Name required !">*</asp:RequiredFieldValidator>
                </td>
                        </tr>
                         <tr>
                              <td>
                    <asp:Label ID="lblemailid" runat="server" Text="Emailid:"></asp:Label>
                </td>
                              <td>
                    <asp:TextBox ID="txtemailid" runat="server"></asp:TextBox>
                                  <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
                                      ControlToValidate="txtemailid" ErrorMessage="Email id required !">*</asp:RequiredFieldValidator>
                                  <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
                                      ControlToValidate="txtemailid" ErrorMessage="Invalid Email id !"
                                      ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
                </td>
                         </tr>
                         <tr>
                              <td>
                    <asp:Label ID="lblpassword" runat="server" Text="Password:"></asp:Label>
                </td>
                              <td>
                    <asp:TextBox ID="txtpassword" runat="server" TextMode="Password"></asp:TextBox>
                                  <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
                                      ControlToValidate="txtpassword" ErrorMessage="Password required !">*</asp:RequiredFieldValidator>
                                  <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
                                      ControlToValidate="txtpassword" ErrorMessage="Invalid Password !"
                                      ValidationExpression="\w{6,10}">*</asp:RegularExpressionValidator>
                </td>
                         </tr>
                         <tr>
                <td>
                    &nbsp;</td>
                <td>
                    <asp:Button ID="Btnregister" runat="server" onclick="Btnregister_Click"
                        Text="Register" />
                             </td>
            </tr>
               </table>   
            </ContentTemplate>
        </asp:UpdatePanel>      
</
div>
    </form>

</
body>
</
html>

Page will look like this in browser

5.gif

Step 8:
In DataAccesslogiclayer add LINQ TO SQL class name test.dbml

Step 9:
Create Stored procedure sp_REGISTER.

-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
-- =============================================
-- Author:     
          Jayendrasinh Gohil
-- Create date: 30/07/2009
-- Description:          STORED PROCEDURE FOR REGISTER TABLE
-- =============================================

ALTER PROCEDURE
sp_REGISTER
          -- Add the parameters for the stored procedure here
          (
   @Task INT =0,
   @FNAME nvarchar(50)='',
   @LNAME nvarchar(50) = '',
   @EMAILID nvarchar(MAX) = '',
   @PASSWORD nvarchar(50)
)

AS
IF
(@Task = 1)
 BEGIN
   INSERT INTO [testLINQ].[dbo].[REGISTER]
           ([FNAME]
           ,[LNAME]
           ,[EMAILID]
           ,[PASSWORD])
     VALUES
           (
             @FNAME,
             @LNAME,
             @EMAILID,
             @PASSWORD
           )

END

Here we take @Task variable for running multiple SQL statement run in task wise. Pass @Task = 1 for insert, 2 for delete so on.

Step 10:
In Businesslogic layer, create class REGISTER.cs like this

#region
"Public Using"
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Data.Linq;
#endregion
#region
"Private Using"
using
DataAccesslayer;
#endregion 

namespace BusinessLoggiclayer
{
    public class REGISTER
    {

        #region
"Private variable"
        string _FNAME;      
        string _LNAME;     
        string _EMAILID;      
        string _PASSWORD;       

        #endregion 

        #region "Public Property"
        public string FNAME
        {
            get { return _FNAME; }
            set { _FNAME = value; }
        }
        public string LNAME
        {
            get { return _LNAME; }
            set { _LNAME = value; }
        }
        public string EMAILID
        {
            get { return _EMAILID; }
            set { _EMAILID = value; }
        }
        public string PASSWORD
        {
            get { return _PASSWORD; }
            set { _PASSWORD = value; }
        }

        #endregion

        #region "Public Method"
        public void Insert()
        {
            using (testDataContext db = new testDataContext())
            {
                db.sp_REGISTER(1, _FNAME, _LNAME, _EMAILID, _PASSWORD);
            }
        }

        #endregion

    }
}

Step 11:
Write code in Register.aspx.cs

using
System;
using
System.Collections;
using
System.Configuration;
using
System.Data;
using
System.Linq;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.HtmlControls;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Xml.Linq; 

#region "Private Using"
using
BusinessLoggiclayer;
#endregion 

public partial class Register : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
        }
    }
    protected void Btnregister_Click(object sender, EventArgs e)
    {
        REGISTER r = new REGISTER();
        r.FNAME = txtfname.Text;
        r.LNAME = txtlname.Text;
        r.EMAILID = txtemailid.Text;
        r.PASSWORD = txtpassword.Text;
        r.Insert();
    }
}


Login to add your contents and source code to this article
 About the author
 
Jayendrasinh Gohil

I have complite my PGDCA from SP University V.V.Nagar and MCP (Microsoft Certified Professional).With more then 2 years of exp. in the fild of Web Application.I have knowlage of  .NET 3.5,LINQ,AJAX,Crystal Report etc.

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Project.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
DAL configuration by Olly On August 31, 2009
There is no mention of how to configure the DAL. I get the following error:

Error 2 'DataAccessLayer.testDataContext' does not contain a definition for 'sp_REGISTER' and no extension method 'sp_REGISTER' accepting a first argument of type 'DataAccessLayer.testDataContext' could be found (are you missing a using directive or an assembly reference?) 
Reply | Email | Delete | Modify | 
DAL config by Olly On September 1, 2009

hi Jai,

I added the SP as a method in the .dbml file and the error was resloved, however now Im unable to see the public properties / method of the REGISTER class when I give the .Notation like r. what could I be doing wrong?

Excuse me, an absoulte newbie!

Thanks,
Olly

Reply | Email | Delete | Modify | 
3 tier app by Olly On September 1, 2009

Hey,

I figured it out! I had a local class with the same name in the UI layer that was being given prefrence. Qualifying the Class with the BusinessLogicLayer namespace did the job.

Thanks for posting this very basic example. Its a good start.

cheers,
Olly

Reply | Email | Delete | Modify | 
Awful by Sean On September 4, 2009
This is the most awful code I have seen on DotNetKicks in a LONG time. I would bury this trash if I could. Are you sure you're MCP? I don't even know where to start!

First of all, the conventions you follow are AWFUL. Why are you capitalizing everything? Please stick to the C# convention that you claim to be an expert on.

Next, you absolutely did NOT create a Business Layer, as you have suggested. It's a stripped down Data Access Layer that is missing a ton of functionality. But let me get this straight. You think that since you've added LINQ to SQL to a project that you have a full-blown DAL? What a waste.

Why did you create the REGISTER class, in the first place? You've completely done away with the benefits of using LINQ to SQL because you've just duplicated your efforts by writing code that represents an entity. What was the point? LINQ to SQL does this for you!

I really hope nobody follows this awful code.
Reply | Email | Delete | Modify | 
Layer vs Tier by Tim On September 8, 2009
I think you may be misunderstanding the differences between an n-tier application and an n-layer application.  One reason that n-tier applications are rarely seen in "demo"/"tutorial" form is that they are extremely complex to create and are very dependent on the application being created.

Your code is definitely not n-tier.  it is a layer-based approach, but even still - it is lacking in it's implementation.
Reply | Email | Delete | Modify | 
Very very basic by Viktar On September 28, 2009
This is a very very basic article. What about modifing bussiness entity?
Read my article about a subject:
Convert Subsonic project to Linq to SQL
Reply | Email | Delete | Modify | 
nice but a weak linq part by miram On December 9, 2009
Nice article
However the linq part was quite thin.
Reply | Email | Delete | Modify | 
3 tire application by your On December 30, 2009
3 tires? you mean like a tricycle? yay! Me first!
Reply | Email | Delete | Modify | 
Thanks by Nhat Khanh On December 30, 2009
thank you very much!
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.