Docstoc

Procedimentos.doc - DEI-ISEP

Document Sample
Procedimentos.doc - DEI-ISEP Powered By Docstoc
					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>
        <tr>
             <td style="width: 100px">
                 <asp:Label ID="Label1" runat="server"
                   Text="Nome:"></asp:Label></td>
             <td style="width: 100px">
                 <asp:TextBox ID="TextBox1"
                   runat="server"></asp:TextBox></td>
        </tr>
        <tr>
             <td style="width: 100px">
                 <asp:Label ID="Label2" runat="server"
                   Text="Morada:"></asp:Label></td>
             <td style="width: 100px">
                 <asp:TextBox ID="TextBox2"
                   runat="server"></asp:TextBox></td>
        </tr>
        <tr>
             <td style="width: 100px">
                 <asp:Label ID="Label3" runat="server"
                   Text="Telefone:"></asp:Label></td>
             <td style="width: 100px">
                 <asp:TextBox ID="TextBox3"
                   runat="server"></asp:TextBox></td>
        </tr>
        <tr>
             <td style="width: 100px">
                 <asp:Label ID="Label4" runat="server"
                   Text="Fax:"></asp:Label></td>
             <td style="width: 100px">
                 <asp:TextBox ID="TextBox4"
                   runat="server"></asp:TextBox></td>
        </tr>
        <tr>
             <td style="width: 100px">
                 <asp:Label ID="Label5" runat="server"
                   Text="E-mail:"></asp:Label></td>
             <td style="width: 100px">
                 <asp:TextBox ID="TextBox5"
                   runat="server"></asp:TextBox></td>
        </tr>
    </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">
        <tr>
             <td style="width: 100px">
                 <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>
        </tr>
    </table>
    <br />
    <table>
        <tr>
             <td style="width: 100px; text-align: right">
                 Produto:</td>
             <td style="width: 60px">
                 <asp:DropDownList ID="DropDownList2" runat="server">
                 </asp:DropDownList></td>
             <td style="width: 100px">
             </td>
        </tr>
        <tr>
             <td style="width: 100px; text-align: right">
                 Quantidade:</td>
             <td style="width: 60px">
                 <asp:TextBox ID="TextBox1"
                         runat="server"></asp:TextBox>
             </td>
             <td style="width: 100px">
                 <asp:Button ID="Button1" runat="server"
                         OnClick="Button1_Click" Text="Acresecentar" />
             </td>
         </tr>
    </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“:

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:10
posted:9/22/2011
language:
pages:10