12. Capa Web MiniBank. (2010-06-06)sabia.tic.udc.es/docencia/is/docs/transparencias/12... · It d...

Post on 12-Mar-2020

1 views 0 download

Transcript of 12. Capa Web MiniBank. (2010-06-06)sabia.tic.udc.es/docencia/is/docs/transparencias/12... · It d...

Caso de Estudio: Diseño e Implementación de la Capa Web de MiniBankla Capa Web de MiniBank

Integración de SistemasParte II Diseño e implementación deParte II. Diseño e implementación de aplicaciones Web con .NET

I t d ióIntroducción

I t d ióIntroducción

E t t d t di l di ñ i l t ió d l En este apartado estudiaremos el diseño e implementación de las capas controlador y vista de MiniBank

Configuración de la aplicación Web Configuración de la aplicación Web

Página maestra de MiniBank

Un ejemplo de una acción que realiza una operación que no visualiza Un ejemplo de una acción que realiza una operación que no visualiza resultados Transferencia bancaria

Un ejemplo de una acción que realiza una operación y visualiza el resultado de la operación Búsqueda de cuentas bancarias por identificador de cuenta (resultado en

una página) o de usuario (resultado en varias páginas)

Internacionalización

C fi ió Gl b lConfiguración: Global.asax

namespace Es Udc DotNet MiniBanknamespace Es.Udc.DotNet.MiniBank{

public class Global : System.Web.HttpApplication{

protected void Application Start(object sender, EventArgs e)protected void Application_Start(object sender, EventArgs e){

IUnityContainer container = new UnityContainer();UnityConfigurationSection section =

(UnityConfigurationSection)ConfigurationManager.GetSection("unity");section.Containers.Default.Configure(container);

Application["UnityContainer"] = container;

LogManage Reco dMessage("Unit Containe loaded "LogManager.RecordMessage("Unity Container loaded.",LogManager.MessageType.INFO);

}

<<...>><<...>>

}

C fi ió W b fiConfiguración: Web.config

<system.web>

<!-- Cultural preferences of the Web site --><globalization culture="auto" uiCulture="auto" />

<!-- Valid Options: UseUri (True), UseCookies (False), AutoDetect --><sessionState cookieless="AutoDetect" timeout="30" />

<! V lid O ti O Off R t O l ><!-- Valid Options: On, Off, RemoteOnly --><customErrors mode="RemoteOnly" defaultRedirect="/Errors/InternalError.aspx"></customErrors>

<<...>><<...>>

</system.web>

<!-- Unity configuration block --><unity>

<< Identico a App.config en MiniBank (model)>>

</unity>

C fi ió W b fiConfiguración: Web.config

<applicationSettings><Es.Udc.DotNet.MiniBank.Properties.Settings>

<setting name="MiniBank_defaultCount" serializeAs="String"><value>2</value>

</setting>

<setting name="MiniBank_applicationURL" serializeAs="String">< l >htt //l lh t 8081/Mi iB k</ l ><value>http://localhost:8081/MiniBank</value>

</setting>

</Es.Udc.DotNet.MiniBank.Properties.Settings></applicationSettings></applicationSettings>

C fi ió W b fiConfiguración: Web.config

Configurable desde de forma gráfica en VS desde la pestaña Settings en la Configurable desde de forma gráfica en VS desde la pestaña Settings en la propiedades del proyecto

C fi ió t iConfiguración: otras opciones

Mi iB k M t Vi t d di ñMiniBank.Master: Vista de diseño

Mi iB k M t Vi t d ódiMiniBank.Master: Vista de código

<%@ M t L "C#" A t E tWi "t " C d B hi d "Mi iB k t "<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MiniBank.master.cs"Inherits="Es.Udc.DotNet.MiniBank.Web.MiniBank" %>

<!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>MiniBank</title>t t e a /t t e<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/><link href="~/Img/MiniBank.ico" rel="Shortcut Icon" /><link href="~/Css/MiniBank.Styles.css" rel="stylesheet" type="text/css" />

</head>

<body><div id="window">

<!-- Body Header. --><div id="header">

<asp:Localize ID="lclHeader" runat="server" meta:resourcekey="lclHeader" /></div>

Mi iB k M t Vi t d ódiMiniBank.Master: Vista de código<!-- Main Content. --><div id="pageBody"><div id= pageBody >

<div id="sidebar"><ul>

<li><asp:HyperLink ID="lnkHome" runat="server"meta:resourcekey="lnkHome"NavigateUrl="~/Pages/MainPage.aspx" />

</li>

<<...>>

</ul></div><div id="content">

<asp:ContentPlaceHolder ID="ContentPlaceHolderMain" runat="server"><asp:ContentPlaceHolder ID ContentPlaceHolderMain runat server ></asp:ContentPlaceHolder>

</div></div><!-- Footer. -->di id "f t "<div id="footer">

<asp:Localize ID="lclFooter" runat="server" meta:resourcekey="lclFooter" /></div>

</div></body></html>

Mi iB k M tMiniBank.Master.cs

using System;namespace Es.Udc.DotNet.MiniBank.Web{

public partial class MiniBank : System.Web.UI.MasterPagepublic partial class MiniBank : System.Web.UI.MasterPage{

protected void Page_Load(object sender, EventArgs e){}

}}}

Mi iB k M t d iMiniBank.Master.designer.cs

namespace Es.Udc.DotNet.MiniBank.Web {p

public partial class MiniBank {

protected global::System.Web.UI.WebControls.Localize lclHeader;

protected global::System.Web.UI.WebControls.HyperLink lnkHome;

protected global::System.Web.UI.WebControls.HyperLink lnkCreate;

<<...>>

protected global::System.Web.UI.WebControls.ContentPlaceHolderContentPlaceHolderMain;

protected global::System.Web.UI.WebControls.Localize lclFooter;}

}

T f iTransferencia

Transfer.aspxTransfer.aspx

SuccessfulOperation aspxSuccessfulOperation.aspx

T f i (Vi t d di ñ )Transferencia: Transfer.aspx (Vista de diseño)

T f iTransferencia: Transfer.aspx.designer.cs

namespace Es.Udc.DotNet.MiniBank {

public partial class Transfer {

d l b l S b lC l l fprotected global::System.Web.UI.HtmlControls.HtmlForm TransferForm;

protected global::System.Web.UI.WebControls.Localize lclSourceAccId;protected global::System.Web.UI.WebControls.Localize lclDestinationAccId;protected global::System.Web.UI.WebControls.Localize lclAmount;

protected global::System.Web.UI.WebControls.TextBox txtSourceAccId;protected global::System.Web.UI.WebControls.TextBox txtDestinationAccId;protected global::System.Web.UI.WebControls.TextBox txtAmount;

protected global::System.Web.UI.WebControls.Label lblSourceAccError;protected global::System.Web.UI.WebControls.Label lblDestinationAccError;protected global::System.Web.UI.WebControls.Label lblAmountError;

T f iTransferencia: Transfer.aspx.designer.cs

protected global::System.Web.UI.WebControls.RequiredFieldValidatorrfvSourceAccId;

protected global::System.Web.UI.WebControls.RequiredFieldValidatorf i i drfvDestinationAccId;

protected global::System.Web.UI.WebControls.RequiredFieldValidatorrfvBalance;

protected global::System.Web.UI.WebControls.RegularExpressionValidatortypeSourceAccIdValidator;

protected global::System.Web.UI.WebControls.RegularExpressionValidatortypeDestinationAccId;

protected global::System.Web.UI.WebControls.RegularExpressionValidatortypeAmountValidator;typeAmountValidator;

protected global::System.Web.UI.WebControls.Button btnTransfer;}

}

Transferencia f (Vista de código)Transferencia: Transfer.aspx (Vista de código)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Transfer.aspx.cs"g g g p pInherits="Es.Udc.DotNet.MiniBank.Web.Pages.Transfer" MasterPageFile="~/MiniBank.Master"%>

<asp:Content ID="content" ContentPlaceHolderID="ContentPlaceHolderMain" runat="server">p<div id="form">

<form id="TransferForm" method="post" runat="server">

<div class="field"><span class="label">

<asp:Localize ID="lclSourceAccId" runat="server"meta:resourcekey="lclSourceAccId" /></span>

<span class="entry"><asp:TextBox ID="txtSourceAccId" runat="server" Width="200px"

Columns="16"></asp:TextBox>

<asp:RegularExpressionValidator ID="typeSourceAccIdValidator"runat="server" ControlToValidate="txtSourceAccId" Text="<%$ Resources: Common, typeError %>" ValidationExpression="(\d)*"CssClass="errorMessage" Display="Dynamic">

</asp:RegularExpressionValidator>

Transferencia f (Vista de código)Transferencia: Transfer.aspx (Vista de código)

<asp:RequiredFieldValidator ID="rfvSourceAccId" runat="server"ControlToValidate="txtSourceAccId" Display="Dynamic"Text="<%$ Resources: Common, mandatoryField %>" CssClass="errorMessage">

</asp:RequiredFieldValidator>

<asp:Label ID="lblSourceAccError" runat="server"CssClass="errorMessage" meta:resourcekey="lblSourceAccError">

</asp:Label></span>

</div>

<<...>>

<div class="button"><asp:Button ID="btnTransfer" runat="server" meta:resourcekey="btnTransfer"

O Cli k "bt T f Cli k" /OnClick="btnTransfer_Click" /></div>

</form></div></ C t t></asp:Content>

T f iTransferencia: Transfer.aspx.cs

public partial class Transfer : SpecificCulturePage{

protected void Page_Load(object sender, EventArgs e){

lblSourceAccError.Visible = false;lblDestinationAccError.Visible = false;lblAmountError.Visible = false;

}

protected void btnTransfer_Click(object sender, EventArgs e){

/* Get data. */long sourceAccountIdentifier =

Convert.ToInt32(txtSourceAccId.Text);long destinationAccountIdentifier =

Convert.ToInt32(txtDestinationAccId.Text);d bl tdouble amount =

Convert.ToInt64(txtAmount.Text);

T f iTransferencia: Transfer.aspx.cs

/* Transfer. */try{

/* Get the Service */IUnityContainer container =

(IUnityContainer)Application["unityContainer"];

IAccountService accountService = container.Resolve<IAccountService>();

accountService.Transfer(sourceAccountIdentifier, destinationAccountIdentifier, amount);

Response.Redirect(Response.ApplyAppPathModifier("./SuccessfulOperation.aspx"));

}

T f iTransferencia: Transfer.aspx.cs

catch (InstanceNotFoundException ex){

long key = (long)ex.Key;

/* Process errors and show labels */if (key.Equals(sourceAccountIdentifier))

lblSourceAccError.Visible = true;else

lblDestinationAccError.Visible = true;}catch (InsufficientBalanceException ex){

String labelText = String.Format((string)GetLocalResourceObject("lblAmountError.Text"),ex.CurrentBalance);

lblA tE T t l b lT tlblAmountError.Text = labelText;lblAmountError.Visible = true;

}}

}}

