C# Programming Return ArrayList - c#

I am trying to return an error message for a method in my code, but I am unable to find the correct return object, I have searched on the internet but have no been successful in finding an answer.
The following is a code snippet:
public ArrayList getBeneficiaryID(string UserID)
{
try
{
//long Beneficiary_ID = 0;
//string BeneficiaryID = "";
ArrayList BeneficiaryArray = new ArrayList();
// Open connection to the database
string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["Databasebcfintec_alice"].ConnectionString;
aConn = new SqlConnection(strConn);
aConn.Open();
// Set up a command with the given query and associate
// this with the current connection.
string sql = "Select BeneficiaryID from Beneficiary where user_id = '" + UserID + "'";
cmd = new SqlCommand(sql);
cmd.Connection = aConn;
// Execute the query
odtr = cmd.ExecuteReader();
while (odtr.Read())
{
BeneficiaryArray.Add(odtr["BeneficiaryID"]);
//User_ID = (long)(odtr["user_id"]);
//UserID = User_ID.ToString();
}
odtr.Close();
return BeneficiaryArray;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.ToString());
//return ex.ToString();
return;
}
}
Error Message:
"An object of a type convertible to arraylist is required"
Another method I tried was using the following code:
return ex.ToString();
but it provided the following error message:
"Cannot implicitly convert type 'string' to
'System.Collections.ArrayList'

You can just put return null; or return new ArrayList();
since it looks like you don't care with what you're gonna get with the catch. You already have a console log.

The problem is that you have to return an object. You can't do
return;
because you're not returning anything. You also can't return a string because it can't be cast to an ArrayList.
You can, however, return null, which it sounds like is what you want.

In the catch section you should have to throw the exception.
public ArrayList MethodName(string UserID)
{
try
{
//write your code
}
catch (Exception )
{
//log the exception
throw ;
}
}

Related

Invoice number displayed blank

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

How to catch CLR exception in my code block (C#)

Here is my code:
private Message SendMessage(ref Message message, string serviceURL)
{
Message result = null;
try
{
IRequestChannel channel = null;
BasicHttpBinding binding = ...;
using (var cf = new ChannelFactory<IRequestChannel>(binding, new EndpointAddress(serviceURL)))
{
foreach (OperationDescription op in cf.Endpoint.Contract.Operations)
{
op.Behaviors.Remove<DataContractSerializerOperationBehavior>();
}
cf.Open();
channel = cf.CreateChannel();
channel.Open();
result = channel.Request(message);
channel.Close();
cf.Close();
channel = null;
}
binding = null;
}
catch (Exception ex)
{
Logger.LogError("Error parsing SOAP", ex.Message);
}
return result;
}
On line result = channel.Request(message);
I get an error posted below in a picture. However, I get it only when I turn "Break when" CLR exceptions occur. When I don't debug, my code doesn't go to the catch block.
Looks like you try serialize or deserialize string with value = 'X' to bool. I think you should check contract or check your message object.
Somewhere inside .net code calls XmlConvert.ToBoolean(String) method. Valid values for it 0 or 1 Link to doc

not all code paths return a value error on web method

I have a web method function has checks if a name exists in the database but I am getting the error:
Error 114 'lookups_Creditor.CheckIfNameExists(string)': not all code
paths return a value
Here is the web method:
[WebMethod]
public static bool CheckIfNameExists(string Name)//error on this line
{
try
{
Creditor.CheckIfNameCreditorExists(Company.Current.CompanyID, Name);
}
catch (Exception ex)
{
}
}
And here is the search function for the sql:
public static string CheckIfNameCreditorExists(int CompanyID, string Name)
{
DataSet ds = new DataSet();
string accNo = "";
string sql = "proc_CheckIfACCreditorExists";
string query = "SELECT c.* " +
" FROM Creditor c " +
" WHERE c.Company_ID = " + CompanyID + " AND c.Name LIKE '" + Name + "' ";
DataTable dt = new DataTable();
using (MySql.Data.MySqlClient.MySqlDataAdapter adapter = new MySql.Data.MySqlClient.MySqlDataAdapter(query, DataUtils.ConnectionStrings["TAT"]))
{
adapter.SelectCommand.CommandType = CommandType.Text;
adapter.SelectCommand.CommandText = query;
adapter.Fill(dt);
if (dt.Rows.Count > 0)
{
accNo = Convert.ToString(dt.Rows[0]["AccoutCode"]);
}
}
return accNo;
}
I am trying to create a method that searches for the name in the database. If the name exists, then return the account code associated with that name. I will the display a message on the screen telling the user that the name already exists on the account ABC.
[WebMethod]
public static bool CheckIfNameExists(string Name)//error on this line
{
bool Result = false;
try
{
Result = Creditor.CheckIfNameCreditorExists(Company.Current.CompanyID, Name) != "";
}
catch (Exception ex)
{
}
return Result
}
You have written the return type as Bool and you are not returning anything.
If you don't have anything to return then just make that return type to Void.
By the method name it indicates you should return either "True" or "False".
The error just indicates that, you should return something when you have a return type other than void in your methods.
Your method is supposed to return bool, yet you don't return anything.
You need to rewrite it something like this:
[WebMethod]
public static bool CheckIfNameExists(string Name)
{
bool res = false;
try
{
// Check your string result if it's null or empty
// and store the result in local variable
res = !string.IsNullOrEmpty(Creditor.CheckIfNameCreditorExists(Company.Current.CompanyID, Name));
}
catch (Exception ex)
{
// Do your handling here
}
return res;
}

Why an error message 'InvalidOperationException' has been occured

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.

How to test to see if mySql Database is working?

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.

Categories