Get output from Stored Procedure using Console - c#

Hi I'm trying to produce an output from console but keep getting the error message
Procedure or function 'p_Date_sel'
expects parameter '#DateID', which was
not supplied
Suppose to get the DateID and display all the data,please tell me what I'm doing wrong.
Below is my stored procedure
ALTER procedure [dbo].[p_Date_sel]
#DateID int
AS
BEGIN
SELECT DateTypeID , Date , Name, Notes
FROM dbo.Dates
WHERE DateID= #DateID
END
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
namespace ExecuteStoredProcedure
{
class Program
{
private int _dateID;
private int _dateTypeID;
private DateTime _date;
private string _name;
private string _notes;
public Program()
{
_dateID = 0;
}
public Program(int dateID) {
_dateID = dateID;
}
public Program(int datetypeID,DateTime date,string name,string notes){
_dateTypeID = datetypeID;
_date = date;
_name = name;
_notes = notes;
}
public int dateID
{
get {return _dateID;}
}
public int dateTypeID
{
get { return _dateTypeID; }
set { _dateTypeID = value; }
}
public DateTime date
{
get {return _date ;}
set { _date = value;}
}
public string name
{
get { return _name;}
set { _name = value; }
}
public string notes
{
get { return _notes;}
set { _notes = value; }
}
public void LoadData()
{
SqlConnection conn = new SqlConnection("Data Source=mycbj01psql03\\sandbox01;Initial Catalog=DBRMS;Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("p_Date_sel", conn);
command.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
_dateTypeID = Convert.ToInt16(reader["DateTypeID"]);
_date = Convert.ToDateTime(reader["Date"]);
_name = reader["Name"].ToString();
_notes = reader["Notes"].ToString();
}
reader.Close();
conn.Close();
}
}
}
My Main Program
namespace ExecuteStoredProcedure
{
class TestClass
{
public static void Main(string[] args)
{
Program p = new Program(5);
p.LoadData();
Console.WriteLine("DateID = " + "" + p.dateID);
Console.WriteLine("DateTypeID = " + "" + p.dateTypeID);
Console.WriteLine("Date = " + "" + p.date);
Console.WriteLine("Name = " + "" + p.name);
Console.WriteLine("Notes = " + "" + p.notes);
Console.ReadLine();
}
}
}

Well, you need to supply a value for #DateID!
Your stored proc requires a parameter called #DateID or type INT:
ALTER procedure [dbo].[p_Date_sel]
#DateID int
but in your call, you never ever do supply such a value!
What you need to do is create a SqlParameter and pass in that value to the stored proc. Also, I would strongly recommend to make use of the using() {...} constructs for your sql client code. And as a last recommendation: why not make the DateID a parameter of the LoadData() method?? The way you have it now, you have to create an instance of your class for each value you want to retrieve - not very efficient and useful....
public void LoadData(int dateID)
{
using(SqlConnection conn = new SqlConnection("Data Source=mycbj01psql03\\sandbox01;Initial Catalog=DBRMS;Integrated Security=True"))
{
using(SqlCommand command = new SqlCommand("p_Date_sel", conn))
{
command.CommandType = CommandType.StoredProcedure;
// define the parameter and give it a value!
command.Parameters.Add("#DateID", SqlDbType.Int);
command.Parameters["#DateID"].Value = dateID;
conn.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
_dateTypeID = Convert.ToInt16(reader["DateTypeID"]);
_date = Convert.ToDateTime(reader["Date"]);
_name = reader["Name"].ToString();
_notes = reader["Notes"].ToString();
}
reader.Close();
}
conn.Close();
}
}
That way, you should get your stored proc to work properly. Call it from your main app like this:
Program p = new Program();
p.LoadData(5);

Related

value from a method to bind in Viewbag methods