Bú d d t id tifi d d tBúsqueda de cuentas por identificador de cuenta

FindAccounts aspxFindAccounts.aspx

ShowAccountByAccID aspxShowAccountByAccID.aspx

Bú d d t id tifi d d iBúsqueda de cuentas por identificador de usuarioFindAccounts.aspx

ShowAccountsByUserID.aspx

Búsqueda de cuentas:Búsqueda de cuentas: FindAccounts.aspx (Vista de diseño)

Búsqueda de cuentas:Búsqueda de cuentas: FindAccounts.aspx (Vista de código)<asp:Content ID="content1" ContentPlaceHolderID="ContentPlaceHolderMain"p

runat="server"><div id="form">

<form id="FindForm" method="post" runat="server"><div class="field">

<span class="label"><span class= label ><asp:Localize ID="lclIdentifier" runat="server"

meta:resourcekey="lblIdentifier" /></span><span class="entry">

i i i 200<asp:TextBox ID="txtIdentifier" runat="server" Width="200px"Columns="16" />

<asp:RegularExpressionValidator ID="typeValidator" runat="server"ControlToValidate="txtIdentifier" ValidationExpression="(\d)*"Text="<%$ Resources: Common, typeError %>" Display="Dynamic"yp p y yCssClass="errorMessage" />

