Base de Dados Sales.mdb Tabelas: Customers (CustomerID, Name, Address, PhoneNb, FaxNb, EMail) Products (ProductID, Description, UnitPrice, StockQtd) Sales (SaleID, CustomerID, DateOfSale) SaleDetails (SaleID, Quantity, productid, TotalCost) Users (UserID, User, Pass) ------------------------------------------------------------------------------- Criação da página Inserir.aspx Layout > Insert Table > Colmns = 5; Rows = 2 > OK. Source code: <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Inserir.aspx.cs" Inherits="Inserir" Title="Untitled Page" %> <asp:content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<table> <asp:label ID="Label1" runat="server" Text="Nome:"></asp:Label></td> <asp:textbox ID="TextBox1" runat="server"></asp:textbox></td> <asp:label ID="Label2" runat="server" Text="Morada:"></asp:Label></td> <asp:textbox ID="TextBox2" runat="server"></asp:textbox></td> <asp:label ID="Label3" runat="server" Text="Telefone:"></asp:Label></td> <asp:textbox ID="TextBox3" runat="server"></asp:textbox></td> <asp:label ID="Label4" runat="server" Text="Fax:"></asp:Label></td> <asp:textbox ID="TextBox4" runat="server"></asp:textbox></td> <asp:label ID="Label5" runat="server" Text="E-mail:"></asp:Label></td> <asp:textbox ID="TextBox5" runat="server"></asp:textbox></td> </table> <br /> <asp:label ID="Label6" runat="server" Text="Registo Inserido" Visible="False"></asp:Label> <br /><br /> <asp:button ID="Button1" runat="server" OnClick="Button1_Click" Text="Inserir" /><br /> </asp:content> Inserir.aspx.cs public partial class Inserir : System.Web.UI.Page protected void Page_Load(object sender, EventArgs e) ConnectionStringSettingsCollection connectionstrings = ConfigurationManager.ConnectionStrings;
ShopClassLibrary.DBPath.DB = connectionstrings["salesconnectionstring"].tostring(); Label6.Visible = false; protected void Button1_Click(object sender, EventArgs e) // Código sem validação dos campos try ShopClassLibrary.ShopStatusEnum status; string user = "admin"; string pass = "admin"; string nome = TextBox1.Text; string endereco = TextBox2.Text; string telefone = TextBox3.Text; string fax = TextBox4.Text; string email = TextBox5.Text; ShopClassLibrary.ICustomer cliente = ShopClassLibrary.Factory.CreateCustomerService(); long id = cliente.add(user, pass, nome, endereco, telefone, fax, email, out status); TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; TextBox4.Text = ""; TextBox5.Text = ""; Label6.Visible = true; catch (SystemException) Ficheiro Customer.cs public interface ICustomer: long Add(string user, string pass, string name, string address, string phone, string fax, string email, out ShopStatusEnum status); internal class Customer : ICustomer public long Add(string user, string pass, string name, string address, string phone, string fax, string email, out ShopStatusEnum status) long customerid = -1; OleDbConnection conn = null; // validar dados de entrada if (name == null name.trim().length == 0) status = ShopStatusEnum.INVALID_ARGUMENT; return -1; try
conn = new OleDbConnection(UtilDB.CONN); conn.open(); // validar o utilizador status = UtilDB.ValidateUser(conn, null, user, pass); if (status!= ShopStatusEnum.OK) return -1; // criar comando SQL a executar string sqlcmd = "INSERT INTO Customers (Name, Address, PhoneNb, FaxNb, EMail) Values (?,?,?,?,?)"; OleDbCommand cmd = new OleDbCommand(sqlCmd, conn); cmd.parameters.addwithvalue("name", name); if (address.length == 0) cmd.parameters.addwithvalue("address", DBNull.Value); else cmd.parameters.addwithvalue("address", address); if (phone.length == 0) cmd.parameters.addwithvalue("phone", DBNull.Value); else cmd.parameters.addwithvalue("phone", phone); if (fax.length == 0) cmd.parameters.addwithvalue("fax", DBNull.Value); else cmd.parameters.addwithvalue("fax", fax); if (email.length == 0) cmd.parameters.addwithvalue("email", DBNull.Value); else cmd.parameters.addwithvalue("email", email); // executar o comando int linhasinseridas = cmd.executenonquery(); // verificar o resultado if (linhasinseridas == 0) status = ShopStatusEnum.NOT_OK; // nao inseriu else // inseriu registo // obter codigo do novo id gerado pela base de dados OleDbCommand idcmd = new OleDbCommand("SELECT @@IDENTITY", conn); customerid = (int)idcmd.executescalar(); status = ShopStatusEnum.OK; catch (OleDbException) status = ShopStatusEnum.ERROR; finally // fechar a conexão if (conn!= null && conn.state == ConnectionState.Open) conn.close(); return customerid; ------------------------------------------------------------------------------- Criação da página Vender.aspx
Source code: <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Vender.aspx.cs" Inherits="Vender" Title="Untitled Page" %> <asp:content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <span style="font-size: 16pt"><strong>Venda<br /> <br /> </strong></span> <table style="font-weight: bold; font-size: 16pt"> <asp:label ID="Label1" runat="server" Font-Bold="True" Font-Size="Large" Text="Cliente"></asp:Label> </td> <td style="font-size: 12pt; width: 100px"> <asp:dropdownlist ID="DropDownList1" runat="server"> </asp:dropdownlist> </td> </table> <br /> <table> <td style="width: 100px; text-align: right"> Produto:</td> <td style="width: 60px"> <asp:dropdownlist ID="DropDownList2" runat="server"> </asp:dropdownlist></td> </td>
<td style="width: 100px; text-align: right"> Quantidade:</td> <td style="width: 60px"> <asp:textbox ID="TextBox1" runat="server"></asp:textbox> </td> <asp:button ID="Button1" runat="server" OnClick="Button1_Click" Text="Acresecentar" /> </td> </table> <br /> <strong><span style="font-size: 14pt"> <asp:label ID="Label2" runat="server" Text="Produtos Vendidos"></asp:Label></span> <br /><br /> </strong> <asp:gridview ID="GridView1" runat="server"> </asp:gridview> <br /> <asp:button ID="Button2" runat="server" Text="Fechar Factura" /><br /> </asp:content> Vender.aspx.cs public partial class Vender : System.Web.UI.Page protected void Page_Load(object sender, EventArgs e) ConnectionStringSettingsCollection connectionstrings = ConfigurationManager.ConnectionStrings; ShopClassLibrary.DBPath.DB = connectionstrings["salesconnectionstring"].tostring(); if (!Page.IsPostBack) Label2.Visible = false; GridView1.Visible = false; Button2.Visible = false; // carregar a tabela de clientes para a DropDownList1 ShopClassLibrary.ICustomer customer = ShopClassLibrary.Factory.CreateCustomerService(); DataSet dsclientes = customer.getall("admin", "admin"); DropDownList1.DataTextField = "Name"; DropDownList1.DataValueField = "CustomerID"; DropDownList1.DataSource = dsclientes; DropDownList1.DataBind(); // carregar a tabela de produtos para a DropDownList2 ShopClassLibrary.IProduct product = ShopClassLibrary.Factory.CreateProductService(); DataSet dsprodutos = product.getall("admin", "admin"); DropDownList2.DataTextField = "Description"; DropDownList2.DataValueField = "ProductID"; DropDownList2.DataSource = dsprodutos;
DropDownList2.DataBind(); // criar DataSet vazio (sem dados) para guardar linhas da factura ShopClassLibrary.ISale2 sale = ShopClassLibrary.Factory.CreateSale2Service(); DataSet dsdetalhesvenda = sale.createdetails("admin", "admin"); dsdetalhesvenda.tables[0].columns.add("produto"); Session["detalhesVenda"] = dsdetalhesvenda; protected void Button1_Click(object sender, EventArgs e) Button2.Visible = true; string IDCliente = DropDownList1.SelectedValue; string IDProduto = DropDownList2.SelectedValue; string NomeProduto = DropDownList2.SelectedItem.Text; int quantidade = int.parse(textbox1.text); DataSet dsdetalhesvenda = (DataSet)Session["detalhesVenda"]; // criar nova linha no DataSet DataRow dr = dsdetalhesvenda.tables[0].newrow(); // preencher campos da linha dr["productid"] = IDProduto; dr["quantity"] = quantidade; dr["produto"] = NomeProduto; // acrescentar linha ao DataSet dsdetalhesvenda.tables["saledetails"].rows.add(dr); // visualizar o novo DataSet GridView1.DataSource = dsdetalhesvenda; GridView1.DataBind(); GridView1.Visible = true; // guardar o novo DataSet em memória Session["detalhesVenda"] = dsdetalhesvenda; Label2.Visible = true; Ficheiro Customer.cs public interface ICustomer: DataSet getall(string user, string pass); internal class Customer : ICustomer public DataSet getall(string user, string pass) OleDbConnection conn; ShopStatusEnum status; try conn = new OleDbConnection(UtilDB.CONN);
conn.open(); status = UtilDB.ValidateUser(conn, null, user, pass); if (status!= ShopStatusEnum.OK) return null; DataSet ds = UtilDB.getAllFromTable(conn, "Customers"); return ds; catch (System.Exception) return null; Ficheiro Product.cs internal class Product : Iproduct DataSet getall(string user, string pass); internal class Product : IProduct public DataSet getall(string user, string pass) OleDbConnection conn; ShopStatusEnum status; try conn = new OleDbConnection(UtilDB.CONN); conn.open(); status = UtilDB.ValidateUser(conn, null, user, pass); if (status!= ShopStatusEnum.OK) return null; DataSet ds = UtilDB.getAllFromTable(conn, "Products"); return ds; catch (System.Exception) return null; Ficheiro Sale.cs internal class Sale : ISale2 public DataSet CreateDetails(string user, string pass) OleDbConnection conn = null; DataSet ds; try conn = new OleDbConnection(UtilDB.CONN); conn.open(); if (UtilDB.ValidateUser(conn, null, user, pass)!= ShopStatusEnum.OK) return null; // criar o DataSet vazio para a aplicação cliente preencher ds = UtilDB.GetByID(conn, null, "SaleDetails", "SaleID", -1); if (ds == null) return null;
// configurar as colunas para utilização ds.tables["saledetails"].columns["saleid"].allowdbnull = true; catch (OleDbException) return null; finally if (conn.state == ConnectionState.Open) conn.close(); return ds; ------------------------------------------------------------------------------- Versão 4: Para esconder as colunas 0- SaleID, 2- ProdutID, e 3- TotalCost do dataset criado em memória, que é a fonte de dados do GridView onde se apresentam os detalhes dos Produtos Vendidos, é necessário tratar o evento RowCreated.
GridView1 > Properties > Events > Behavior > RowCreated > Duplo clique Na página Vender.aspx, Source code, é acrescentado: <asp:gridview ID="GridView1" runat="server" OnRowCreated="GridView1_RowCreated"> </asp:gridview> Vender.aspx.cs public partial class Vender : System.Web.UI.Page protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) e.row.cells[0].visible = false; e.row.cells[2].visible = false; e.row.cells[3].visible = false; Botão Fechar Factura :