Caso de Estudio: Diseño e Implementación de la Capa Web de MiniBank Integración de Sistemas Parte II Diseño e implementación de Parte II. Diseño e implementación de aplicaciones Web con.net
Introducción
Introducción En este apartado estudiaremos el diseño e implementación ió de las capas controlador y vista de MiniBank 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 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
Configuración: ió Global.asax l namespace Es.Udc.DotNet.MiniBank public class Global : System.Web.HttpApplication 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; LogManager.RecordMessage("Unity Container loaded.", LogManager.MessageType.INFO); <<...>>
Configuración: ió 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" /> <!-- 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>
Configuración: ió 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"> <value>http://localhost:8081/minibank</value> lh t ib l > </setting> </Es.Udc.DotNet.MiniBank.Properties.Settings> </applicationsettings>
Configuración: ió 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
Configuración: ió otras opciones
MiniBank.Master: ib M Vista de diseño
MiniBank.Master: ib M Vista de código <%@ Master Language="C#" AutoEventWireup="true" twi " CodeBehind="MiniBank.master.cs" d ib " 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 <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>
MiniBank.Master: ib M Vista de código <!-- Main Content. --> <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> </div> </div> <!-- Footer. --> <div id="footer"> " <asp:localize ID="lclFooter" runat="server" meta:resourcekey="lclfooter" /> </div> </div> </body> </html>
MiniBank.Master.csiB M using System; namespace Es.Udc.DotNet.MiniBank.Web public partial class MiniBank : System.Web.UI.MasterPage protected void Page_Load(object sender, EventArgs e)
MiniBank.Master.designer.csiB M i namespace Es.Udc.DotNet.MiniBank.Web 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.contentplaceholder ContentPlaceHolderMain; protected global::system.web.ui.webcontrols.localize lclfooter;
Transferencia Transfer.aspx SuccessfulOperation.aspxaspx
Transferencia: Transfer.aspx (Vista de diseño)
Transferencia: Transfer.aspx.designer.cs namespace Es.Udc.DotNet.MiniBank public partial class Transfer protected global::system.web.ui.htmlcontrols.htmlform l b lc l l 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;
Transferencia: Transfer.aspx.designer.cs protected global::system.web.ui.webcontrols.requiredfieldvalidator rfvsourceaccid; protected global::system.web.ui.webcontrols.requiredfieldvalidator rfvdestinationaccid; i protected global::system.web.ui.webcontrols.requiredfieldvalidator rfvbalance; protected global::system.web.ui.webcontrols.regularexpressionvalidator typesourceaccidvalidator; protected global::system.web.ui.webcontrols.regularexpressionvalidator typedestinationaccid; protected global::system.web.ui.webcontrols.regularexpressionvalidator typeamountvalidator; protected global::system.web.ui.webcontrols.button btntransfer;
Transferencia: Transfer.aspx (Vista de código) <%@ Page Language="C#" g AutoEventWireup="true" CodeBehind="Transfer.aspx.cs" Inherits="Es.Udc.DotNet.MiniBank.Web.Pages.Transfer" MasterPageFile="~/MiniBank.Master" %> <asp:content ID="content" ContentPlaceHolderID="ContentPlaceHolderMain" runat="server"> <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: 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" OnClick="btnTransfer_Click" k" /> </div> </form> </div> </asp:content> t>
Transferencia: 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); double amount = Convert.ToInt64(txtAmount.Text);
Transferencia: 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"));
Transferencia: 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); lblamounterror.text t = labeltext; lt lblamounterror.visible = true;
Búsqueda de cuentas por identificador d de cuenta FindAccounts.aspx ShowAccountByAccID.aspx
Búsqueda de cuentas por identificador d de usuario FindAccounts.aspx ShowAccountsByUserID.aspx
Búsqueda de cuentas: Búsqueda de cuentas: FindAccounts.aspx (Vista de diseño)
Búsqueda de cuentas: FindAccounts.aspx (Vista de código) <asp:content ID="content1" ContentPlaceHolderID="ContentPlaceHolderMain" runat="server"> <div id="form"> <form id="findform" method="post" runat="server"> <div class="field"> <span class="label"> label <asp:localize ID="lclIdentifier" runat="server" meta:resourcekey="lblidentifier" /> </span> <span class="entry"> <asp:textbox ID="txtIdentifier" i runat="server" Width="200px" Columns="16" /> <asp:regularexpressionvalidator ID="typeValidator" runat="server" ControlToValidate="txtIdentifier" ValidationExpression="(\d)*" Text="<%$ Resources: Common, typeerror %>" Display="Dynamic" y CssClass="errorMessage" /> <asp:requiredfieldvalidator ID="rfvIdentifier" runat="server" ControlToValidate="txtIdentifier" Display="Dynamic" Text="<%$ Resources: Common, mandatoryfield %>" CssClass="errorMessage" /> <asp:label CssClass="errorMessage" ID="lblIdentifierError" runat="server" meta:resourcekey="lblidentifiererror" /> </span> </div>
Búsqueda de cuentas: FindAccounts.aspx (Vista de código) <div class="field"> <span class="label"> <asp:localize ID="lclFindBy" runat="server" meta:resourcekey="lclfindby" /> </span> <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úsqueda de cuentas: FindAccounts.aspx.cs public 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") FindAccountByAccountIdentifier(identifier); else String url = String.Format("./ShowAccountsByUserID.aspx?userID=0", identifier); Response.Redirect(Response.ApplyAppPathModifier(url)); p pp pp
Bú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 */ Context.Items.Add("account", account); /* Transfer to visualization WebForm */ Server.Transfer(Response. ApplyAppPathModifier("./ShowAccountByAccID.aspx")); i catch (InstanceNotFoundException) lblidentifiererror.visible = true;
Búsqueda de cuentas: Búsqueda de cuentas: ShowAccountByAccID.aspx (Vista de diseño)
Búsqueda de cuentas: ShowAccountByAccID.aspx (Vista de código) <asp:content ID="content1" ContentPlaceHolderID="ContentPlaceHolderMain" ContentPlaceHolderMain runat="server"> <asp:table CssClass="accountDetails" ID="TableAccountInfo" 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> <asp:tablecell ID="cellBalance" runat="server"></asp:tablecell> </asp:tablerow> </asp:table> </asp:content>
Búsqueda de cuentas: ShowAccountByAccID.aspx.cs A protected void Page_Load(object sender, EventArgs e) Account account = (Account)Context.Items["account"]; cellaccountid.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: ShowAccountsByUserID.aspx (Vista de código) <asp:content ID="content1" ContentPlaceHolderID="ContentPlaceHolderMain" runat="server"> <form runat="server"> <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: 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"> <asp:hyperlink ID="lnkNext" Text="<%$ Resources:Common, Next %>" runat="server" Visible="False"> </asp:hyperlink> </span> </div> </asp:content>
Búsqueda de cuentas: ShowAccountsByUserID.aspx.cs protected void Page_Load(object sender, EventArgs e) int startindex, count; lnkprevious.visible = false; lnknext.visible = false; lblnouseraccounts.visible = false; /* Get User Identifier passed as parameter in the request from * the previous page */ long userid = Convert.ToInt32(Request.Params.Get("userID")); /* Get Start Index */ try startindex = Int32.Parse(Request.Params.Get("startIndex")); catch (ArgumentNullException) startindex = 0;
Búsqueda de cuentas: ShowAccountsByUserID.aspx.cs /* Get Count */ try count = Int32.Parse(Request.Params.Get("count")); catch (ArgumentNullException) count = Settings.Default.MiniBank_defaultCount; << 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ú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); pp pp this.lnkprevious.visible = true;
Búsqueda de cuentas: ShowAccountsByUserID.aspx.cs /* "Next" link */ if ((startindex + count) < numberofaccounts) String url = Settings.Default.MiniBank_applicationURL + "/ShowAccountsByUserID.aspx aspx" + "?userid=" + userid + "&startindex=" + (startindex + count) + "&count=" + count; this.lnknext.navigateurl = Response.ApplyAppPathModifier(url); this.lnknext.visible t ibl = true;
Selección de idioma y país SetLocale.aspx
Selección ecc de idioma y país: SetLocale.aspx.cs 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 ecc de idioma y país: SetLocale.aspx.cs else 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 ecc de idioma y país: SetLocale.aspx.cs private String GetLanguageFromBrowserPreferences() String language; CultureInfo cultureinfo = CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]); C t C t language = cultureinfo.twoletterisolanguagename; return language;
Selección ecc de idioma y país: SetLocale.aspx.cs private String GetCountryFromBrowserPreferences() String country; CultureInfo cultureinfo = CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]); if (cultureinfo.isneutralculture) country = ""; else // cultureinfoname is something like en-us String cultureinfoname = cultureinfo.name; // Gets the last two caracters of cultureinfoname country = cultureinfoname.substring(cultureinfoname.length - 2); return country;
Selección ecc de idioma y país: SetLocale.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(); this.combocountry.selectedvalue t t l = selectedcountry; t private void UpdateComboLanguage(String selectedlanguage) this.combolanguage.datasource = Languages.GetLanguages(selectedLanguage); this.combolanguage.datatextfield = "value"; this.combolanguage.datavaluefield = "text"; this.combolanguage.databind(); this.combolanguage.selectedvalue = selectedlanguage;
Selección ecc de idioma y país: SetLocale.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 * correct language. */ this.updatecombocountry(combolanguage.selectedvalue, combocountry.selectedvalue);