1
I have a code that registers certain types of equipment, the form fields I have are: Name, Server, Type and Port of the equipment.
I wish it was not possible for the user to register two equipments with the same door and do not know how.
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: </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: </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: </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: </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: </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 c# code of the back end:
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
}
I think in that case your back-end code would be better so we can help you. I believe that at the front end it is not interesting to do this kind of validation.
– Ana Carolina Manzan