step by step exercises - telemark university...
TRANSCRIPT
Client-Server
SoftwareArchitecture
WebServices
APIs
3-TierArchitecture
API:ApplicationProgrammingInterface.Differentdevicesorsoftwaremodulescansharethesamecode.Codeonce,useitmanytimes
WebServices:Astandardwaytogetdataoveranetwork/InternetusingstandardWebprotocols(HTTP,etc.)
3-Tier:Awaytostructureyourcodeintologicalparts.Differentdevicesorsoftwaremodules cansharethesamecode.
GoodSoftware!
2-Tier
n-Tier
3
Thedatabase-centricstyle.Typically,theclientscommunicatedirectlywiththedatabase.
Athree-tierstyle,inwhichclientsdonotconnectdirectlytothedatabase.
WebServices,etc.
3-tier/layerArchitecture
4
PresentationTier
BusinessLogicTier
DataAccessTier
DataSource
PL
BL
DAL
Note!T
hedifferen
tlayerscanbeon
the
samecompu
ter(LogicL
ayers)oro
ndiffe
rent
Compu
tersinanetwork(Ph
ysicalLa
yers)
DataTier- DL
LogicTier
Why3-Tier(N-TierArchitecture?)• Flexibleapplications• Reusablecode– Codeonce,usemanytimes
• Modularized– Youneedonlytochangepartofthecode– Youcandeployonlyonepart– YoucanTestonlyonepart– MultipleDevelopers
• Differentparts(Tiers)canbestoredondifferentcomputers
• DifferentPlatformsandLanguagescanbeused• etc.
5
3-tier/layerArchitecturePresentationTier• Thisisthetopmostleveloftheapplication.• Thepresentationtierdisplaysinformationrelatedtosuchservicesasbrowsing
merchandise,purchasingandshoppingcartcontents.• Itcommunicateswithothertiersbywhichitputsouttheresultstothe
browser/clienttierandallothertiersinthenetwork.• Insimpletermsitisalayerwhichuserscanaccessdirectlysuchasawebpage,
oranoperatingsystemsGUIApplicationtier(businesslogic,logictier,dataaccesstier,ormiddletier)• Thelogicaltierispulledoutfromthepresentationtierand,asitsownlayer.• Itcontrolsanapplication’sfunctionalitybyperformingdetailedprocessing.Datatier• Thistierconsistsofdatabaseservers.Hereinformationisstoredandretrieved.• Thistierkeepsdataneutralandindependentfromapplicationserversor
businesslogic.• Givingdataitsowntieralsoimprovesscalabilityandperformance.
7http://en.wikipedia.org/wiki/Multitier_architecture
3-tierArchitecture
PresentationTier
BusinessLogicTier
DataAccessTier
Database
PresentationTier PresentationTier
StoredProcedures
DataTier
LogicTier
3-tierArchitecture
PresentationTier
BusinessLogicTier
DataAccessTier
Database
PresentationTier PresentationTier
StoredProcedures
DifferentDevicescansharethesameBusinessandDataAccessCode
ThedifferentTierscanbephysicalorlogical DataTier
LogicTier
WebServer
3-tier+WebService Architecture- Example
PresentationTier
Business/DataLogicTier
DataSource
WebServices
Server(s)
DataTier
StoredProcedures
Server-side Client-side
WebServer
3-tier+WebServiceArchitecture- Example
PresentationTier
Business/DataLogicTier
DataSource
WebServices
Team
Fou
ndationServer
TFSCient
InstalledononeormoreWindowsServersinyourLANorintheCloud
DataTier
StoredProcedures
TeamFoundationServer
3-tierArchitectureScenarios
PresentationLayer
BusinessLogic
DataAccessLogicDatabase
PresentationLayer PresentationLayer
StoredProcedures
Client
ClientClient
WebServer
WebService
PresentationLayer
Client
PresentationLayer
Internet
LocalNetwork(LAN)
Client
Firewall
PresentationLayer
ServerServer
Exercises1. CreateDataTier (Database)2. CreateLogicTier(DatabaseCommunicationLogic)
CreatePresentationTier(UserInterfaceLogic):3. WebApp:UsingASP.NETWebForms(WSnormallynotneeded)
4. DesktopApp:UsingWinFormsA. WithoutWebServices(WeassumetheAppwillbeused
onlyintheLANandthatwehavedirectaccesstotheDatabase)
B. WithWebServices(WeassumetheAppshouldbeusedonInternetoutsidetheFirewallwithoutdirectDBaccess)
Database
PresentationTier
e.g.,ADO,ADO.NET
LogicTier
WebService
BusinessTier
DataAccessTier
DataTier
StoredProceduresViewsTables
WebServer
DatabaseServer
PresentationTier
Client
ASP.NETWebForms
WebAppPresentationTier
Client
Client
ClientWinForms
3-tierArchitectureScenarios
Firewall
Clients
DesktopAppMobileApp
Internet
LocalNetwork
Note!ThedifferentTierscanbeonthesameComputer(LogicLayers)orondifferentComputers inanetwork(PhysicalLayers)
Android, iOS,Windows8/WindowsPhone,
etc.
PresentationTiers
DevicescansharethesameBusiness/LogicTierandAPIs
SeperatePresentationTierforeachDeviceApp
API
API
API
API
15
VisualStudioProjectsSolution withallProjects(LogicTier,WebService,DesktopApp,WebApp,MobileApp)
Solution withProjectsusedbyWebApp(LogicTier,WebApp)
DataTierWearegoingtocreatetheDatabase/DataLayer/Tier,including:1. Tables2. Views3. StoredProcedures4. Triggers5. Scriptforsome“Dummy”Data
DownloadZipFileswithTables,Views,StoredProceduresandTriggerseinordertocreatetheDataTierinSQLServer(TheZIPFileislocatedonthesameplaceasthisFile)
16
Note!Installtheminthisorder
CreateLogicTier
21
Database
PresentationTier
LogicTier
ASP.NETWebForms
DataTier
PresentationTier PresentationTier
WinForms WindowsStoreApp
Purpose:• AlltheAppsshould/could
sharethesameLogicTier• TomakeyourAppseasier
tomaintainandextend• etc.
25
CreatetheCode,e.g.,likethis(“StudentData.cs”):
CreateyourownNamespace
Improvements:UseTry...Catch...
AViewthatcollectsdatafromseveraltables
27
Code(“StudentData.cs”):using System.Data.SqlClient;using System.Data.SqlTypes;using System.Data;
namespace Tuc.School.LogicTier{
public class StudentData{
public DataSet GetStudentDB(string connectionString){
string selectSQL = "select StudentName, StudentNumber, SchoolName, ClassName, Grade from StudentData order by StudentName";
// Define the ADO.NET objects.SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter da = new SqlDataAdapter(selectSQL, con);
DataSet ds = new DataSet();da.Fill(ds);
return ds;
}}
}
28
CreateapropernamefortheAssembly (.dllFile)
ThiswillbetheAssembly foryourLogicTier,thatcanbeimportedandusedinotherprojects.Createonce– useitmanytimes!!
ThenBuildyourProject(hopefullywithnoerrors)
Right-clickon theProjectintheSolution ExplorerandselectProperties
30
PresentationLayerWebApp:ASP.NETWebForms
WewillcreateaWebFormlikethiswherethedatacomesfromourLogicTier
34
Codefor“Student.cs”using System;using System.Collections.Generic;using System.Linq;using System.Web;
using System.Data;
using Tuc.School.LogicTier;
namespace Tuc.School.WebApp{
public class Student{
public DataSet GetStudent(string connectionString){
StudentData studentData = new StudentData();
return studentData.GetStudentDB(connectionString);
}}
}
GetDatfromourLogicTier
Sinceweareusing theDataSetClass
OurLogicTier
36
CreateWebFormPage(“StudentInformation.aspx”)
GridView (Drag&DropfromToolboxorcreatecodein.aspxfile)
37
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StudentInformation.aspx.cs" Inherits="WebApp.StudentInformation" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">
<title>Student Information</title></head><body>
<form id="form1" runat="server"><div>
<h1>Student Information</h1>
</div><asp:GridView ID="gridStudentData" runat="server"></asp:GridView>
</form></body></html>
HTML/ASPXCode(“StudentInformation.aspx”)
38
CodebehindfortheWebForm(“StudentInformation.aspx.cs”)using System.Web.Configuration;using Tuc.School.WebApp;
namespace WebApp{
public partial class StudentInformation : System.Web.UI.Page{
private string connectionString = WebConfigurationManager.ConnectionStrings["SCHOOLConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e){
if (!IsPostBack){
FillStudentGrid();}
}
private void FillStudentGrid(){
DataSet ds = new DataSet();
Student studentList = new Student();
ds = studentList.GetStudent(connectionString);
gridStudentData.DataSource = ds;
gridStudentData.DataBind();}
}}
Note!
Web.Config
39
Storethe“ConnectionString”foryourDatabasein“Web.Config”
<?xml version="1.0" encoding="utf-8"?><!--For more information on how to configure your ASP.NET application, please visithttp://go.microsoft.com/fwlink/?LinkId=169433-->
<configuration>
<connectionStrings><add name="SCHOOLConnectionString" connectionString="Data Source=macwin8;Initial
Catalog=SCHOOL;Persist Security Info=True;User ID=sa;Password=xxxxxx"providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web><compilation debug="true" targetFramework="4.5" /><httpRuntime targetFramework="4.5" />
</system.web></configuration>
ThenyoucaneaslyswitchDatabssewithoutchangingtheCode!!
41
AdditionalExercise:
UpdateGridViewwithNewDatafromDatabase
GotoNewWebForminordertoAddanotherStudent
43
PresentationLayerDesktopApp:WinForms
PartA:WithoutWebServices(weassumetheAppwillbeusedonlyinthelocalLAN(orlocalonthesamecomputerwherethedatabaseislocated)andthatwehavedirectaccesstotheDatabase)
Label
DataGridView
47
CodeforClass“StudentWinForm.cs”
using System.Data;
using Tuc.School.LogicTier;
namespace Tuc.School.WinFormApp{
class StudentWinForm{
public DataSet GetStudent(string connectionString){
StudentData studentData = new StudentData();
return studentData.GetStudentDB(connectionString);}
}}
ReferencetoourLogicTier
Sinceweareusing theDataSetClass
OurDatabaseMethod inourLogicTier
50
using System.Configuration;using Tuc.School.WinFormApp;
namespace WinFormApp{
public partial class Form1 : Form{
private string connectionString = ConfigurationManager.ConnectionStrings["SCHOOLConnectionString"].ConnectionString;
public Form1(){
InitializeComponent();}
private void Form1_Load(object sender, EventArgs e){
FillStudentGrid();
}
private void FillStudentGrid(){
DataSet ds = new DataSet();
StudentWinForm studentList = new StudentWinForm();
ds = studentList.GetStudent(connectionString);
dataGridViewStudentInformation.DataSource = ds.Tables[0];
}}
}
WinFormCodeNote!
ConnectionString isstoredinApp.config
52
CreateDBConnectionStringinApp.config<?xml version="1.0" encoding="utf-8" ?><configuration>
<startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings><add name="SCHOOLConnectionString" connectionString="Data Source=macwin8;Initial Catalog=SCHOOL;Persist Security
Info=True;User ID=sa;Password=xxxxxx"providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
55
PresentationLayerDesktopApp:WinForms
PartB:UsingWebServices(weassumetheTheAppshould beusedonInternetoutsidetheFirewall)
Label
DataGridView
60
Deploy/PublishWebServicetoIIS
CopyWebServiceFiles(Project)todefaultIISDirectory:C:\inetpub\wwwroot
67
using System.Windows.Forms;
namespace WinFormAppWSClient{
public partial class FormWSClient : Form{
public FormWSClient(){
InitializeComponent();}
private void FormWSClient_Load(object sender, EventArgs e){
FillStudentGrid();}
private void FillStudentGrid(){
DataSet ds = new DataSet();
SchoolWSReference.SchoolWSSoapClient schoolWs = newSchoolWSReference.SchoolWSSoapClient();
ds = schoolWs.GetStudent();
dataGridViewStudentInformation.DataSource = ds.Tables[0];
}}
WinFormCode
CalltheWebServicemethod
FillGridView
Hans-PetterHalvorsen,M.Sc.
UniversityCollegeofSoutheastNorwaywww.usn.no
E-mail:[email protected]:http://home.hit.no/~hansha/