Single entry in ASP.NET form

1

I have a code that makes the register of certain types of equipment, the form fields that I have are: Name, Server, Type and Port of the equipment.

I would like the user not to register two devices with the same port and I do not know how to do it.

My ASP.NET code is:

<%@ Page Title="" Language="C#" MasterPageFile="~/interna.master" AutoEventWireup="true" CodeFile="equipamentocadastro.aspx.cs" Inherits="usuariocadastro" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolderCorpo" Runat="Server">
                                                <div class="tabbable">
                                                    <ul class="nav nav-tabs padding-16">

                                                        <li class="active">
                                                            <a data-toggle="tab" href="#edit-password" aria-expanded="true">
                                                                <i class="blue ace-icon fa fa-tachometer bigger-125"></i>
                                                                Cadastro de equipamentos
                                                            </a>
                                                        </li>
                                                    </ul>
                                                </div>
    <br />
     <div>


         <!--///////////////////////////// problema após colocar o CssClass que permite a busca dentro da dropdownlist-->


         <!--script src="assets/css/chosen.css"></!--script>
         <script src="assets/js/chosen.jquery.js"></script-->


         <p>Cadastre os MPNs que serão monitorados.</p>
    <div class="table-responsive">
    <table class="table table-striped table-bordered table-hover">
        <tr>
            <td class="td">Nome:&nbsp;</td>
            <td>
                <asp:TextBox ID="txtLocalizacao" runat="server" class="col-xs-10 col-sm-5"></asp:TextBox>
                <asp:Label ID="lblIDEquipamento" runat="server" Visible="false"></asp:Label>
            </td>

        </tr>
         <tr>
            <td class="td">Servidor:&nbsp;</td>
            <td>
                <div class="form-group">
                   <asp:DropDownList ID="ddlServidor"  Runat="Server">
                         <asp:ListItem Value="1">192.168.0.21</asp:ListItem>
                         <asp:ListItem Value="2">192.168.0.28</asp:ListItem>
                         <asp:ListItem Value="3">192.168.0.200</asp:ListItem>
                   </asp:DropDownList>
                 </div> 

            </td>
        </tr>

        <tr>
            <td class="td">Tipo:&nbsp;</td>
            <td>
                <div class="form-group">
                   <asp:DropDownList ID="ddlTipoEqp"  Runat="Server">
                         <asp:ListItem Value="1">MPN</asp:ListItem>
                         <asp:ListItem Value="2">Graxeira</asp:ListItem>
                   </asp:DropDownList>
                 </div> 
            </td>

        </tr>
        <tr>
            <td class="td">Porta:&nbsp;</td>
            <td>
                <asp:TextBox ID="txtPorta" runat="server" class="col-xs-10 col-sm-5"></asp:TextBox>
            </td>
        </tr>   
        <tr>
            <td class="td">Enviar alerta por e-mail:&nbsp;</td>
            <td>
                <asp:CheckBox ID="chkEnviarMensagem" runat="server" class="ace ace-switch ace-switch-3"  />
            </td>
        </tr>       


        <tr>
            <td></td>
            <td>
                <asp:Button ID="btnSubmit" runat="server" Text="Cadastrar" OnClick="btnSubmit_Click"/>
                <asp:Button ID="btnUpdate" runat="server" Text="Atualizar" Visible="false" OnClick="btnUpdate_Click" />
                <asp:Button ID="btnCancel" runat="server" Text="Cancelar" OnClick="btnCancel_Click" /></td>

        </tr>
    </table>
    </div>

    <div style="padding: 10px; margin: 0px; width: 100%;">
        <p>
            Total de usuários: <asp:Label ID="lbltotalcount" runat="server" Font-Bold="true"></asp:Label>
        </p>
        <asp:GridView ID="GridViewEmail" runat="server" DataKeyNames="IDEquipamento" autogeneratecolumns="false"
            OnSelectedIndexChanged="GridViewEmail_SelectedIndexChanged"
OnRowDeleting="GridViewEmail_RowDeleting" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="10" class="table table-striped table-bordered table-hover">
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:boundfield datafield="Localizacao" headertext="Nome"  />
                <asp:boundfield datafield="Endereco" headertext="Servidor"  />
                <asp:boundfield datafield="NomeTipoEquipamento" headertext="Tipo Equipamento"  />
                <asp:boundfield datafield="Porta" headertext="Porta"  />
                <asp:boundfield datafield="EnviarMensagem" headertext="Enviar alerta"  />
                <asp:commandfield showdeletebutton="true" buttontype="Image" deleteimageurl="~\images\lixo.png" headertext=" Excluir "  HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center" />
            </Columns>

            <EditRowStyle BackColor="#2461BF"  />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White"  />
            <PagerStyle BackColor="#2461BF" ForeColor="White"  />
            <RowStyle BackColor="#EFF3FB"  />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#F5F7FB" />
            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
            <SortedDescendingCellStyle BackColor="#E9EBEF" />
            <SortedDescendingHeaderStyle BackColor="#4870BE" />
        </asp:GridView>
    </div>    
     </div>
    <br /><br />
            <div style="float:left;">
                    <input type="button" value="Voltar para o monitoramento" class="btn btn-primary" onClick="javascript: window.location = 'default.aspx';" />
            </div>
    <script type="text/javascript">
     $(document).on("ready", function () {
            //$('.chosen-select').chosen(); 
     })
    </script>
