Get Identity Value from Typed DataSet - c#

I got a typed dataset in my form. Using BindingSource to walk in rows, inserting and updating records.
Everything is fine but I need inserted records identity value for generating a string for my GeneratedCode field in my table.
After getting this value I'll send value to my CodeGen() method and generate string, and update same row's CodeGen field with this value.
I'm using Access database. I know there is that ##Identity thing for Access, but how can I use it? I don't want to use OleDbCommand or something like this.
How can I do that?
string GenCode(int pCariId)
{
string myvalue;
int totalDigit = 7;
myvalue = "CR" + pCariId.ToString();
for (int digit = myvalue.Length; digit <= totalDigit - 1; digit++)
{
myvalue = myvalue.Insert(2, "0");
}
return myvalue;
}
private void dataNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
{
switch (e.Button.ButtonType)
{
case NavigatorButtonType.EndEdit:
try
{
this.Validate();
if (KaydetFlags == 1)
{
this.bndCariKayit.EndEdit();
datagate_muhasebeDataSet.TB_CARI.Rows[datagate_muhasebeDataSet.Tables["TB_CARI"].Rows.Count - 1]["INS_USR"] = 0;
datagate_muhasebeDataSet.TB_CARI.Rows[datagate_muhasebeDataSet.Tables["TB_CARI"].Rows.Count - 1]["INS_TRH"] = DateTime.Now;
XtraMessageBox.Show("Yeni Cari Kaydı Tamamlandı.");
KaydetFlags = 0;
}
else
{
DataRowView currentRow = (DataRowView)bndCariKayit.Current;
currentRow.Row["UPD_USR"] = "0";
currentRow.Row["UPD_TRH"] = DateTime.Now;
XtraMessageBox.Show("Cari Kaydı Güncellendi.");
this.bndCariKayit.EndEdit();
}
this.tB_CARITableAdapter.Update(datagate_muhasebeDataSet.TB_CARI);
}
catch (System.Exception ex)
{
XtraMessageBox.Show("Kayıt İşlemi Başarısız. Lütfen Tekrar Deneyiniz.");
}
break;

According to documentation you have to use RowUpdated method of your TableAdapter
private static void OnRowUpdated(
object sender, OleDbRowUpdatedEventArgs e)
{
// Conditionally execute this code block on inserts only.
if (e.StatementType == StatementType.Insert)
{
OleDbCommand cmdNewID = new OleDbCommand("SELECT ##IDENTITY",
connection);
// Retrieve the Autonumber and store it in the CategoryID column.
e.Row["CategoryID"] = (int)cmdNewID.ExecuteScalar();
e.Status = UpdateStatus.SkipCurrentRow;
}
}
Another option, which I actually use is to create Select query which simply gets maximum value from you id column:
SelectLastAddedId:
SELECT MAX(id) FROM obmiar
Just set query execute mode to scalar and you can refer to it in your code as
int lastId = TableAdapter.SelectLastAddedId()

Related

RowUpdating Not working showing me input string is not in correct format

protected void gv_card_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int result = 0;
CreditCard prod = new CreditCard();
GridViewRow row = gv_card.Rows[e.RowIndex];
string id = gv_card.DataKeys[e.RowIndex].Value.ToString();
string tid = ((TextBox)row.Cells[0].Controls[0]).Text;
string tnumber = ((TextBox)row.Cells[1].Controls[0]).Text;
string texpirydate = ((TextBox)row.Cells[2].Controls[0]).Text;
string tcvv = ((TextBox)row.Cells[3].Controls[0]).Text;
string tcardtype = ((TextBox)row.Cells[4].Controls[0]).Text;
string tholdername = ((TextBox)row.Cells[5].Controls[0]).Text;
result = prod.CardUpdate(int.Parse(tid), tholdername, tnumber,texpirydate, int.Parse(tcvv), tcardtype );
if (result > 0)
{
Response.Write("<script>alert('Product updated successfully');</script>");
}
else
{
Response.Write("<script>alert('Product NOT updated');</script>");
}
gv_card.EditIndex = -1;
bind();
}
}
Above is my Code but it just cant seem to update my gridview
That message is likely coming from your call to int.Parse(string), which expects the string to be a valid integer. To handle this, you can instead use int.TryParse(string, out int), which will return true or false if it is able to parse the string. If it's successful, the out parameter will contain the parsed integer value.
So you would first try to parse the integer fields. If that fails you could return an error message, and if it succeeds then you can use the integers directly in your call to CardUpdate:
int tidValue;
int tcvvValue;
if (!int.TryParse(tid, out tidValue))
{
Response.Write("<script>alert('The value specified for TID is not an integer.');</script>");
}
else if (!int.TryParse(tcvv, out tcvvValue))
{
Response.Write("<script>alert('The value specified for TCVV is not an integer.');</script>");
}
else
{
result = prod.CardUpdate(tidValue, tholdername, tnumber, texpirydate, tcvvValue, tcardtype);
if (result > 0)
{
Response.Write("<script>alert('Product updated successfully');</script>");
}
else
{
Response.Write("<script>alert('Product NOT updated');</script>");
}
}