<asp:RequiredFieldValidator ID="rfvIdentifier" runat="server"ControlToValidate="txtIdentifier" Display="Dynamic"Text="<%$ Resources: Common, mandatoryField %>"CssClass="errorMessage" />CssClass= errorMessage />

<asp:Label CssClass="errorMessage" ID="lblIdentifierError"runat="server" meta:resourcekey="lblIdentifierError" />

</span></div>

Búsqueda de cuentas:Búsqueda de cuentas: FindAccounts.aspx (Vista de código)

<div class="field">div class field<span class="label">

<asp:Localize ID="lclFindBy" runat="server"meta:resourcekey="lclFindBy" />

</span>/ p<span class="entry">

<asp:DropDownList ID="ddlFindBy" runat="server" Width="200px"><asp:ListItem Value="accID"

Text="<%$ Resources:Common, accId %>" /><asp:ListItem Value="userID"

Text="<%$ Resources:Common, userId %>" /></asp:DropDownList>

</span></div><div class="button">

<asp:Button ID="btnFind" runat="server" meta:resourcekey="btnFind"OnClick="btnFind_Click" />

</div></form>

</div></asp:Content>

Bú d d t Fi dA tBúsqueda de cuentas: FindAccounts.aspx.cs

public partial class FindAccounts : SpecificCulturePagepublic partial class FindAccounts : SpecificCulturePage{

protected void Page_Load(object sender, EventArgs e){

lblIdentifierError.Visible = false;}

protected void btnFind_Click(object sender, EventArgs e){

/* Get data. *// /String identifierType = this.ddlFindBy.SelectedValue;Int32 identifier = Convert.ToInt32(this.txtIdentifier.Text);

/* Do action. */if (identifierType == "accID")if (identifierType == accID ){

FindAccountByAccountIdentifier(identifier);}else{

String url = String.Format("./ShowAccountsByUserID.aspx?userID={0}",

identifier);Response.Redirect(Response.ApplyAppPathModifier(url));p p pp y pp

}}

Bú d d t Fi dA tBúsqueda de cuentas: FindAccounts.aspx.cs

private void FindAccountByAccountIdentifier(long accountIdentifier){

try{

<< Get the Service >>

/* Get Account Data */Account account = accountService.FindAccount(accountIdentifier);

/* Attach data to context *// Attach data to context /Context.Items.Add("account", account);

/* Transfer to visualization WebForm */Server.Transfer(Response.

i i /ApplyAppPathModifier("./ShowAccountByAccID.aspx"));}catch (InstanceNotFoundException){

lblIdentifierError.Visible = true;}

}}

