I can not pass one value from one class to another - c#

I can not pass one value from one class to another, when i try, the value pass to 0 instead the value from the first class.
I have this: an method that will check if the person is in the database, and the variable IDautor will gain the id is on the database, it will enter in the if clauses then the array id2 in the position 1 will save the value from IDautor... I pretend to use that value in the class Artigo, but the value came always 0 and i don't no why
Class Autor
public bool Login(TextBox txtUser, TextBox txtPassword)
{
string utl, pass;
try
{
utl = txtUser.Text;
pass = txtPassword.Text;
_Sql = "Select Count(IDAutor) From Autor Where uUser = #uUser and Pass = #Pass";
SqlCommand cmd = new SqlCommand(_Sql, Conn);
cmd.Parameters.Add("#uUser", SqlDbType.VarChar).Value = utl;
cmd.Parameters.Add("#Pass", SqlDbType.VarChar).Value = pass;
Conn.Open();
IDautor = (int)cmd.ExecuteScalar();
if (IDautor > 0)
{
MessageBox.Show("Bem Vindo");
Conn.Close();
id2[1] = IDautor;
return true;
}
else
{
MessageBox.Show("Tera que tentar de novo");
Conn.Close();
return false;
}
}
catch(Exception ex)
{
MessageBox.Show("ERRO Message: "+ ex);
Conn.Close();
return false;
}
}
public int[] id2
{
get { return this.id2; }
}
and in trying to save the value in array id2 and use that value in another class
Class Artigo
public string AddArtigo(string newArtigo)
{
if (newArtigo == null)
{
return "Nao selecionou o PDF desejado. Tente de novo";
}
if (newArtigo != null)
{
using (FileStream st = new FileStream(newArtigo, FileMode.Open, FileAccess.Read))
{
SqlConnection Conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Convidado1\Desktop\Aplicaçao C#\Aplicaçao\ITArtiConf\ITArtiConf\Database1.mdf;Integrated Security=True;User Instance=True");
Autor au = new Autor();
byte[] buffer = new byte[st.Length];
st.Read(buffer, 0, (int)st.Length);
st.Close();
Conn.Open();
SqlCommand cmd = Conn.CreateCommand();
cmd.CommandText = "insert into Artigo (idAutor) values('" + au.id2[1] + "')";
cmd.ExecuteNonQuery();
Conn.Close();
SqlCommand cmd1 = new SqlCommand("UPDATE SomeTable SET Artigo=#Artigo WHERE idAutor =" + au.id2[1], Conn);
cmd1.Parameters.AddWithValue("#Artigo", buffer);
Conn.Open();
int i = cmd1.ExecuteNonQuery();
Conn.Close();
}
return "Guardado";
}
return "Error";
}
the au.id2[1] become 0 instead the value on the other class.

Autor au = new Autor();
This line of code creates new Author object, which has all properties set into their default values. You don't call anything more on that object before trying to get id value, so it's value is 0.
You should consider making that property static, what will makes it's value persistent.

The best way would be not to use Autor au = new Autor(); but rather to change the constructor of the Artigo to accept an Autor and save it or some properties as members of Artigo or to change the signature of AddArtigo to accept an Autor.
So, either:
Autor au = new Autor();
au.Login(user, pass); // this should really accept strings and not TextBoxes...
Artigo art = new Artigo(au); // this saves id2[1] as a member somewhere
art.AddArtigo(newArtigo); // why does the Artigo class have an AddArtigo method?
or
Autor au = new Autor();
au.Login(user, pass);
Artigo art = new Artigo();
art.AddArtigo(newArtigo, au);
Either way, there are multiple little issues with your solution (from having an array id2, to a Login method accepting TextBoxes and an Artigo that adds itself, most likely that code would be better suited as part of the Artigo constructor).

Pass Author object to another class.
using this Author object u can access value.
Author _author = new Author();
int value = _author.id[1];

Related

How to pass GUID parameters to SQL Server through a stored procedure?

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
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();
}
}
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 }

how to create an id to be shown in the text box based on selected dropdownlist

i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}

Mysql read and change variable at the same time