NullReferenceException when creating a table with DateTime Column(SMO, C#)

My application is used to copy tables from one database and duplicate them to another, I'm using smo and C#. My code:
private static void createTable(Table sourcetable, string schema, Server destinationServer,
Database db)
{
Table copiedtable = new Table(db, sourcetable.Name, schema);
createColumns(sourcetable, copiedtable);
copiedtable.AnsiNullsStatus = sourcetable.AnsiNullsStatus;
copiedtable.QuotedIdentifierStatus = sourcetable.QuotedIdentifierStatus;
copiedtable.TextFileGroup = sourcetable.TextFileGroup;
copiedtable.FileGroup = sourcetable.FileGroup;
copiedtable.Create();
}
private static void createColumns(Table sourcetable, Table copiedtable)
{
foreach (Column source in sourcetable.Columns)
{
Column column = new Column(copiedtable, source.Name, source.DataType);
column.Collation = source.Collation;
column.Nullable = source.Nullable;
column.Computed = source.Computed;
column.ComputedText = source.ComputedText;
column.Default = source.Default;
if (source.DefaultConstraint != null)
{
string tabname = copiedtable.Name;
string constrname = source.DefaultConstraint.Name;
column.AddDefaultConstraint(tabname + "_" + constrname);
column.DefaultConstraint.Text = source.DefaultConstraint.Text;
}
column.IsPersisted = source.IsPersisted;
column.DefaultSchema = source.DefaultSchema;
column.RowGuidCol = source.RowGuidCol;
if (server.VersionMajor >= 10)
{
column.IsFileStream = source.IsFileStream;
column.IsSparse = source.IsSparse;
column.IsColumnSet = source.IsColumnSet;
}
copiedtable.Columns.Add(column);
}
}
The project perfectly well works with North wind database, however, with some tables from AdventureWorks2014 database I get the following inner exception at copiedtable.Create();:
NullReferenceException: Object reference not set to an instance of an object.
I suspect, that AdventureWorks datetime column may be causing the problem (Data is entered like: 2008-04-30 00:00:00.000)
I have solved this problem myself and it was quite interesting. I couldn't find any null values neither in the Table itself, nor in it's columns.
Then I realized, that AdventureWorks2014 DB used User defined Data Types and XML Schema collections. As I haven't copied them, they couldn't be accessed and the creation of the table failed. It was only necessary to copy XML Schema Collections and User Defined Data Types to second database:
private static void createUserDefinedDataTypes(Database originalDB, Database destinationDB)
{
foreach (UserDefinedDataType dt in originalDB.UserDefinedDataTypes)
{
Schema schema = destinationDB.Schemas[dt.Schema];
if (schema == null)
{
schema = new Schema(destinationDB, dt.Schema);
schema.Create();
}
UserDefinedDataType t = new UserDefinedDataType(destinationDB, dt.Name);
t.SystemType = dt.SystemType;
t.Length = dt.Length;
t.Schema = dt.Schema;
try
{
t.Create();
}
catch(Exception ex)
{
throw (ex);
}
}
}
private static void createXMLSchemaCollections(Database originalDB, Database destinationDB)
{
foreach (XmlSchemaCollection col in originalDB.XmlSchemaCollections)
{
Schema schema = destinationDB.Schemas[col.Schema];
if (schema == null)
{
schema = new Schema(destinationDB, col.Schema);
schema.Create();
}
XmlSchemaCollection c = new XmlSchemaCollection(destinationDB, col.Name);
c.Text = col.Text;
c.Schema = col.Schema;
try
{
c.Create();
}
catch(Exception ex)
{
throw (ex);
}
}
}

Parameter '?user_email' not found in the collection

I am using MySql 5.6x with Visual Studio 2015, windows 10, 64-bit. C# as programming language. In my CRUD.cs (Class file) i have created the following method:
public bool dbQuery(string sql,string[] paramList= null)
{
bool flag = false;
try
{
connect();
cmd = new MySqlCommand(sql,con);
cmd.Prepare();
if(paramList != null){
foreach(string i in paramList){
string[] valus = i.Split(',');
string p = valus[0];
string v = valus[1];
cmd.Parameters[p].Value = v;
}
}
if (cmd.ExecuteNonQuery() > 0)
{
flag = true;
}
}
catch (Exception exc)
{
error(exc);
}
}
I am passing the query and Parameters List like this:
protected void loginBtn_Click(object sender, EventArgs e)
{
string sql = "SELECT * FROM dept_login WHERE (user_email = ?user_email OR user_cell = ?user_cell) AND userkey = ?userkey";
string[] param = new string[] {
"?user_email,"+ userid.Text.ToString(),
"?user_cell,"+ userid.Text.ToString(),
"?userkey,"+ userkey.Text.ToString()
};
if (db.dbQuery(sql, param))
{
msg.Text = "Ok";
}
else
{
msg.Text = "<strong class='text-danger'>Authentication Failed</strong>";
}
}
Now the problem is that after the loop iteration complete, it directly jumps to the catch() Block and generate an Exception that:
Parameter '?user_email' not found in the collection.
Am i doing this correct to send params like that? is there any other way to do the same?
Thanks
EDIT: I think the best way might be the two-dimensional array to collect the parameters and their values and loop then within the method to fetch the parameters in cmd.AddWidthValues()? I may be wrong...
In your dbQuery you don't create the parameters collection with the expected names, so you get the error when you try to set a value for a parameter that doesn't exist
public bool dbQuery(string sql,string[] paramList= null)
{
bool flag = false;
try
{
connect();
cmd = new MySqlCommand(sql,con);
cmd.Prepare();
if(paramList != null){
foreach(string i in paramList){
string[] valus = i.Split(',');
string p = valus[0];
string v = valus[1];
cmd.Parameters.AddWithValue(p, v);
}
}
if (cmd.ExecuteNonQuery() > 0)
flag = true;
}
catch (Exception exc)
{
error(exc);
}
}
Of course this will add every parameter with a datatype equals to a string and thus is very prone to errors if your datatable columns are not of string type
A better approach would be this one
List<MySqlParameter> parameters = new List<MySqlParameter>()
{
{new MySqlParameter()
{
ParameterName = "?user_mail",
MySqlDbType= MySqlDbType.VarChar,
Value = userid.Text
},
{new MySqlParameter()
{
ParameterName = "?user_cell",
MySqlDbType= MySqlDbType.VarChar,
Value = userid.Text
},
{new MySqlParameter()
{
ParameterName = "?userkey",
MySqlDbType = MySqlDbType.VarChar,
Value = userkey.Text
},
}
if (db.dbQuery(sql, parameters))
....
and in dbQuery receive the list adding it to the parameters collection
public bool dbQuery(string sql, List<MySqlParameter> paramList= null)
{
bool flag = false;
try
{
connect();
cmd = new MySqlCommand(sql,con);
cmd.Prepare();
if(paramList != null)
cmd.Parameters.AddRange(paramList.ToArray());
if (cmd.ExecuteNonQuery() > 0)
{
flag = true;
}
}
catch (Exception exc)
{
error(exc);
}
}
By the way, unrelated to your actual problem, but your code doesn't seem to close and dispose the connection. This will lead to very nasty problems to diagnose and fix. Try to use the using statement and avoid a global connection variable
EDIT
As you have noticed the ExecuteNonQuery doesn't work with a SELECT statement, you need to use ExecuteReader and check if you get some return value
using(MySqlDataReader reader = cmd.ExecuteReader())
{
flag = reader.HasRows;
}
This, of course, means that you will get troubles when you want to insert, update or delete record where instead you need the ExecuteNonQuery. Creating a general purpose function to handle different kind of query is very difficult and doesn't worth the work and debug required. Better use some kind of well know ORM software like EntityFramework or Dapper.
Your SQL Commands' Parameters collection does not contain those parameters, so you cannot index them in this manner:
cmd.Parameters[p].Value = v;
You need to add them to the Commands' Parameters collection in this manner: cmd.Parameters.AddWithValue(p, v);.

Failed to enable constraints using TableAdapters

I'm trying to check if a username exists in my table when everytime a character is entered in the TextBox. Here is my code:
Within the register.aspx.cs file I have a TextChanged event on the TextBox:
protected void username_txt_TextChanged(object sender, EventArgs e)
{
string check = authentication.checkUsername(username_txt.Text);
if(check == "false")
{
username_lbl.Text = "Available";
}
else
{
username_lbl.Text = "Not Available";
}
}
It calls this method:
public static string checkUsername(string Username)
{
userInfoTableAdapters.usersTableAdapter userInfoTableAdapters = new userInfoTableAdapters.usersTableAdapter();
DataTable userDataTable = userInfoTableAdapters.checkUsername(Username);
DataRow row = userDataTable.Rows[0];
int rowValue = System.Convert.ToInt16(row["Users"]);
if (rowValue == 0)
{
return "false";
}
else
{
return "true";
}
}
The query that is being executed is:
SELECT COUNT(username) AS Users FROM users WHERE (username = #Username)
For some reason, it keeps breaking on this line:
DataTable userDataTable = userInfoTableAdapters.checkUsername(Username);
It gives an error that says:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Just incase, the username field in my table is Unique and Not Null, I have tried just executing the query itself and it works perfectly so it isn't at the query end.
Does anyone understand what I am doing wrong?
Your query doesn't return the row - so using a TableAdapter query that returns the DataTable is inappropriate in this case.
I'd recommend using your query with something like the function below. I took the liberty of actually returning boolean....
public static bool checkUsername(string userName)
{
SqlClient.SqlCommand withCmd = new SqlClient.SqlCommand();
bool result = false;
withCmd.Connection.Open();
withCmd.CommandType = CommandType.text;
withCmd.CommandText = "SELECT COUNT(username) AS Users FROM users WHERE (username = #Username)"
withCmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#Username", System.Data.SqlDbType.VarChar, 16)).Value = userName;
try {
int intResult;
object scalarResult = withCmd.ExecuteScalar();
if ((scalarResult != DBNull.Value)
&& (scalarResult != null)
&& (int.TryParse(scalarResult, out intResult)))
result = (intResult==1);
} catch (Exception ex) {
result = false; // hmm, bad...can't tell handle error...
} finally {
// only close if we opened the connection above ...
withCmd.Connection.Close();
}
}
return result;
}
A TableAdapter does support scalar queries on the Table Object, when you add and name your query, check the properties of that query and be sure its ExecuteMode is Scalar. It will then return the integer value, not the row!
On the other hand, if you want to keep your structure, change the query to actually return the row, something like
SELECT uu.* AS dbo.Users uu FROM users WHERE (username = #Username)
and make the result of the checkUsername() function depend on the number of rows returned (which should be 1 or zero....)

How to move to next row in datatable if one row catches an error? C# 2.0

I am getting data from a mySql database and I am inserting it into another system. If a column has data in an incorrect format I log this and go to next row in the datatable. It works as expected but now if I have a search function in my method that gets some additional data and this function fails I want to immediately log this and go to next row. As it is now I just log it but it still gets inserted (without the value that didn't meet the search criteria).
My code:
private void updateCustomer()
{
MySqlConnection connection = new MySqlConnection("server=myServer;database=myDatabase;uid=myID;password=myPass");
MySqlCommand command = new MySqlCommand(#"mySelectCommand", connection);
DataTable customerTbl = new DataTable();
MySqlDataReader reader;
try
{
connection.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
customerTbl.Load(reader);
}
reader.Close();
}
catch (Exception ex)
{
_out.error("Could not connect to mySql database");
}
finally
{
connection.Close();
}
foreach (DataRow row in customerTbl.Rows)
{
// Declare the customer variables
string customerID = Encoding.ASCII.GetString((byte[])row["Customer ID"]);
string ChildOf = row["Child of"].ToString();
// Create the customer object
Customer customer = new Customer();
customer.entityId = customerID;
if (ChildOf != "")
{
RecordRef parentRef = new RecordRef();
try
{
parentRef.internalId = searchCustomer(ChildOf);
}
catch
{
// If it fails here I want to log the customerID and then go to the next row in the datatable (could not find the internalid for ChildOf
_out.error(customerID + " was not updated. Error: invalid format Parent string");
}
finally
{
parentRef.typeSpecified = false;
customer.parent = parentRef;
}
}
// Invoke update() operation
WriteResponse response = _service.update(customer);
// Process the response
if (response.status.isSuccess)
{
}
else
{
_out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
}
}
}
You need to remove the row in the catch block, and change the foreach loop to a backwards for loop to handle the removals.
I realized that I want to log the other failed fields as well. Maybe it's an inefficient way but I did something like:
bool findParent = true;
if (ChildOf != "")
{
try
{
RecordRef parentRef = new RecordRef();
parentRef.internalId = searchCustomer(ChildOf);
parentRef.typeSpecified = false;
customer.parent = parentRef;
}
catch
{
findParent = false;
_out.error(customerID + " was not inserted. Error: invalid format Parent string");
}
}
And then an if statement before trying to insert:
if (findPartner == true && findParent == true)
{
response = _service.add(customer);
// Process the response
if (response.status.isSuccess)
{
}
else
{
_out.error(customerID + " was not inserted. Error: " + getStatusDetails(response.status));
}
}
else
{
//_out.error(customerID + " was not updated. Error: " + getStatusDetails(response.status));
}
Use the row.HasError property.

Categories

Resources