Búsqueda de cuentas:Búsqueda de cuentas: ShowAccountByAccID.aspx (Vista de diseño)

Búsqueda de cuentas:Búsqueda de cuentas: ShowAccountByAccID.aspx (Vista de código)

<asp:Content ID="content1" ContentPlaceHolderID="ContentPlaceHolderMain"<asp:Content ID content1 ContentPlaceHolderID ContentPlaceHolderMainrunat="server">

<asp:Table CssClass="accountDetails" ID="TableAccountInfo" runat="server">

<asp:TableRow runat="server"><asp:TableRow runat= server ><asp:TableHeaderCell ID="cellCaptionAccountID" runat="server"

Text="<%$ Resources:Common, accId %>"></asp:TableHeaderCell><asp:TableCell ID="cellAccountID" runat="server"></asp:TableCell>

</asp:TableRow>

<asp:TableRow runat="server"><asp:TableHeaderCell ID="cellCaptionUserID" runat="server"

Text="<%$ Resources:Common, userId %>"></asp:TableHeaderCell><asp:TableCell ID="cellUserID" runat="server"></asp:TableCell>

</asp:TableRow>

<asp:TableRow runat="server"><asp:TableHeaderCell ID="cellCaptionBalance" runat="server"

Text="<%$ Resources:Common, balance %>"></asp:TableHeaderCell>, p<asp:TableCell ID="cellBalance" runat="server"></asp:TableCell>