I want to shift some variables by one. I searched for the command for it but I couldn't find. If anybody knows it please help me.
Here is the code:
private int shiftNumbers(int number)
{
int newNumber = 0;
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
try
{
con.Open();
cmd = new MySqlCommand(stm, con);
cmd.Parameters.AddWithValue("#number", number);
}
catch (Exception e)
{
ErrorMessage = e.Message;
con.Close();
return null;
}
try
{
rdr = cmd.ExecuteReader();
while(rdr.Read()) {
newNumber = rdr.GetInt32(1);
cmd.Parameters.AddWithValue("#newNumber ", (newNumber-1));
}
}
catch (Exception e)
{
ErrorMessage = e.Message;
con.Close();
return null;
}
con.Close();
return 1;
}
I know this code useless but I show it for you to get the logic that I want to do.
I think your approach is wrong.
First, you read from the database, using a select statement;
Then you go over that result, your rdr.Read();
Then you create a new command, updating the original record;
Move forward in your reader (rdr) and repeat from 2 until you are done.
What you are doing now is impossible. You can't get a result set from an update, just a count affected.
Or, if you can, let your update statement do the calculation (it seems it is only subtracting one from the original number, so why not do that in SQL?):
string stm = "UPDATE devices SET number = number - 1 WHERE number>#number";
Yes, your code is really useless. In your update statement you are passing a parameter #newNumber bu not providing it. Closing the connection in catch block.
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
First decide from where you are going to get the #newNumber value and then add that as parameter and use ExecuteNonQuery() method.
If you want pass the other parameter as well in your method and use it like
private int shiftNumbers(int number, int newNumber)
{
//int newNumber = 0;
string stm = "UPDATE devices SET number= #newNumber WHERE number>#number";
using(SqlConnection con = new SqlConnection(connectionString))
{
cmd = new MySqlCommand(stm, con);
SqlParameter paramNumber = new SqlParameter("#number", SqlDbType.Int);
paramNumber.Value = number;
SqlParameter paramNewNumber = new SqlParameter("#newNumber", SqlDbType.Int);
paramNewNumber.Value = newNumber;
cmd.Parameters.Add(paramNumber);
cmd.Parameters.Add(paramNewNumber);
con.Open();
cmd.ExecuteNonQuery();
}
//Rest of your code logic if any
}

message error "Specified cast is not valid"

I'm trying to get information from database access with this method
public List<gerant> getinfogerant()
{
List<gerant> gerer = new List<gerant>();
string sql_gerant = "select CIN,NOM,PRENOM,ADRESS_PERSONNEL,NUM_TEL,MAIL,MOBILE,CP_GERANT,VILLE_GERANT,DATE_CIN from GERANT";
connexion connect = new connexion();
OleDbConnection connection = connect.getconnexion();
connection.Open();
OleDbCommand cmd = new OleDbCommand(sql_gerant, connection);
OleDbDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
gerer.Add(new gerant(reader.GetInt64(0),
reader.GetString(1),
reader.GetString(2),
reader.GetString(3),
reader.GetDouble(4),
reader.GetString(5),
reader.GetDouble(6),
reader.GetInt32(7),
reader.GetString(8),
reader.GetDateTime(9))
);
}
connection.Close();
return gerer;
}
In my database access I define the field cin as long integer and formatted "00000000"
But I'm getting an error in reader.GetInt64(0):
Specified cast is not valid
How can I solve that?
Try this code
public List<gerant> getinfogerant()
{
List<gerant> gerer = new List<gerant>();
try
{
connexion connect = new connexion();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = new OleDbConnection(connect.getconnexion());
cmd.CommandType = CommandType.Text;
comd.CommandText = "select CIN,NOM,PRENOM,ADRESS_PERSONNEL,NUM_TEL,MAIL,MOBILE,CP_GERANT,VILLE_GERANT,DATE_CIN from GERANT";
connection.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
gerant g = new gerant();
if (!reader.IsDBNull(0)) g.CIN = int.Parse(reader.GetValue(0).ToString());
if (!reader.IsDBNull(1)) g.NOM = reader.GetValue(1).ToString();
if (!reader.IsDBNull(2)) g.PRENOM = reader.GetValue(2).ToString();
if (!reader.IsDBNull(3)) g.ADRESS_PERSONNEL = reader.GetValue(3).ToString();
if (!reader.IsDBNull(4)) g.NUM_TEL = Convert.ToDouble(reader.GetValue(4).ToString());
if (!reader.IsDBNull(5)) g.MAIL = reader.GetValue(5).ToString();
if (!reader.IsDBNull(6)) g.MOBILE =Convert.ToDouble(reader.GetValue(6).ToString());
if (!reader.IsDBNull(7)) g.CP_GERANT = int.Parse(reader.GetValue(7).ToString());
if (!reader.IsDBNull(8)) g.VILLE_GERANT = reader.GetValue(8).ToString();
if (!reader.IsDBNull(9)) g.DATE_CIN = Convert.ToDateTime(reader.GetValue(9).ToString());
gerer.add(g);
}
return gerer;
}
catch(Exception ex)
{
throw ex;
}
finally
{
reader.Close();
connection.Close();
}
}
and please adjust the names of your classes and methods:
- public List getinfogerant() -> public List getInfoGerant()
connexion connect = new connexion(); -> connection (not x)
Please check for DBNULL values, might be you are getting a null value.
Regards
Jasbeer Singh
Integers in Access come in 1, 2 and 4 byte varieties. The single byte number is named Byte (Range 0-255), the two-byte number is named Integer (-32768 to 32767) and then there is the Long Integer (-2 billion to 2 billion).
https://eggerapps.at/mdbviewer/docs/en/field-types.html
use getint32
I guess, you're getting exception not in the reader.GetInt64(0) but in the gerant constructor, so it could be any column.
To check this modify your code as follows
while (reader.Read())
{
var cin = reader.GetInt64(0);
var nom = reader.GetString(1);
var prenom = reader.GetString(2);
var addressPersonel = reader.GetString(3);
var numTel = reader.GetDouble(4);
var mail = reader.GetString(5);
var mobile = reader.GetDouble(6);
var cpGerant = reader.GetInt32(7);
var villeGerant = reader.GetString(8);
var dateCin = reader.GetDateTime(9);
gerer.Add(new gerant(cin,
nom,
prenom,
addressPersonel,
numTel,
mail,
mobile,
cpGerant,
villeGerant,
dateCin)
);
}
And you will get exception in real line.
I recommend to check column NUM_TEL and MOBILE for double numbers.
Also, check non-string columns for DbNull value before reading. long, int, double and DateTime can not be null.

