0

I'm getting my first steps on programming, so I'm a little green at this. Thanks in advance for the help you can give.

The code is this:

SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CET47ConnectionString"].ConnectionString);
        SqlCommand myCommand = new SqlCommand();


        myCommand.Parameters.AddWithValue("@nome", nome.Value);
        myCommand.Parameters.AddWithValue("@data_de_nascimento", Convert.ToDateTime(data_de_nascimento.Value));
        myCommand.Parameters.AddWithValue("@rua", rua.Value);
        myCommand.Parameters.AddWithValue("@localidade", localidade.Value);
        myCommand.Parameters.AddWithValue("@concelho", concelho.Value);
        myCommand.Parameters.AddWithValue("@codigo_postal", codigopostal1.Value + " - " + codigopostal2.Value);
        myCommand.Parameters.AddWithValue("@pais", pais.Value);
        myCommand.Parameters.AddWithValue("@telefone", telf.Value);
        myCommand.Parameters.AddWithValue("@telemovel", telem.Value);
        myCommand.Parameters.AddWithValue("@email", email.Value);
        myCommand.Parameters.AddWithValue("@nif", nif.Value);

        SqlParameter val_output = new SqlParameter();
        val_output.ParameterName = "@retorno";
        val_output.Direction = ParameterDirection.Output;
        val_output.SqlDbType = SqlDbType.Int;

        myCommand.Parameters.Add(val_output);

        myCommand.CommandType = CommandType.StoredProcedure;
        myCommand.CommandText = "inserir_candidato";

        myCommand.Connection = myConn;
        myConn.Open();
        myCommand.ExecuteNonQuery();

        int valor_retornado = Convert.ToInt32(myCommand.Parameters["@retorno"].Value);

        myConn.Close();

        if (valor_retornado == 0)
        {
            Lbl_message.Text = "O utilizador já existe";

        }
        else
        {
            string caminho = ConfigurationSettings.AppSettings.Get("PathFicheiros");// string que aponta para localhost
            string caminhoPDFs = ConfigurationSettings.AppSettings.Get("PathFicheirosPDFs");// string que aponta para local fisico do ficheir
            string pdfTemplate = caminhoPDFs + "Template\\template.pdf";
            //Response.Write(pdfTemplate);
            //Response.End();

            Guid g = Guid.NewGuid();

            string nomePDF = g + ".pdf";
            string newFile = caminhoPDFs + nomePDF;

            PdfReader pdfr = new PdfReader(pdfTemplate);

            PdfStamper pdfst = new PdfStamper(pdfr, new FileStream(newFile, FileMode.Create));

            AcroFields pdfform = pdfst.AcroFields;

            pdfform.SetField("nome", nome.Value);// o nome é o atributo que esta na template.
            pdfform.SetField("data_de_nascimento", data_de_nascimento.Value);
            pdfform.SetField("rua", rua.Value);
            pdfform.SetField("localidade", localidade.Value);
            pdfform.SetField("concelho", concelho.Value);
            pdfform.SetField("codigo_postal", codigopostal1.Value + "-" + codigopostal2.Value);
            pdfform.SetField("pais", pais.Value);
            pdfform.SetField("telefone", telf.Value);
            pdfform.SetField("telemovel", telem.Value);
            pdfform.SetField("email", email.Value);
            pdfform.SetField("contribuinte", nif.Value);

            pdfst.Close();

SqlConnection myConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["CET47ConnectionString"].ConnectionString);
SqlCommand myCommand2 = new SqlCommand();

myCommand2.Parameters.AddWithValue("@nif", nif.Value);
myCommand2.Parameters.AddWithValue("@gui", g);

myCommand2.CommandType = CommandType.StoredProcedure;
myCommand2.CommandText = "registro_inscricao";
myCommand2.Connection = myConn2;

myConn2.Open();
myCommand2.ExecuteNonQuery();
myConn2.Close();

The stored procedure

CREATE PROCEDURE registro_inscricao
    @nif as int,
    @gui as uniqueidentifier
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN
        UPDATE registos
        SET registo = @gui
        WHERE nif = @nif
    END
END

And I get this error:

System.Data.SqlClient.SqlEXception: 'Procedure or function registro_inscricao has too many arguments specified'