</asp:TableRow>

</asp:Table>

</asp:Content>

Bú d d t Sh A tB A IDBúsqueda de cuentas: ShowAccountByAccID.aspx.cs

protected void Page_Load(object sender, EventArgs e){

Account account = (Account)Context.Items["account"];

icellAccountID.Text = account.accId.ToString();cellUserID.Text = account.usrId.ToString();cellBalance.Text = account.balance.ToString();

}

Búsqueda de cuentas:Búsqueda de cuentas: ShowAccountsByUserID.aspx (Vista de diseño)

Búsqueda de cuentas:Búsqueda de cuentas: ShowAccountsByUserID.aspx (Vista de código)

<asp:Content ID="content1" ContentPlaceHolderID="ContentPlaceHolderMain"runat="server">

<form runat="server"><p>p

<asp:Label ID="lblNoUserAccounts" meta:resourcekey="lblNoUserAccounts"runat="server">

</asp:Label></p>

<asp:GridView ID="gvUserAccounts" runat="server" CssClass="userAccounts"GridLines="None" AutoGenerateColumns="False">

<Columns><asp:BoundField DataField="accId"

$ /HeaderText="<%$ Resources:Common, accId %>" /><asp:BoundField DataField="balance"

HeaderText="<%$ Resources:Common, balance %>" /></Columns>

</asp:GridView>

</form>

Búsqueda de cuentas:Búsqueda de cuentas: ShowAccountsByUserID.aspx (Vista de código)

<!-- "Previous" and "Next" links. --><div class="previousNextLinks">

<span class="previousLink"><asp:HyperLink ID="lnkPrevious" Text="<%$ Resources:Common, Previous %>"

runat="server" Visible="False"></asp:HyperLink>

</span><span class="nextLink">

i %$ %<asp:HyperLink ID="lnkNext" Text="<%$ Resources:Common, Next %>"runat="server" Visible="False">

</asp:HyperLink></span>

</di ></div>

</asp:Content>

Bú d d tBúsqueda de cuentas: ShowAccountsByUserID.aspx.cs

protected void Page_Load(object sender, EventArgs e){

int startIndex, count;

lnkPrevious Visible = false;lnkPrevious.Visible = false;lnkNext.Visible = false;lblNoUserAccounts.Visible = false;

/* Get User Identifier passed as parameter in the request from * th i* the previous page */long userID = Convert.ToInt32(Request.Params.Get("userID"));

/* Get Start Index */try{

startIndex = Int32.Parse(Request.Params.Get("startIndex"));}catch (ArgumentNullException)g p{

startIndex = 0;}

Bú d d tBúsqueda de cuentas: ShowAccountsByUserID.aspx.cs

/* Get Count *// Get Count /try{

count = Int32.Parse(Request.Params.Get("count"));}catch (ArgumentNullException)catch (ArgumentNullException){

count = Settings.Default.MiniBank_defaultCount;}

<< G t th S i >><< Get the Service >>IUnityContainer container = ...

/* Get Accounts Info */List<Account> accounts =

accountService.FindAccountsByUserIdentifier(userID, startIndex, count);

if (accounts.Count == 0){

lblNoUserAccounts.Visible = true;return;

}

Bú d d tBúsqueda de cuentas: ShowAccountsByUserID.aspx.cs

this.gvUserAccounts.DataSource = accounts;this.gvUserAccounts.DataBind();

/* Get the number of accounts in order to manage the previous * and next links */int numberOfAccounts = accountService.GetNumberOfAccounts(userID);

/* "Previous" link */if ((startIndex - count) >= 0){

String url = Settings.Default.MiniBank_applicationURL +"/ShowAccountsByUserID.aspx" + "?userID=" + userID +"&startIndex=" + (startIndex - count) + "&count=" + count;

this.lnkPrevious.NavigateUrl = Response.ApplyAppPathModifier(url);p pp y pp

this.lnkPrevious.Visible = true;}

Bú d d tBúsqueda de cuentas: ShowAccountsByUserID.aspx.cs

/* "Next" link */if ((startIndex + count) < numberOfAccounts){

String url = Settings.Default.MiniBank_applicationURL +"/ShowAccountsByUserID aspx" + "?userID=" + userID +/ShowAccountsByUserID.aspx + ?userID= + userID +"&startIndex=" + (startIndex + count) + "&count=" + count;

this.lnkNext.NavigateUrl = Response.ApplyAppPathModifier(url);

thi l kN t Vi ibl tthis.lnkNext.Visible = true;}

}