ExecuteNonQuery requires the command to have a transaction error in my code

I get the following error on cmd.ExecuteNonQuery.
"ExecuteNonQuery requires the command to have a transaction when the
connection assigned to the command is in a pending local transaction.
The Transaction property of the command has not been initialized."
Here is my code:
//if (hdRefresh.Value.Length > done.Value.Length || done.Value == "1")
//{
// //Write Your Add Customer Code here > Response.Write("true")
// done.Value = hdRefresh.Value;
//}
//else
//{
// Response.Redirect("~/Cashier/BTBill.aspx");
// return;
//}
if (IsClosedToDay())
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "Warning", "<script>alert('Day Closing has been Performed ')</script>", false);
return;
}
DateTime dateFeomDB = getdate();
// by atizaz
if (HDD.Value == "" || HDD.Value == null)
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "Warning", "<script>alert('No Transaction Found')</script>", false);
return;
}
//
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLCONN"].ToString());
Common.BillTransaction bill1 = new Common.BillTransaction();
ProcessUpdateBalandUnAuthBal insertBalance = new ProcessUpdateBalandUnAuthBal();
Common.Currency currencyy = new Common.Currency();
ProcessAuthorizeTokenByBillNo authorize = new ProcessAuthorizeTokenByBillNo();
BillTransaction bill = new BillTransaction();
scon.Open();
SqlTransaction sqlTrans = scon.BeginTransaction();
try
{
string strforxml = HDD.Value;
XmlDocument docXml = new XmlDocument();
#region Read In To Sender Controlls
#region Common Information
Contact con = new Contact();
con.Title = ddlTitle.SelectedItem.Text;
con.FirstName = TextBox1.Text.Trim();
con.LastName = TextBox9.Text.Trim();
con.ConTactNo = txtCell.Text == "" ? SqlString.Null : txtCell.Text;
con.Country = ddlCountry.SelectedItem.Text;
con.CustomerType = ddlCustomerType.SelectedItem.Text;
con.CustTypeID = int.Parse(ddlCustomerType.SelectedValue);
con.CountryID = Int32.Parse(ddlCountry.SelectedValue);
con.sqlTransaction = sqlTrans;
if (Scitytxt.Value != "")
{
try
{
con.City = Scitytxt.Value;
con.CityID = Int32.Parse(Scityval.Value);
}
catch (Exception)
{ }
}
else
{
con.City = SqlString.Null;// Scitytxt.Value;
con.CityID = SqlInt32.Null;// Int32.Parse(Scityval.Value);
con.Address = "";
}
//con.City = ddlCity.SelectedItem.Text;
//con.CityID = int.Parse(ddlCity.SelectedValue);
con.Address = TextBox10.Text;
#endregion
#region Check For NIC and Passport
if (txtNIC.Text != "" || txtPassport.Text != "")
{
SqlDataReader rdrsender;
if (txtNIC.Text != "")
{
con.NIC = txtNIC.Text;
}
else
{
con.NIC = SqlString.Null;
}
if (txtPassport.Text != "")
{
con.Passport = txtPassport.Text;
}
else
{
con.Passport = SqlString.Null;
}
ProcessSearchContactInContactInfo srchSender = new ProcessSearchContactInContactInfo();
srchSender.Contact = con;
srchSender.Invokewith5parameters();
rdrsender = srchSender.ResultSet;
#region If record Doesnot Exist In response of NIC Passport
if (!rdrsender.Read())
{
rdrsender.Close();
rdrsender.Dispose();
// con.sqlTransaction = sqlTrans;
ProcessAddContact InsertnewSenderInfo = new ProcessAddContact();
// InsertnewSenderInfo.sqlTransaction = sqlTrans;
InsertnewSenderInfo.Contact = con;
InsertnewSenderInfo.Invoke();
// sender1 = InsertnewSenderInfo.ResultSet;
// Sender_ID.Value = sender1[13].ToString();
}
#endregion
#region If Record Exists
else
{
con.CustomerID = Int32.Parse(rdrsender["Customer_ID"].ToString());
rdrsender.Close();
rdrsender.Dispose();
}
#endregion
}
#endregion
#region If Customer Donot Have NIC And/OR Passport
else// this executes when both Pasport and NIC are Null
{
con.NIC = SqlString.Null;
con.Passport = SqlString.Null;
ProcessAddContact InsertnewSenderInfo = new ProcessAddContact();
InsertnewSenderInfo.Contact = con;
InsertnewSenderInfo.Invoke();
DataSet ds = new DataSet();
int a = con.CustomerID;
StringReader inforeader = new StringReader("<CusTable><CusInfo><Relation_Type></Relation_Type><HusbandFather_Name></HusbandFather_Name><Address_Present></Address_Present><Address_Other></Address_Other><Phone_No_Office></Phone_No_Office><Cell_No></Cell_No><Fax_No></Fax_No><Date_Of_Birth></Date_Of_Birth><NTN_No></NTN_No><Nationality></Nationality><Occupation></Occupation><Relation_With_Financial_Institution></Relation_With_Financial_Institution><Other_Relation_With_Financial_Institution></Other_Relation_With_Financial_Institution><Business_Relation></Business_Relation></CusInfo></CusTable>");
ds.ReadXml(inforeader);
ds.GetXml();
SqlCommand cmd = new SqlCommand("update Contact_Info set CustInfo=" + ds.GetXml() + " WHERE Customer_ID=" + a + "", scon);
cmd.ExecuteNonQuery();
// sender1 = InsertnewSenderInfo.ResultSet;
// Sender_ID.Value = sender1[13].ToString();
}
tell me what is problem in my code and how to solve it.
You need to change this line
SqlCommand cmd = new SqlCommand("update Contact_Info set CustInfo=" + ds.GetXml() +
" WHERE Customer_ID=" + a + "", scon);
in this way
SqlCommand cmd = new SqlCommand("update Contact_Info set CustInfo=" + ds.GetXml() +
" WHERE Customer_ID=" + a + "", scon, sqlTrans);
The error message states exactly the problem.
Before code reaches that line you have opened a transaction and it is still open at the point of error
.....
scon.Open();
SqlTransaction sqlTrans = scon.BeginTransaction();
.....
Now, every SqlCommand executed when the connection has an opened transaction need to be informed of this. The transaction is not automatically set by the Framework.
You can use the SqlCommand constructor, as explained above, or you can set the cmd.Transaction property before executing the command.
Warning 1
The need to set the transaction for the current command is true even if you create the SqlCommand directly from the connection itself.
SqlCommand cmd = scon.CreateCommand();
cmd.Transaction = sqlTrans; // Required when inside a transaction
Warning 2
Avoid at all cost the use of string concatenation when using query text to update/insert/delete/select on a database. Use parameters. This will remove problems with strange or invalid characters and, most important, will prevent SqlInjection Attacks
string sqlText = "update Contact_Info set CustInfo=#info WHERE Customer_ID=#id";
SqlCommand cmd = new SqlCommand(sqlText, scon, sqlTrans);
cmd.Parameters.AddWithValue("#info", ds.GetXml());
cmd.Parameters.AddWithValue("#id",a);
cmd.ExecuteNonQuery();
Also, another recommendation is to NOT use AddWithValue, while handy, this method has many problems as explained in my answer here
You have started a transaction that is not commited before you called cmd.ExecuteNonQuery().
Just write down cmd.Transaction = sqlTrans; just before cmd.ExecuteNonQuery();
it will ensure that Now ExecuteNonQuery() will be executed in same transaction and also will be able to see all the modification done to database in the same transaction.
If you have this code:
SqlTransaction sqlTrans = scon.BeginTransaction();
then you should also have this:
cmd.Transaction = sqlTrans;
they work together.
For me dapper's ExecuteAsync takes 2 optional parameters and transaction wasn't being recognized so I had to name the parameters like this:
var result = await a_mConn.ExecuteAsync(sql: a_sSqlQuery,transaction: a_mTransaction);

Categories

Resources