Trying to return value from GetStage_details() methods and bind it to ViewBag.Stage_details but getting error at var result.
Error msg is :
can't implicitly convert type oracle.ManagedDtaAccessclient.oracledatareader to System.Collection.generic.List<Models.Stage_Details."
Any idea how to resolve it show that correct value return from table and bind to ViewBag.Stage_details will be appreciated.
public class Stage_details
{
public int Stage_Cd { get; set; }
public string Stage_Desc { get; set; }
}
public ActionResult Index_shift()
{
ViewBag.Stage_details = new SelectList(GetStage_details(), "Stage_Cd", "Stage_Desc");
}
private List<Stage_details> GetStage_details()
{
List<Stage_details> Stage_detail = new List<Stage_details>();
OracleConnection conn = new
OracleConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());
conn.Open();
string cmdText= "select a.stage_cd,a.stage_desc from Stage_Mst a";
OracleCommand command = new OracleCommand(cmdText,conn);
command.CommandType = CommandType.Text;
var result = command.ExecuteReader();
return result;
}
According to Microsoft documentation, You could read each element from reader and build Stage_detail object inside loop, like the following code :
private List<Stage_details> GetStage_details()
{
List<Stage_details> Stage_detail = new List<Stage_details>();
OracleConnection conn = new
OracleConnection(ConfigurationManager.ConnectionStrings["Mycon"].ToString());
conn.Open();
string cmdText = "select a.stage_cd,a.stage_desc from Stage_Mst a";
OracleCommand command = new OracleCommand(cmdText, conn)
{
CommandType = CommandType.Text
};
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Stage_detail.Add(new Stage_details { Stage_Cd = (int)reader["stage_cd"], Stage_Desc = reader["stage_desc"].ToString() });
}
}
return Stage_detail;
}
I hope you find this helpful.

How to get a specific string out of a database with C# using a parameter that can change in layer model

