Npgsql passing an array of parameters - asp.net

I am new in using Npgsql and I tried to make an helper in my asp.net project so that I can call it conveniently in my controllers method.
npgsqlqueryhelper
public DataSet ExecuteQueryWithParams(string commandText, params NpgsqlParameter[] parameters)
{
using (var connection = npgsqlcon.GetnpgsqlConnection())
using (NpgsqlCommand command = new NpgsqlCommand(commandText, connection))
{
DataSet ds = new DataSet();
command.Parameters.AddRange(parameters);
command.CommandTimeout = 5000;
NpgsqlDataAdapter da = new NpgsqlDataAdapter(command);
da.Fill(ds);
connection.Close();
return ds;
}
}
My Controller Method
List<rollingPAR> rollingparlist = new List<rollingPAR>();
npgsqlhelper = new npgsqlQueryHelper();
NpgsqlParameter[] parameterList = {
new NpgsqlParameter("#lid", r.lid),
new NpgsqlParameter("#posting_date", r.date_end)
};
var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status()", parameterList).Tables[0];
rollingparlist = table.AsEnumerable().Select(row => new rollingPAR
{
get_payment_status = row.Field<int>("get_payment_status")
}).ToList();
As I tried to run my program, I always encountered an error saying that function ln.get_payment_status() does not exist but when I tried to supply the parameters directly on the query
(e.g var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status(1231,'06-18-2019')", parameterList).Tables[0];)
It gives me the data that I need. I don't know what is my mistake and I'm stuck here since yesterday. Can anyone help me with this? TIA

The parameter place holders are not automatically included in the function call. Try adding them:
var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status(#lid,#posting_date)", parameterList).Tables[0];

With the help of Sir #JGH, it turns out that my query is missing the parameter placeholders but after I edit it, I encountered an error regarding the datatype between the asp.net datetime and postgresql date so I added this code to remove the error.
parameterList[1].NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Date;
So here is now the new code:
List<rollingPAR> rollingparlist = new List<rollingPAR>();
npgsqlhelper = new npgsqlQueryHelper();
NpgsqlParameter[] parameterList = {
new NpgsqlParameter("#lid", r.lid),
new NpgsqlParameter("#posting_date", r.date_end)
};
parameterList[1].NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Date;
var table = npgsqlhelper.ExecuteQueryWithParams("SELECT ln.get_payment_status(#lid,#posting_date)", parameterList).Tables[0];
rollingparlist = table.AsEnumerable().Select(row => new rollingPAR
{
get_payment_status = row.Field<int?>("get_payment_status")
}).ToList();
Thank you sir #JGH

Related

How to store stored procedure results to a variable in Entity Framework?

How do I store the results from my stored procedure to variables? Here is my sample code:
public ActionResult ManageProfile(string eid)
{
var vm = new ManageProfileViewModel(); // Call ViewModel
sp_GetUserDetails_Result gResult = db_RIRO.sp_GetUserDetails(Session["EID"].ToString()).First();
// Get UserId, FirstName, LastName from stored procedure result
gResult.UserId = vm.UserId;
gResult.FirstName = vm.FirstName;
gResult.LastName = vm.LastName;
return View(vm);
}
The stored procedure works fine when I manually try to execute it in Management Studio. The problem with my code is after executing it returns a null.
Assigning of my variables should be the other way around.
vm.FirstName = gResult.SAPID
instead of
gResult.SAPID = vm.FirstName.
It is difficult to tell you without seeing the stored procedure.
Make sure your stored procedure has output parameter.
For example, if you have a output variable "#userId" from stored procedure:
something like in your code:
sqlcmd.Parameters.Add("#userId", SqlDbType.NVarChar, 4000).Value = "";
sqlcmd.Parameters["#userId"].Direction = ParameterDirection.Output;using
using (SqlConnection conn = new SqlConnection(dbConnStr))
{
sqlcmd.Connection = conn;
conn.Open();
sqlcmd.ExecuteNonQuery();
conn.Close();
if(sqlcmd.Parameters["#userId"].SqlValue.ToString() != "Null")
{
gResult.UserId = sqlcmd.Parameters["#userId"].SqlValue.ToString();
}
}
Hope this pseudo code helps you.

Retrieve data from SQLite database Android using Xamarin

I'm simply trying to retrieve data from SQLite, but my code neither returns a value nor gives an error. Please help me out.
So far I've done
var test = new List<cdProdGroup>();
var db = new SQLiteConnection(path);
var test1 = db.Query<cdProdGroup>("SELECT * FROM cdProdGroup");
foreach (var item in test1) {
cdProdGroup cd = new cdProdGroup {
DIQ_PG_CD_EBS = item.DIQ_PG_CD_EBS,
DIQ_PG_DESC = item.DIQ_PG_DESC,
DVSN_CD = item.DVSN_CD
};
test.Add(cd);
}
I'm using Xamarin for coding
The SELECT * FROM cdProdGroup query is unnecessary as is the re-assignment into a new List<cdProdGroup>.
You can simplify the query like so:
var db = new SQLiteConnection(path);
var test = db.Table<cdProdGroup>().ToList();

Is it possible to create an ADOX catalog in memory and populate it?

I tried creating one like this:
using (MemoryStream stream = new MemoryStream())
{
Catalog catalog = new Catalog(stream); // do I need to add more after this?
foreach (DataTable dt in ds.Tables)
{
Table adoxTable = new Table();
adoxTable.Name = dt.TableName;
adoxTable.ParentCatalog = catalog; // issue is here
catalog.Tables.Append(table);
}
return stream.ToArray();
}
However when I get to the line adoxTable.ParentCatalog = catalog; I get the exception: The connection cannot be used to perform this operation. It is either closed or invalid in this context.
Do I need to add additional steps after creating the catalog in order to properly utilize it?

Adding value to dropdownlist

I have web Service method that returns value of one column of a table. I want add that value to my drop down list. Is there any easy way to do it.
Here is my web method that returns all conference_name in conference table.
[WebMethod(Description = "Retrieves all Conference")]
public DataSet GetAllConference()
{
DataSet dataSet = new DataSet();
// Create connection object
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT conference_name FROM Conference";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "Conference");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables.Count <= 0)
return null;
else
return dataSet;
}
On user side there will be one dropdown list. How can i add the value return by the web method to the dropdown list.
You need to add web reference of web service in order to call the method, You may read this post to know how add reference, After adding reference you can call the method adn fill the drop down by the code given below,
DataSet ds = wsObject.GetAllConference();
if(ds.Tables.Count > 0)
{
ddlist.DataTextField = "conference_name";
ddlist.DataValueField = "conference_name"; //Change field to one you want.
//ddlist.DataValueField = "IDColumnInTheDataTable"; //un comment after give right column name
ddlist.DataSource = ds.Tables[0];
ddlist.DataBind();
}

Executing stored procedure with asp.net

I am trying to execute a stored procedure in asp.net. The stored procedure requires 3 parameters, all 3 are ID's(ints). The 3 parameters are : TaskID, ExhibitID, and InvestigatorID.
I have a hidden field that contains an array of ExhibitID's that came from a javascript function.
My question is how do I get the query to execute as I am looping through the array?
Here is an example of my stored procedure:
var cnSaveTask = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
var comLinkExhibitToTask = new SqlCommand("p_CaseFileTasksExhibitLinkAdd", cnSaveTask) { CommandType = CommandType.StoredProcedure };
foreach (string exhibit in hidExhibitsIDs.Value.Split(','))
{
comLinkExhibitToTask.Parameters.AddWithValue("#TaskID", taskID);
comLinkExhibitToTask.Parameters.AddWithValue("#ExhibitID", Convert.ToInt32(exhibit));
comLinkExhibitToTask.Parameters.AddWithValue("#InvestigatorID", int.Parse(Session["InvestigatorID"].ToString()));
}
try
{
cnSaveTask.Open();
comLinkExhibitToTask.ExecuteNonQuery();
}
It is not working in my DB though. Nothing gets added. My guess is that since it is iterating and not executing, it just keeps replacing the "exhibitID" everytime then eventually tries to execute it. But I don't think just adding "comLinkExhibitToTask.ExecuteNonQuery()"
outside the try is a good idea. Any suggestions?
you can either move the try block into the foreach loop or wrap the foreach loop with a try block. (depending on what error handling you wish - continue with the next exhibit on error or completely abort execution)
I've never used AddWithValue, so I can't speak to its functionality. Here's how I typically write a DB call like this.
using (SqlConnection cnSaveTask = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ConnectionString))
{
cnSaveTask.Open();
using (SqlCommand comLinkExhibitToTask = new SqlCommand("p_CaseFileTasksExhibitLinkAdd", cnSaveTask))
{
comLinkExhibitToTask.CommandType = CommandType.StoredProcedure;
comLinkExhibitToTask.Parameters.Add(new SqlParameter("#TaskID", SqlDbType.Int) {Value = taskID});
// etc.
comLinkExhibitToTask.ExecuteNonQuery();
}
}
The solution:
var cnSaveTask = new SqlConnection(ConfigurationManager.ConnectionStrings["OSCIDConnectionString"].ToString());
try
{
var comLinkExhibitToTask = new SqlCommand("p_CaseFileTasksExhibitLinkAdd", cnSaveTask) { CommandType = CommandType.StoredProcedure };
cnSaveTask.Open();
comLinkExhibitToTask.Parameters.Add(new SqlParameter("#TaskID", SqlDbType.Int));
comLinkExhibitToTask.Parameters.Add(new SqlParameter("#ExhibitID", SqlDbType.Int));
comLinkExhibitToTask.Parameters.Add(new SqlParameter("#InvestigatorID", SqlDbType.Int));
foreach (string exhibit in hidExhibitsIDs.Value.Split(','))
{
comLinkExhibitToTask.Parameters["#TaskID"].Value = taskID;
comLinkExhibitToTask.Parameters["#ExhibitID"].Value = Convert.ToInt32(exhibit);
comLinkExhibitToTask.Parameters["#InvestigatorID"].Value = int.Parse(Session["InvestigatorID"].ToString());
comLinkExhibitToTask.ExecuteNonQuery();
}
}
catch (Exception ex)
{
ErrorLogger.Log(0, ex.Source, ex.Message);
}
finally
{
if (cnSaveTask.State == ConnectionState.Open)
{
cnSaveTask.Close();
}
}
Since I was in a loop it kept adding parameters. So just declare the parameters outside the loop, and only pass the values in the loop. That way there are only 3 parameters, and the values will be passed in accordingly

Resources