S l ió d idi íSelección de idioma y país

SetLocale.aspxp

Selección de idioma y país: Se ecc ó de d o a y pa sSetLocale.aspx.csprotected void Page Load(object sender, EventArgs e)protected void Page_Load(object sender, EventArgs e){

String language;String country;

if (!I P tB k)if (!IsPostBack){

/* * We check if exists a locale in the session. In this case, * we get the language and the region/country from the locale.* Other case we use the browser preferences to extract the* language and the region/country*/

if (!SessionManager.IsLocaleDefined(Context)){{

/* Gets preferred language from browser */language = GetLanguageFromBrowserPreferences();country = GetCountryFromBrowserPreferences();

}

Selección de idioma y país: Se ecc ó de d o a y pa sSetLocale.aspx.cs

lelse{

Locale locale = SessionManager.GetLocale(Context);language = locale.Language;country = locale.Country;

}

/* Finally we update de data of the "Combo", using the* selected language and region/country.*//

UpdateComboLanguage(language);UpdateComboCountry(language, country);

}}

Selección de idioma y país: Se ecc ó de d o a y pa sSetLocale.aspx.cs

private String GetLanguageFromBrowserPreferences(){

String language;CultureInfo cultureInfo =

C lt I f C t S ifi C lt (R t U L [0])CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]);language = cultureInfo.TwoLetterISOLanguageName;return language;

}

Selección de idioma y país: Se ecc ó de d o a y pa sSetLocale.aspx.cs

private String GetCountryFromBrowserPreferences(){

String country;CultureInfo cultureInfo =

CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]);

if (cultureInfo.IsNeutralCulture){

t ""country = "";}else{

// c lt reInfoName is something like en US// cultureInfoName is something like en-USString cultureInfoName = cultureInfo.Name;// Gets the last two caracters of cultureInfonamecountry =

cultureInfoName Substring(cultureInfoName Length 2);cultureInfoName.Substring(cultureInfoName.Length - 2);}return country;

}

Selección de idioma y país: Se ecc ó de d o a y pa sSetLocale.aspx.cs

private void UpdateComboCountry(String selectedLanguage, String selectedCountry)

{this.comboCountry.DataSource =

Countries.GetCountries(selectedLanguage);this.comboCountry.DataTextField = "value";this.comboCountry.DataValueField = "text";this.comboCountry.DataBind();thi b C t S l t dV l l t dC tthis.comboCountry.SelectedValue = selectedCountry;

}

private void UpdateComboLanguage(String selectedLanguage){{

this.comboLanguage.DataSource = Languages.GetLanguages(selectedLanguage);

this.comboLanguage.DataTextField = "value";this comboLanguage DataValueField = "text";this.comboLanguage.DataValueField = text ;this.comboLanguage.DataBind();this.comboLanguage.SelectedValue = selectedLanguage;

}

Selección de idioma y país: Se ecc ó de d o a y pa sSetLocale.aspx.cs

protected void btnSetLocale_Click(object sender, EventArgs e){

string language = comboLanguage.SelectedValue;string country = comboCountry.SelectedValue;

Locale locale = new Locale(language, country);

SessionManager.SetLocale(Context, locale);

Response.Redirect(Response.ApplyAppPathModifier("~/MainPage.aspx"));

}

protected void comboLanguage_SelectedIndexChanged(object sender, EventArgs e)

{/* After a language change the countries are printed in the/* After a language change, the countries are printed in the* correct language.

*/this.UpdateComboCountry(comboLanguage.SelectedValue,

comboCountry SelectedValue);comboCountry.SelectedValue);}