I need to make a helpdesk form for my end of year task and I'm stuck.
The task requires me to load the solution of a specific problem that the user selects via a combobox. My implementation needs to separated into layers like business persist and so on.
The code that I wrote to solve this didn't work (EXPLAIN WHY HERE). I have made a few attempts at it and have included them below.
First Attempt:
For my first attempt, I have written the following code to load the solution to the selected problem from the database:
public List<HelpDesk> getOplossing()
{
List<HelpDesk> lijst = new List<HelpDesk>();
MySqlConnection conn = new MySqlConnection(_connectionstring);
MySqlCommand cmd = new MySqlCommand("SELECT Oplosing from tblhelpdesk where Probleem = #probleem" , conn);
cmd.Parameters.Add(new MySqlParameter("#probleem",
getProbleem().ToString()));
conn.Open();
MySqlDataReader datareader = cmd.ExecuteReader();
while (datareader.Read())
{
HelpDesk hlpdsk = new HelpDesk(
datareader["Oplosing"].ToString());
lijst.Add(hlpdsk);
}
conn.Close();
return lijst;
}
And in the controller I called it like this:
public List<HelpDesk> getOplossing()
{
return _persistcode.getOplossing();
}
Attempt 2:
This is what I wrote for my second attempt.
public string getOplossing()
{
MySqlConnection conn = new MySqlConnection(_connectionstring);
MySqlCommand cmd = new MySqlCommand("SELECT Oplosing from tblhelpdesk", conn);
conn.Open();
string oplossing;
oplossing = cmd.ExecuteScalar().ToString();
conn.Close();
return oplossing;
}
Again in the controller:
public string getOplossing()
{
return _persistcode.getOplossing();
}
My entire HelpDesk class:
And the class HelpDesk looks like this: (I provided the whole class so you guys can have a gander at all the problem :/ )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GPDeBruykerSander_Domain.Business
{
public class HelpDesk
{
private int _id;
private Boolean _categorie; //Hardware= True en Software= False
private DateTime _datumProbleem;
private string _probleem;
private DateTime _datumOplossing;
private string _oplossing;
public int ID
{
get { return _id; }
set { _id = value; }
}
public override string ToString()
{
return Probleem;
}
public Boolean Categorie
{
get { return _categorie; }
set { _categorie = value; }
}
public DateTime DatumProbleem
{
get { return _datumProbleem; }
set { _datumProbleem = value; }
}
public string Probleem
{
get { return _probleem; }
set { _probleem = value; }
}
public DateTime DatumOplossing
{
get { return _datumOplossing; }
set { _datumOplossing = value; }
}
public string Oplossing
{
get { return _oplossing; }
set { _oplossing = value; }
}
public HelpDesk (int id, Boolean categorie, DateTime datumProbleem, string probleem, DateTime datumOplossing, string oplossing)
{
_id = id;
_categorie = categorie;
_datumProbleem = datumProbleem;
_probleem = probleem;
_datumOplossing = datumOplossing;
_oplossing = oplossing;
}
public HelpDesk(Boolean categorie, DateTime datumProbleem, string probleem, DateTime datumOplossing, string oplossing)
{
_categorie = categorie;
_datumProbleem = datumProbleem;
_probleem = probleem;
_datumOplossing = datumOplossing;
_oplossing = oplossing;
}
public HelpDesk(DateTime datumProbleem, Boolean categorie, string probleem)
{
_datumProbleem = datumProbleem;
_categorie = categorie;
_probleem = probleem;
}
public HelpDesk(DateTime datumOplossing, string oplossing)
{
_datumOplossing = datumOplossing;
_oplossing = oplossing;
}
public HelpDesk(string probleem)
{
_probleem = probleem;
}
}
}
I hope somebody can help me find the solution because I'm stuck :/
You were closer to solving your problem in your first attempt, so I will help you with that. But since you haven't actually provided any reasons as to why your code doesn't work (errors thrown by the application, etc.), I can only take a stab at potential issues I see in your code.
Looking at your MySQL query: SELECT Oplosing from tblhelpdesk where Probleem = #probleem, I would say that you are missing quotes around #probleem. So this query should look like this:
SELECT Oplosing from tblhelpdesk where Probleem = '#probleem'
I would also make the following suggestions:
Suggestion 1: Make getProbleem() method actually return a string, so you don't have to call ToString() on it. You haven't provided the implementation of this method so I can only assume the return type is not a string. If the return type is a string the ToString() is completely redundant here.
Suggestion 2:
I would also suggestion is that you pass the problem string as a parameter to getOplossing(), so that the database code is encapsulated better. For example:
public List<HelpDesk> getOplossing(string probleem)
{
...
cmd.Parameters.Add(new MySqlParameter("#probleem", probleem));
...
}
And your controller will call it like so:
public List<HelpDesk> getOplossing()
{
string probleem = getProbleem().ToString();
return _persistcode.getOplossing(probleem);
}

Why do I get Error StreamReader in my .NET webservice with JSON?

I want to create a .NET webservice using C# with JSON. but I've error in my return statement on my webservice, cannot implicitly convert type 'string' to 'Model.User'
how to resolve that error line?
Here is my WebService.asmx :
[OperationContract]
public Model.User GetUser(string ccduser)
{
Model.User user = new Model.User();
string connectionString = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString)) {
string sql = "Select * from ms_webuser where ccduser = '" + ccduser + "'";
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
user.cnmuser = reader["cnmuser"].ToString();
}
}
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Model.User));
serializer.WriteObject(stream, user);
stream.Position = 0;
StreamReader streamReader = new StreamReader(stream);
return streamReader.ReadToEnd(); //here is the error red line
}
Here is my Model.User Class:
namespace Model
{
public class User
{
private string _ccduser;
private string _cnmuser;
public string ccduser
{
get { return _ccduser; }
set { _ccduser = value; }
}
public string cnmuser
{
get { return _cnmuser; }
set { _cnmuser = value; }
}
}
}
You get that error because the ReadToEnd method returns a string and you have declared your method to return a Model.User
To resolve it you should return the user you want to return instead or you should change the method to return a string.

"Object reference not set to an instance of an object." in C#, SQL 2005, VS 2008

