I am creating a simple inventory system using c#.
When I am generating the invoice number, the form is loaded but it doesn't show anything.
It is an auto-incremented invoice number; order is completed incrementally by 1.
For example, starting at E-0000001, after order we expect E-0000002. I don't understand why it is blank.
No error displayed. I tried to debug the code but I couldn't find what's wrong.
public void invoiceno()
{
try
{
string c;
sql = "SELECT MAX(invoid) FROM sales";
cmd = new SqlCommand(sql, con);
var maxInvId = cmd.ExecuteScalar() as string;
if (maxInvId == null)
{
label4.Text = "E-000001";
}
else
{
int intVal = int.Parse(maxInvId.Substring(2, 6));
intVal++;
label4.Text = String.Format("E-{0:000000}", intVal);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.Write(ex.StackTrace);
}
}
Let's extract a method - NextInvoiceId - we
Open connection
Execute query
Obtain next invoice number
Code:
private int NextInvoiceNumber() {
//TODO: put the right connection string here
using(var conn = new SqlConnection(ConnectionStringHere)) {
conn.Open();
string sql =
#"SELECT MAX(invoid)
FROM sales";
using (var cmd = new SqlCommand(sql, conn)) {
var raw = cmd.ExecuteScalar() as string;
return raw == null
? 1 // no invoces, we start from 1
: int.Parse(raw.Trim('e', 'E', '-')) + 1;
}
}
}
Then we can easily call it:
public void invoiceno() {
label4.Text = $"E-{NextInvoiceNumber():d6}";
}
Edit: You should not swallow exceptions:
try
{
...
}
// Don't do this!
catch (Exception ex) // All the exceptions will be caught and...
{
// printed on the Console...
// Which is invisible to you, since you develop Win Forms (WPF) application
Console.WriteLine(ex.ToString());
Console.Write(ex.StackTrace);
}
let system die and inform you that something got wrong
Related
I have a ASP.Net app to call AS400 program in order to create a file under QTEMP. But when I try to select this file from QTEMP, it does not exist.
I understand the reason: call program and select file are different jobs. I cannot access other job's QTEMP.
I do not know much about the AS400, the only way I can find out is to create this file under another library other than QTEMP. But it will impact my other app functions which I do not want to do.
I am using cwbx.dll to call the AS400 program and then I am using IBM.Data.DB2.iSeries to select the file from QTEMP. Obviously they are two connections opened. I am not sure if under as400 concept, they may be two separate jobs.
Here is the function to call the program:
As400Caller1.CallAs400Program("myProgram", "myLibrary", paramsList1);
Here is the CallAs400Program function:
public void CallAs400Program(string programName, string libraryName, List<AS400Param> parameters) {
try
{
system.Connect(cwbcoServiceEnum.cwbcoServiceRemoteCmd);
//check connection
if (system.IsConnected(cwbcoServiceEnum.cwbcoServiceRemoteCmd) == 1)
{
//create a program object and link to the system
Program program = new Program();
program.LibraryName = libraryName;
program.ProgramName = programName;
program.system = system;
//create a parameter collection associated with the program and pass data
ProgramParameters prms = new ProgramParameters();
foreach (AS400Param p in parameters)
{
prms.Append(p.ParameterName, cwbrcParameterTypeEnum.cwbrcInout, p.ParameterLength);
if (!p.OutParam)
{
prms[p.ParameterName].Value = AS400ParamStringConverter.ConvertASCIItoEBCDIC(p.ParameterValue.PadRight(p.ParameterLength, ' '));
}
}
//call the program
try
{
program.Call(prms);
}
catch (Exception ex)
{
if (system.Errors.Count > 0)
{
foreach (cwbx.Error error in system.Errors)
{
throw ex;
}
}
if (program.Errors.Count > 0)
{
foreach (cwbx.Error error in program.Errors)
{
throw ex;
}
}
}
}
else
{
Console.WriteLine("No AS400 Service connection");
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (system.IsConnected(cwbcoServiceEnum.cwbcoServiceRemoteCmd) == 1)
system.Disconnect(cwbcoServiceEnum.cwbcoServiceAll);
}
}
Here is my select SQL code:
try
{
List<TableRowModel> dataList = new List<TableRowModel>();
string library = "QTEMP";
string cmdText = $#"SELECT * FROM {library}.myFile";
iDB2Command command = new iDB2Command(cmdText);
command.Connection = IDB2Context.Current;
iDB2DataReader reader = command.ExecuteReader();
while (reader.Read())
{
}
return dataList;
}
catch (Exception ex)
{
throw ex;
}
Exception throw:
myFile in QTEMP type *FILE not found.
How can I use C# to solve the issue of accessing other Jobs QTEMP?
QTEMP is session specific...you can't access it from another job..
Consider an using an SQL Stored procedure that you can call from .NET.
The stored proc can call the RPG program and the return the results from the file in QTEMP all in a single call.
I need to load data from SQLite to memory, and when the table contains more than 40k entries this process lasts for a few minutes. Data in db is encrypted so I decrypt it to load in memory.
Basically, I am:
loading all the data from the table
while it is reading I decrypt the info and add it to a dictionary
The code:
internal static void LoadInfo(Dictionary<int, InfoMemory> dic)
{
using (SQLiteConnection con = new SQLiteConnection(conString))
{
using (SQLiteCommand cmd = con.CreateCommand())
{
cmd.CommandText = String.Format("SELECT ID, Version, Code FROM Employee;");
int ID, version, code;
try
{
con.Open();
using (SQLiteDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
try { ID = Convert.ToInt32(Decrypt(rdr[0].ToString())); }
catch { ID = -1; }
try { version = Convert.ToInt32(Decrypt(rdr[1].ToString())); }
catch { version = -1; }
try { code = Convert.ToInt32(Decrypt(rdr[2].ToString())); }
catch { code = -1; }
if (ID != -1)
{
if (!dic.ContainsKey(ID)) dic.Add(ID, new InfoMemory(version, code));
}
}
rdr.Close();
}
}
catch (Exception ex) { Log.Error(ex.Message); }
finally { con.Close(); GC.Collect(); }
}
}
}
How can I make this process faster?
One way I try is by loading encrypted data to memory and decrypt when needed, but if I do that I consume more memory. Since I am working in mobile devices I want to maintain the memory consumption as low as possible.
One thing you can do is; instead of using try/catch:
int id, version, code;
if(!int.TryParse(rdr[0], out id))
{
id = -1;
}
if(!int.TryParse(rdr[1], out version))
{
version = -1;
}
if(!int.TryParse(rdr[2], out code))
{
code = -1;
}
The following code gives me the error (I get it from the MessageBox.Show() in the catch block)
"Exception in PopulateBla() : There is a file sharing violation. A
different process might be using the file [,,,,,,]
CODE
using (SqlCeCommand cmd = new SqlCeCommand(SQL_GET_VENDOR_ITEMS, new SqlCeConnection(SQLCE_CONN_STR)))
{
cmd.Parameters.Add("#VendorID", SqlDbType.NVarChar, 10).Value = vendorId;
cmd.Parameters.Add("#VendorItemID", SqlDbType.NVarChar, 19).Value = vendorItemId;
try
{
cmd.Connection.Open();
using (SqlCeDataReader SQLCEReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if (SQLCEReader.Read())
{
itemID = SQLCEReader.GetString(ITEMID_INDEX);
packSize = SQLCEReader.GetString(PACKSIZE_INDEX);
recordFound = true;
}
}
}
catch (SqlCeException err)
{
MessageBox.Show(string.Format("Exception in PopulateControlsIfVendorItemsFound: {0}\r\n", err.Message));//TODO: Remove
}
finally
{
if (cmd.Connection.State == ConnectionState.Open)
{
cmd.Connection.Close();
}
}
}
SQL_GET_VENDOR_ITEMS is my query string.
What file sharing problem could be happening here?
UPDATE
This is the kind of code that makes that sort of refactoring recommended by ctacke below difficult:
public void setINVQueryItemGroup( string ID )
{
try
{
dynSQL += " INNER JOIN td_item_group ON t_inv.id = td_item_group.id AND t_inv.pack_size = td_item_group.pack_size WHERE td_item_group.item_group_id = '" + ID + "'";
}
catch( Exception ex )
{
CCR.ExceptionHandler( ex, "InvFile.setINVQueryDept" );
}
}
A SQL statement is being appended to by means of a separate method, altering a global var (dynSQL) while possibly allowing for SQL Injection (depending on where/how ID is assigned). If that's not enough, any exception thrown could mislead the weary bughunter due to indicating it occurred in a different method (doubtless the victim of a careless copy-and-paste operation).
This is "Coding Horror"-worthy. How many best practices can you ignore in a scant few lines of code?
Here's another example:
string dynSQL = "SELECT * FROM purgatory WHERE vendor_item = '" + VendorItem + "' ";
if (vendor_id != "")
{
dynSQL += "AND vendor_id = '" + vendor_id + "' ";
}
It could be done by replacing the args with "?"s, but the code to then determine which/how many params to assign would be 42X uglier than Joe Garagiola's mean cleats.
I really like Chris' idea of using a single connection to your database. You could declare that global to your class like so:
public ClayShannonDatabaseClass
{
private SqlCeConnection m_openConnection;
public ClayShannonDatabaseClass()
{
m_openConnection = new SqlCeConnection();
m_openConnection.Open();
}
public void Dispose()
{
m_openConnection.Close();
m_openConnection.Dispose();
m_openConnection = null;
}
}
I'm guessing your code is crashing whenever you attempt to actually open the database.
To verify this, you could stick an integer value in the code to help you debug.
Example:
int debugStep = 0;
try
{
//cmd.Connection.Open(); (don't call this if you use m_openConnection)
debugStep = 1;
using (SqlCeDataReader SQLCEReader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
debugStep = 2;
if (SQLCEReader.Read())
{
debugStep = 3;
itemID = SQLCEReader.GetString(ITEMID_INDEX);
debugStep = 4;
packSize = SQLCEReader.GetString(PACKSIZE_INDEX);
debugStep = 5;
recordFound = true;
}
}
}
catch (SqlCeException err)
{
string msg = string.Format("Exception in PopulateControlsIfVendorItemsFound: {0}\r\n", err.Message);
string ttl = string.Format("Debug Step: {0}", debugStep);
MessageBox.Show(msg, ttl); //TODO: Remove
}
// finally (don't call this if you use m_openConnection)
// {
// if (cmd.Connection.State == ConnectionState.Open)
// {
// cmd.Connection.Close();
// }
// }
I'm guessing your error is at Step 1.
Provided the file isn't marked read-only (you checked that, right?), then you have another process with a non-sharing lock on the file.
The isql.exe database browser that comes with SQL CE is a common culprit if it's running in the background.
Depending on your version of SQLCE, it's quite possible that another process has an open connection (can't recall what version started allowing multiple process connections), so if you have any other app in the background that has it open, that may be a problem too.
You're also using a boatload of connections to that database, and they don't always get cleaned up and released immediately up Dispose. I'd highly recommend building a simple connection manager class that keeps a single (or more like two) connections to the database and just reuses them for all operations.
My code as follows:
namespace EntityDAO
{
public static class StudentDAO
{
public static Boolean AddStudent(StudentDTO oDto)
{
string str =System.Configuration.ConfigurationManager.AppSettings["myconn"];
SqlConnection oconnection = new SqlConnection(str);
oconnection.Open();
try
{
string addstring = "insert into STUDENT(ID,NAME)values('"
+ oDto.ID + "','"
+ oDto.NAME + "')";
SqlCommand ocommand = new SqlCommand(addstring,oconnection);
ocommand.ExecuteNonQuery();
return true;
}
catch
{
return false;
}
finally
{
oconnection.Close();
}
but when I run this program ,an error message has been occured and the error message for oconnection.Open(); and the message is 'InvalidOperationException'(Instance failure).I have tried many times to solve this problem but i did't overcome this problem.so please,anyone help me.
The following is not proposed as a complete solution to your problem, but should help you figure it out:
namespace EntityDAO
{
public static class StudentDAO
{
public static Boolean AddStudent(StudentDTO oDto)
{
var str = ConfigurationManager.AppSettings["myconn"];
using (var oconnection = new SqlConnection(str))
{
oconnection.Open();
try
{
var addstring = string.Format(
"insert into STUDENT(ID,NAME)values('{0}','{1}')", oDto.ID, oDto.NAME);
using (var ocommand = new SqlCommand(addstring, oconnection))
{
ocommand.ExecuteNonQuery();
}
return true;
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
return false;
}
}
}
}
}
Don't ever hide exceptions from yourself. Even if the caller of this code wants true or false, make sure you log the details of the exception.
Also, what AYK said about SQL Injection. I'm entering this as CW, so if someone has more time than I do, they should feel free to edit to use parameters.
I am new to MySQL database, I am using Visual Studio C# to connect to my database. I have got a following select method. How can I run it to check if it is working?
EDITED The open and close connection methods
//Open connection to database
private bool OpenConnection()
{
try
{
// connection.open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server.");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
Select method which is in the same class as the close and open connection as shown above
public List<string>[] Select()
{
string query = "SELECT * FROM Questions";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
list[3] = new List<string>();
list[4] = new List<string>();
list[5] = new List<string>();
list[6] = new List<string>();
list[7] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"] + "");
list[1].Add(dataReader["difficulty"] + "");
list[2].Add(dataReader["qustions"] + "");
list[3].Add(dataReader["c_answer"] + "");
list[4].Add(dataReader["choiceA"] + "");
list[5].Add(dataReader["choiceB"] + "");
list[6].Add(dataReader["choiceC"] + "");
list[7].Add(dataReader["choiceD"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
This method is in a separate class which has got all the database connection settings. Now that I want to call this method from my main class to test it to see if it's working, how can I do this?
You should create an object instance of that DB class and then call the Select() method.
So, supposing that this DB class is named QuestionsDB you should write something like this:
QuestionDB questionDAL = new QuestionDB();
List<string>[] questions = questionDAL.Select();
However, before this, please correct this line
List<string>[] list = new List<string>[8]; // you need 8 lists for your db query
You could check if you have any record testing if the first list in your array list has more than zero elements.
if(questions[0].Count > 0)
... // you have read records.
However, said that, I will change your code adding a specific class for questions and using a list(of Question) instead of an array of list
So, for example, create a class like this
public class Question
{
public string ID;
public string Difficulty;
public string Question;
public string RightAnswer;
public string AnswerA;
public string AnswerB;
public string AnswerC;
public string AnswerD;
}
and change your select to return a List(of Question)
List<Question> list = new List<Question>;
......
while (dataReader.Read())
{
Question qst = new Question();
qst.ID = dataReader["id"] + "";
qst.Difficulty = dataReader["difficulty"] + "";
qst.Question = dataReader["qustions"] + "";
qst.RightAnswer = dataReader["c_answer"] + "";
qst.AnswerA = dataReader["choiceA"] + "";
qst.AnswerB = dataReader["choiceB"] + "";
qst.AnswerC = dataReader["choiceC"] + "";
qst.AnswerD = dataReader["choiceD"] + "";
list.Add(qst);
}
return list;
You can test whether the method works by writing a unit test for it. A good unit testing frame work is Nunit. Before you call this you must create and open a connection to the DB:
//Open connection
if (this.OpenConnection() == true)
{
as the other person said, you will want to fix the lists up.