</asp:Content>

The back end c # code:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Configuration;


public partial class usuariocadastro : System.Web.UI.Page
{
    public string IDCliente = "1";
    public string IDPerfil = "1";

    #region SqlConnection Connection and Page Lode
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionStringSQL"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (null != Request.Cookies["MPN"]["IDPerfil"])
            IDPerfil = Utils.Cripto.Decrypt(Request.Cookies["MPN"]["IDPerfil"]);

        if (null != Request.Cookies["MPN"]["IDCliente"])
            IDCliente = Utils.Cripto.Decrypt(Request.Cookies["MPN"]["IDCliente"]);

        try
        {


            if (!Page.IsPostBack)
            {
                //equip.Text = "9999";
                BindGridView();

            }
        }
        catch (Exception ex)
        {
            ShowMessage(ex.Message);
        }
    }
    #endregion
    #region show message
    /// <summary>
    /// This function is used for show message.
    /// </summary>
    /// <param name="msg"></param>
    void ShowMessage(string msg)
    {
        ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('" + msg + "');</script>");
    }
    /// <summary>
    /// This Function is used TextBox Empty.
    /// </summary>
    void clear()
    {
        txtLocalizacao.Text = string.Empty;
        txtLocalizacao.Focus();
        txtPorta.Text = string.Empty;
    }
    #endregion
    #region bind data to GridViewEmail
    private void BindGridView()
    {
        try
        {
            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand("SELECT Equipamento.IDEquipamento, Equipamento.Localizacao, Equipamento.IDServidor, TipoEquipamento.NomeTipoEquipamento, Equipamento.Porta, Equipamento.EnviarMensagem, Servidor.Endereco FROM Equipamento INNER JOIN Servidor ON Equipamento.IDServidor = Servidor.IDServidor INNER JOIN TipoEquipamento on TipoEquipamento.IDTipoEquipamento = Equipamento.IDTipoEquipamento WHERE (Equipamento.IDCliente = @IDCliente) ORDER BY Equipamento.Localizacao", conn);
            cmd.Parameters.AddWithValue("@IDCliente", IDCliente);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            adp.Fill(ds);
            GridViewEmail.DataSource = ds;
            GridViewEmail.DataBind();

            lbltotalcount.Text = GridViewEmail.Rows.Count.ToString();

            //equip.ClearSelection();
            //equip.Items.FindByValue(IDCliente).Selected = true;

        }
        catch (SqlException ex)
        {
            ShowMessage(ex.Message);
        }
        finally
        {
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
        }
    }
    #endregion
    #region Insert Data
    /// <summary>
    /// this code used to Student Data insert in Sql Database
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtLocalizacao.Text != "")
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("INSERT INTO Equipamento (IDCliente,Localizacao,IDServidor,Porta,Atualizar,EnviarMensagem,IDTipoEquipamento) VALUES (@IDCliente,@Localizacao,@IDServidor,@Porta,1,@EnviarMensagem, @IDTipoEquipamento);SELECT CAST(scope_identity() AS int);", conn); 
                cmd.Parameters.AddWithValue("@IDCliente", IDCliente);
                cmd.Parameters.AddWithValue("@Localizacao", txtLocalizacao.Text);
                cmd.Parameters.AddWithValue("@IDServidor", ddlServidor.SelectedValue);
                cmd.Parameters.AddWithValue("@IDTipoEquipamento", ddlTipoEqp.SelectedValue);
                cmd.Parameters.AddWithValue("@Porta", txtPorta.Text);
                cmd.Parameters.AddWithValue("@EnviarMensagem", chkEnviarMensagem.Checked);
                Int32 intIDEquipCadastrado = (Int32)cmd.ExecuteScalar();
                cmd.CommandText = "INSERT INTO EquipamentoEstadoAtual (IDEquipamento,IDCor,DataHoraAtualizacao) VALUES (" + intIDEquipCadastrado .ToString() + ",4,GETDATE())";
                cmd.ExecuteNonQuery();

                int idequipamento = Convert.ToInt32(ddlTipoEqp.SelectedValue);

                if (idequipamento == 1)
                { 
                    cmd.CommandText = "INSERT INTO EntradaEstado (IDEquipamento,IDEntradaTipo,IDEntrada, Valor, DataHoraAtualizacao) VALUES (" + intIDEquipCadastrado.ToString() + ",1,0,0,GETDATE()),(" + intIDEquipCadastrado.ToString() + ",1,1,0,GETDATE()),(" + intIDEquipCadastrado.ToString() + ",1,2,1,GETDATE()),(" + intIDEquipCadastrado.ToString() + ",1,3,0,GETDATE()),(" + intIDEquipCadastrado.ToString() + ",1,4,0,GETDATE()),(" + intIDEquipCadastrado.ToString() + ",1,5,0,GETDATE()),(" + intIDEquipCadastrado.ToString() + ",1,6,0,GETDATE()),(" + intIDEquipCadastrado.ToString() + ",1,7,1,GETDATE());";

                } else if(idequipamento == 2) { 
                    cmd.CommandText = "INSERT INTO EntradaEstado (IDEquipamento,IDEntradaTipo,IDEntrada, Valor, DataHoraAtualizacao) VALUES (" + intIDEquipCadastrado.ToString() + ",1,8,0,GETDATE()), (" + intIDEquipCadastrado.ToString() + ",1,9,0,GETDATE()), (" + intIDEquipCadastrado.ToString() + ",1,10,1,GETDATE()), (" + intIDEquipCadastrado.ToString() + ",1,11,0,GETDATE()), (" + intIDEquipCadastrado.ToString() + ",1,12,0,GETDATE());";
                }

                cmd.ExecuteNonQuery();
                cmd.Dispose();
                //Response.Redirect("default.aspx");
                //ShowMessage("E-mail cadastrado com sucesso!");
                clear();
                BindGridView();
            }
        }
        catch (SqlException ex)
        {
            ShowMessage(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }

    #endregion
    #region SelectedIndexChanged
    /// <summary>
    /// this code used to GridViewRow SelectedIndexChanged value show textbox
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewEmail_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow row = GridViewEmail.SelectedRow;
        lblIDEquipamento.Text = row.Cells[2].Text;
        txtLocalizacao.Text = row.Cells[3].Text;
        btnSubmit.Visible = false;
        btnUpdate.Visible = true;
    }
    #endregion
    #region Delete Student Data
    /// <summary>
    /// This code used to GridViewEmail_RowDeleting Student Data Delete
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void GridViewEmail_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            conn.Open();
            int IDEquipamento = Convert.ToInt32(GridViewEmail.DataKeys[e.RowIndex].Value);
            SqlCommand cmd = new SqlCommand("Delete From EquipamentoEstadoAtual where IDEquipamento='" + IDEquipamento + "'; Delete from EntradaEstado where IDEquipamento='" + IDEquipamento + "'; Delete from Equipamento where IDEquipamento='" + IDEquipamento + "';",conn);
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            //Response.Redirect("default.aspx");
            //ShowMessage("E-mail deletado com sucesso!");
            GridViewEmail.EditIndex = -1;
            BindGridView();
        }
        catch (SqlException ex)
        {
            ShowMessage(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }
    #endregion
    #region student data update
    /// <summary>
    /// This code used to student data update
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            conn.Open();
            string IDEmail = lblIDEquipamento.Text;
            SqlCommand cmd = new SqlCommand("update email Set Email=@Email where IDEmail=@IDEmail and IDEquipamento=@IDEquipamento", conn);
            cmd.Parameters.AddWithValue("@Email", txtLocalizacao.Text);
            cmd.Parameters.AddWithValue("@IDEmail", IDEmail);
            cmd.Parameters.AddWithValue("@IDEquipamento", "equip.Text");
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            //Response.Redirect("default.aspx");
            //ShowMessage("E-mail atualizado com sucesso!");
            GridViewEmail.EditIndex = -1;
            BindGridView(); btnUpdate.Visible = false;
        }
        catch (SqlException ex)
        {
            ShowMessage(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }
    #endregion
    #region textbox clear
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        clear();
        Response.Redirect("default.aspx");
    }
    #endregion

}
    
asked by anonymous 03.07.2017 / 15:08

1 answer

2

I think in this case, the most interesting thing is that you validate the existence of an already registered device for a specific port on the server side, since this is apparently a business rule. Check if a device already exists in the database for that port, and if it already exists, return an error message to the user.

You can even include a UNIQUE constraint in the table where you record these equipments in the column corresponding to the port, so the bank itself will not allow two equal values for that column to be registered. In that case, you would also have to handle the errors that would be returned by the bank.

But in any case, validate before registering the equipment. As said above, what you need to do is characteristic of business rule, so in this case you'd better prevent a possible exception if this duplicate port value gets to the bank. If it arrives, your UNIQUE restriction will only prevent this value from being effectively registered.

    
03.07.2017 / 15:14