I am trying to select "food_ItemName" and "food_UnitPrice" from "t_Food" table in SQL Server 2005.
I have the following code:
private void GetDatabaseConnection()
{
string connectionString = #"Server = RZS-F839AD139AA\SQLEXPRESS; Integrated Security = SSPI; Database = HotelCustomerManagementDatabase";
connection = new SqlConnection(connectionString);
connection.Open();
}
and.....
public Food PopulateFoodItemListview()
{
GetDatabaseConnection();
string selectFoodItemQuery = #"SELECT food_ItemName, food_UnitPrice FROM t_Food";
SqlCommand command = new SqlCommand(selectFoodItemQuery, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
food.ItemName.Add(reader.GetString(0)); // Exception is generated in this line
food.UnitPrice.Add(reader.GetDouble(1));
}
connection.Close();
return food;
}
In food class I have the following code:
public class Food
{
private List<string> itemName;
private List<double> unitPrice;
private double itemUnit;
private Customer foodCustomer = new Customer();
public Food ()
{
}
public Food(List<string> itemName, List<double> unitPrice) : this()
{
this.itemName = itemName;
this.unitPrice = unitPrice;
}
public List<string> ItemName
{
get { return itemName; }
set { itemName = value ; }
}
public List<double> UnitPrice
{
get { return unitPrice; }
set { unitPrice = value; }
}
public double ItemUnit
{
get { return itemUnit; }
set { itemUnit = value; }
}
}
but it generating following exception. Why?
"Object reference not set to an instance of an object."
You need to create an instance of the 'itemName' and 'unitPrice' variables before you can add to either of them. You can go ahead and do that when you are declaring them.
private List<string> itemName = new List<string>();
private List<double> unitPrice = new List<string>();
Well to start:
ConnectionStrings should go into the app.config/web.config.
ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString
Use the following code to open/close connection:
using(SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
}
And try to avoid having nulls in the reader...
SELECT ISNULL(food_ItemName, ''), ISNULL(food_UnitPrice, 0.0)
EDIT:
You forgot to initialize the private member of the class Food
Edit to those lines:
private List<string> itemName = new List<string>;
private List<double> unitPrice = new List<double>;
Or do it like this
public List<string> ItemName
{
get
{
if (itemName == null) itemName = new List<string>;
return itemName;
}
}
public List<double> UnitPrice
{
get
{
if (unitPrice== null) unitPrice= new List<double>;
return unitPrice;
}
}
On which variable does it complain?
It looks like the problematic one (well, maybe there are more problems but this one is for sure can cause the exception) is ItemName which is not initiated.
Have you looked at your stack trace to figure out which line the error is occurring on or which function?
From what I could see it look like it may be referring to your food object in the PopulateFoodItemListview() method. The food object is never created.

Databinding in combo box