Already fix one error. Thx to @Klaus. But still can't pass the value of guid to the DB

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
  • 1
    You have both `myCommand2` and `myCommand`; typo? – Klaus Gütter Jan 24 '21 at 10:26
  • Strange. Are you sure you aren't pointing to another DB? Because the code seems to be correct. – xanatos Jan 24 '21 at 10:26
  • it's the same DB. @KlausGütter lol thx. didn´t see that. – Carlos Alves Jan 24 '21 at 10:34
  • As Klaus said, you should probably use commd 2 everywhere since you myCommand must have been initialize before with other parameters – Pierre Michel Jan 24 '21 at 10:35
  • //But still can't pass the value of guid to the DB => How do you pass the values/Call the stored procedure. Could you post that part of the code! – Nantharupan Jan 24 '21 at 10:40
  • yes i have mycommand to create a user, after that i create a pdf with a GUID and i try to pass that GUID to the DB after been created to be associated to the user. – Carlos Alves Jan 24 '21 at 10:41
  • Can you show us what `nif.Value` and `g` is? Is the exception still the same? – Klaus Gütter Jan 24 '21 at 10:42
  • im going to edit the post and show all the code. – Carlos Alves Jan 24 '21 at 10:46
  • Can you run the stored procedure on the server? Is one of the parameters `null`. Does it compile correctly? Try recreating it. – Peter Smith Jan 24 '21 at 10:46
  • 1
    You are passing all the parameters from the first SP to the second. You either need to clear them or use a different command. Also the see the blog post mentioned below about using `AddWithValue` – Peter Smith Jan 24 '21 at 11:03
  • Apart from your problem: **You do not have `using` blocks around your connection and command objects. You must dispose these correctly** See also [C# Data Connections Best Practice?](https://stackoverflow.com/questions/17552829/c-sharp-data-connections-best-practice) – Charlieface Jan 24 '21 at 13:06

2 Answers2

1

You could try something below.

   using (SqlConnection con = new SqlConnection(dc.Con)) {
        using (SqlCommand cmd = new SqlCommand("registro_inscricao", con)) {
          cmd.CommandType = CommandType.StoredProcedure;
    
            cmd.Parameters.Add("@nif", SqlDbType.Int).Value = nif.Value;
            cmd.Parameters.Add("@gui", SqlDbType.UniqueIdentifier).Value = g;

          con.Open();
          cmd.ExecuteNonQuery();
        }
      }
Nantharupan
  • 594
  • 3
  • 15
  • Why would you specify the types as `SqlDbType.VarChar` and not as the correct types according to the procedure definition (`SqlDbType.Int` and `SqlDbType.UniqueIdentifier`)? – Klaus Gütter Jan 24 '21 at 10:51
  • @KlausGütter, No. Thanks for the correction. It should be according to the right type. Corrected it. – Nantharupan Jan 24 '21 at 10:52
  • 1
    Related Blog post: https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ – Klaus Gütter Jan 24 '21 at 10:58
  • OK it's working now. after i correct the typo that @KlausGütter mentioned i had forgot to save the code. nows is working. THX again all for the help. – Carlos Alves Jan 24 '21 at 11:01
0

As @xantos said, the code you supplied above does work, however - you didn't include how your variables are declared, if "g" definitely a GUID or are you trying to pass an object that contains a GUID as a property, as you have for the Value property of @nif?

I refactored your C# code as follows, to include the variable definitions (and dispose of the SQL Objects when done - a good practice to clean up after yourself):

static void TestDB()
{
    var nif = new { Value = 100 };
    Guid g = Guid.NewGuid();

    using (SqlConnection myConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["CET47ConnectionString"].ConnectionString))
    {
        myConn2.Open();
        using (SqlCommand myCommand2 = new SqlCommand())
        {
            myCommand2.Parameters.AddWithValue("@nif", nif.Value);
            myCommand2.Parameters.AddWithValue("@gui", g);

            myCommand2.CommandType = CommandType.StoredProcedure;
            myCommand2.CommandText = "registro_inscricao";
            myCommand2.Connection = myConn2;

            myCommand2.ExecuteNonQuery();
        }
        myConn2.Close();
    }
}

I also created a sample Stored Procedure from your definition, as follows:

CREATE PROCEDURE registro_inscricao
    @nif as int,
    @gui as uniqueidentifier
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN
        PRINT 'GUID: ' + CAST(@gui AS NVARCHAR(50))
        --UPDATE registos
        --SET registo = @gui
        --WHERE nif = @nif
    END
END

The result was, it worked first time.

Looks like your problem isn't in the code above, more likely you are attempting to pass a collection or an object.

Check nif.Value is a single INT value and not a collection (e.g. INT[])

Check g is a single GUID value (e.g. it's not defined as a collection type GUID[] or contains a property for your GUID { SomeProperty = GUID }

  • i declare the GUID here : Guid g = Guid.NewGuid(); i use this to associated to the pdf. the last of part of is this code is sending a email with the pdf attach, where the guid is the reference to the registration. – Carlos Alves Jan 24 '21 at 11:17