I have two forms, and a class, queries return in Stored procedure.
-- Stored Procedure:
ALTER PROCEDURE [dbo].[Payment_Join]
#reference nvarchar(20)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT p.iPaymentID
, p.nvReference
, pt.nvPaymentType
, p.iAmount
, m.nvMethod
, u.nvUsers
, p.tUpdateTime
FROM Payment p
, tblPaymentType pt
, tblPaymentMethod m
, tblUsers u
WHERE p.nvReference = #reference
and p.iPaymentTypeID = pt.iPaymentTypeID
and p.iMethodID = m.iMethodID
and p.iUsersID = u.iUsersID
END
// payment.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace Finance {
class payment {
string connection = global::Finance.Properties.Settings.Default.PaymentConnectionString;
#region Fields
int _paymentid = 0;
string _reference = string.Empty;
string _paymenttype;
double _amount = 0;
string _paymentmethod;
string _employeename;
DateTime _updatetime = DateTime.Now;
#endregion
#region Properties
public int paymentid
{
get { return _paymentid; }
set { _paymentid = value; }
}
public string reference
{
get { return _reference; }
set { _reference = value; }
}
public string paymenttype
{
get { return _paymenttype; }
set { _paymenttype = value; }
}
public string paymentmethod
{
get { return _paymentmethod; }
set { _paymentmethod = value; }
}
public double amount
{
get { return _amount;}
set { _amount = value; }
}
public string employeename
{
get { return _employeename; }
set { _employeename = value; }
}
public DateTime updatetime
{
get { return _updatetime; }
set { _updatetime = value; }
}
#endregion
#region Constructor
public payment()
{
}
public payment(string refer)
{
reference = refer;
}
public payment(int paymentID, string Reference, string Paymenttype, double Amount, string Paymentmethod, string Employeename, DateTime Time)
{
paymentid = paymentID;
reference = Reference;
paymenttype = Paymenttype;
amount = Amount;
paymentmethod = Paymentmethod;
employeename = Employeename;
updatetime = Time;
}
#endregion
#region Methods
public void Save()
{
try
{
SqlConnection connect = new SqlConnection(connection);
SqlCommand command = new SqlCommand("payment_create", connect);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#reference", reference));
command.Parameters.Add(new SqlParameter("#paymenttype", paymenttype));
command.Parameters.Add(new SqlParameter("#amount", amount));
command.Parameters.Add(new SqlParameter("#paymentmethod", paymentmethod));
command.Parameters.Add(new SqlParameter("#employeename", employeename));
command.Parameters.Add(new SqlParameter("#updatetime", updatetime));
connect.Open();
command.ExecuteScalar();
connect.Close();
}
catch
{
}
}
public void Load(string reference)
{
try
{
SqlConnection connect = new SqlConnection(connection);
SqlCommand command = new SqlCommand("Payment_Join", connect);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Reference", reference));
//MessageBox.Show("ref = " + reference);
connect.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
this.reference = Convert.ToString(reader["nvReference"]);
// MessageBox.Show(reference);
// MessageBox.Show("here");
// MessageBox.Show("payment type id = " + reader["nvPaymentType"]);
// MessageBox.Show("here1");
this.paymenttype = Convert.ToString(reader["nvPaymentType"]);
// MessageBox.Show(paymenttype.ToString());
this.amount = Convert.ToDouble(reader["iAmount"]);
this.paymentmethod = Convert.ToString(reader["nvMethod"]);
this.employeename = Convert.ToString(reader["nvUsers"]);
this.updatetime = Convert.ToDateTime(reader["tUpdateTime"]);
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Check it again" + ex);
}
}
#endregion
}
}
I have already binded the combo box items through designer,
When I run the application I just get the reference populated in form 2 and combo box just populated not the particular value which is fetched. New to c# so help me to get familiar
Assuming WinForms...
The ComboBox control has three properties to be used while using DataBinding.
DataSource;
DisplayMember;
ValueMember.
DataSource
A data source can be a database, a Web service, or an object that can later be used to generate data-bound controls. When the DataSource property is set, the items collection cannot be modified.
DisplayMember
The controls that inherit from ListControl can display diverse types of objects. If the specified property does not exist on the object or the value of DisplayMember is an empty string (""), the results of the object's ToString method are displayed instead.
If the new display member cannot be set, the previous display member setting is maintained.
ValueMember
Specify the contents of the ValueMember property in cases where you bind data.
You can clear the ValueMember property by setting the property to an empty string ("") or a null reference (Nothing in Visual Basic).
Setting a new ValueMember property raises the ValueMemberChanged and SelectedValueChanged events.
Now, the result of your stored procedure shall get stored in memory in an IList, BindingList<T> or any other bindable collection.
This collection should be set as the DataSource of your ComboBox. The best approach, in my opinion, is through a BindingSource.
Here's an example:
public partial class Form1 : Form {
private BindingSource bindingSource1;
public Form1() {
InitializeComponent();
bindingSource1 = new BindingSource();
comboBox1.DataSource = bindingSource1;
comboBox1.DisplayMember = "PaymentMethod";
comboBox1.ValueMember = "PaymentId";
bindingSource1.DataSource = GetPayments(); // GetPayments() shall return one of the above-mentioned bindable collections of payments.
}
}
Check if this helps you.

Categories

Resources