I always encounter this error
ORA-01460: unimplemented or unreasonable conversion request
when I am sending a byte[] of image from stream to my OracleDB.
I even change the parameter direction to InputOutput but I still encountered it.
Help here is my code.
public void AddUser(string userFName, string userLName, byte[] userImage)
{
GetConnection();
try
{
using (oraConn)
{
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmd = new OracleCommand();
cmd.Connection = oraConn;
cmd.CommandText = "SP_ADD_USERINFOS";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("PFIRSTNAME", OracleType.VarChar).Value = userFName;
cmd.Parameters.Add("PLASTNAME", OracleType.VarChar).Value = userLName;
cmd.Parameters.Add("PIMAGE", OracleType.Blob).Value = userImage;
cmd.Parameters["PIMAGE"].Direction = ParameterDirection.InputOutput;
da.SelectCommand = cmd;
DataSet dSet = new DataSet();
da.Fill(dSet);
}
oraConn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I already change the parameter direction. It supposed to send the byte[] to my OracleDB blob column and when it already sent there. I am supposed to view the image.
Already solved!
I just recreated my command. I no longer use a stored procedure from this insertion of image. thanks guys!
Related
In sql I normally execute my procedure using
exec dbo.usp_FCS 'TIMV','serial'
And I tried something somewhat the same in c# but it seems I got this wrong
using (SqlConnection connection = new SqlConnection("Data Source=;Initial Catalog=;User ID=;Password="))
{
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" + "'" + MachineName + " ','serial' " , connection))
{
try
{
connection.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
}
catch (SqlException ex)
{
label6.Visible = true;
label6.Text = string.Format("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
}
}
My question is,how can I give those 2 inputs 'TIMV' and 'serial' of my stored procedure using c#?
Edit:
I tried something like this:
using (SqlCommand cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya" , connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#p2", SqlDbType.VarChar).Value = "serial";
try
{ my code...
And it is still not working
The most correct way to add a parameter to an SqlCommand is through the Add method that allows you to specify the datatype of the parameter and, in case of strings and decimals, the size and the precision of these values. In that way the Database Engine Optimizer can store your query for reuse and be a lot faster the second time you call it. In your case I would write
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 20).Value = MachineName;
cmd.Parameters.Add("#serial", SqlDbType.NVarChar, 20).Value = "serial";
This assumes that your stored procedure receives two parameters named EXACTLY #mname and #serial, the type of the parameters is NVarChar and the length expected is 20 char. To give a more precise answer we need to see at least the first lines of the sp.
In your code above also the execution of the command is missing. Just creating the command does nothing until you execute it. Given the presence of an SqlDataAdapter I think you want to fill a DataSet or a DataTable and use this object as DataSource of your grid. Something like this
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
yourDataGrid.DataSource = dt;
And if this is an ASP.NET app, also the DataBind call
yourDataGrid.DataBind();
You use the Parameters collection of the SqlCommand class to send parameters to a stored procedure.
Suppose your parameter names are #p1 and #p2 (Please, for your sake, don't use names like this ever) - your c# code would look like this:
using (var cmd = new SqlCommand("usp_FCS_GetUnitInfo_Takaya", connection))
{
cmd..CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#p1", SqlDbType.VarChar).Value = MachineName;
cmd.Parameters.Add("#21", SqlDbType.VarChar).Value = "serial";
try
{
// rest of your code goes here....
Note: use the SqlDbType value that fits the parameters data type.
Try this:
DataSet ds = new DataSet("dts");
using (SqlConnection conn = new SqlConnection
("Data Source=;Initial Catalog=;User ID=;Password="))
{
try
{
SqlCommand sqlComm = new SqlCommand("usp_FCS_GetUnitInfo_Takaya",conn);
sqlComm.Parameters.AddWithValue("#p1", MachineName);
sqlComm.Parameters.AddWithValue("#p2", "serial");
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
catch (Exception e)
{
label6.Visible = true;
label6.Text = string.Format
("Failed to Access Database!\r\n\r\nError: {0}", ex.Message);
return;
}
I'm trying to execute a stored procedure and print the output, but when I run the below code I'm getting error like "Procedure or function 'SPInsertLocal' expects parameter '#RES', which was not supplied."
private void InsertPdtLocal(string code, string PON,string Qty)
{
string str = Properties.Settings.Default.conLocal;
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand("Execute SPInsertLocal #PON,#TCode,#Qty,#Type", con);
try
{
con.Open();
cmd.CommandTimeout = 150;
cmd.Parameters.AddWithValue("#PON", PON);
cmd.Parameters.AddWithValue("#Qty", Qty);
cmd.Parameters.AddWithValue("#TCode", code);
cmd.Parameters.AddWithValue("#Type", Globals.s_type);
SqlParameter output = new SqlParameter("#RES", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
con.Close();
int id = Convert.ToInt32(output.Value);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
What I'm doing wrong here?
SqlCommand cmd = new SqlCommand("Execute SPInsertLocal #PON,#TCode,#Qty,#Type,#RES", con);
I was not passing the parameter , fixed the issue
You can refactor the code as follows where the using statement is used for the auto management of connection closing and avoid hardcoding Execute statement in c# code which is a bad practice
private void InsertPdtLocal(string code, string PON,string Qty)
{
string str = Properties.Settings.Default.conLocal;
try
{
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.Parameters.AddWithValue("#PON", PON);
cmd.Parameters.AddWithValue("#Qty", Qty);
cmd.Parameters.AddWithValue("#TCode", code);
cmd.Parameters.AddWithValue("#Type", Globals.s_type);
var output = cmd.Parameters.Add("#RES" , SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
int id = Convert.ToInt32(output.Value);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a large stored procedure that returns 5 different tables.
I need to display these tables generated by the stored procedures as HTML.
As I am struggling to find what the problem is due to the seemingly meaningless error messages given by the method in the closed class; I am looking for a new solution to the problem, however all contributions are welcome
I have inherited a system that uses a very old method for doing this through IES.Core.ReportTool.
I have an XLST file and some c# to do this -
string connStr = ConfigurationManager.AppSettings["DBConnStr"];
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Proc_cisiv_ProgramDayData";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ProgramDayNodeID", SqlDbType.Int);
cmd.Parameters.Add("#UserID", SqlDbType.Int);
PageInfo pInfo = CMS.DocumentEngine.DocumentContext.CurrentPageInfo;
cmd.Parameters["#ProgramDayNodeID"].Value = pInfo.NodeID;
cmd.Parameters["#UserID"].Value = CMS.Membership.MembershipContext.AuthenticatedUser.UserID;
ReportTool rt = new ReportTool();
try
{
lit.Text = rt.GenerateHTML(Server.MapPath("~/CMSPages/XSLT/ProgrammeDay.xslt"), connStr, cmd, false);
}
catch (Exception ex)
{
lit.Text = ex.ToString();
}
but something is not quite right and it is throwing a Null Reference Exception which is as follows -
System.NullReferenceException: Object reference not set to an instance of an object. at IES.Core.ReportTool.BaseGenerateHTMLFromSQL(String xslPathAndFileName, String xsdPathAndFileName, String xmlMapPathAndFileName, XsltArgumentList xslArgs, String DBConnStr, SqlCommand sqlCommandObject, Boolean debug) at IES.Core.ReportTool.GenerateHTML(String xslPathAndFileName, String DBconnStr, SqlCommand sqlCommandObject, Boolean debug) at ProgramDayDetail.Page_Load(Object sender, EventArgs e) in c:\Projects\brsweb\CMSWebParts\MyWebPart\ProgramDayDetail.ascx.cs:line 37
Line 37 is
lit.Text = rt.GenerateHTML(Server.MapPath("~/CMSPages/XSLT/ProgrammeDay.xslt"), connStr, cmd, false);
The solution that I have found so far (Not quite finished but it is displaying the data that is returned from the stored procedure as it should)
string connStr = ConfigurationManager.AppSettings["DBConnStr"];
SqlConnection connection = new SqlConnection(connStr);
connection.Open();
SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "Proc_cisiv_ProgramDayData";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ProgramDayNodeID", SqlDbType.Int);
cmd.Parameters.Add("#UserID", SqlDbType.Int);
PageInfo pInfo = CMS.DocumentEngine.DocumentContext.CurrentPageInfo;
cmd.Parameters["#ProgramDayNodeID"].Value = pInfo.NodeID;
cmd.Parameters["#UserID"].Value = CMS.Membership.MembershipContext.AuthenticatedUser.UserID;
string mapPath = "";
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
lit.Text = ds.GetXml();
}
catch (Exception ex)
{
lit.Text = ex.ToString() + "</br></br>" + pInfo.NodeID + "</br></br>" + CMS.Membership.MembershipContext.AuthenticatedUser.UserID + "</br></br>" + mapPath;
}
connection.Close();
looking at your exception I think that the code you are showing us isn't sufficient to understand the problem.
The call to GenerateHTML method starts in the right way. Inside that call you call IES.Core.ReportTool.BaseGenerateHTMLFromSQL and there you are getting the System.NullReferenceException.
The exception is propagated until line 37 but isn't the right line number.
Check for inner exceptions
The following code produces an error.
dbo.getit works fine when I call it directly on the server. The error occurs at cmd.ExecuteReader() . What am I doing wrong?
string user;
string pw;
SqlDataReader dr = null;
SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=myDB; Integrated Security=True");
user = Username.Text.Trim();
pw = Password.Text.Trim();
conn.Open();
try {
SqlCommand cmd = new SqlCommand("dbo.getit", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#param1", user);
cmd.Parameters.AddWithValue("#param2", pw);
dr = cmd.ExecuteReader();
while ( dr.Read() )
{
Session["username"] = user;
// Session["admin"] =
// Session["completed"] =
Server.Transfer("all_is_well.aspx");
}
conn.Close();
conn.Dispose();
} catch (Exception ex) {
if (dr != null)
{
dr.Close();
conn.Close();
}
Server.Transfer("ERROR.aspx");
}
SOLUTION:
Replace the two corresponding lines above with these:
SqlCommand cmd = new SqlCommand("select * from dbo.getit(#param1, #param2);", conn);
cmd.CommandType = CommandType.text;
This just seems questionable,
Session["username"] = user;
Server.Transfer("all_is_well.aspx");
inside the while loop!
Can you at least finish iterating on the reader, using a temporary object to store the result of the query, and then initialize you session and do the Server.Transfer. .
Server.Transfer terminates execution of the current page and starts execution of a new page for the current request. Also, Transfer calls End, which throws a ThreadAbortException exception upon completion.
I think what you are trying to do (and I am answering based on what you are trying to do - not necessarily best pratice) is verify that the user is authorized/authenticated in some way based on a data store. You'd be better off not using ExecuteReader at all. Use ExecuteScalar. If the result of ExecuteScalar is not null, the user was found.
if (cmd.ExecuteScalar() != null)
{
Server.Transfer("all_is_well.aspx");
}
else
{
Server.Transfer("someErrorPage.aspx");
}
SOLUTION:
Replace the two corresponding lines above with these:
SqlCommand cmd = new SqlCommand("select * from dbo.getit(#param1, #param2);", conn);
cmd.CommandType = CommandType.text;
That worked.
I need delete data in oracle 10g database from ASP.NET 2.0 web site.
Method DeleteMonthPlan I use on execute delete command. Problem is that this command is executing long time "in browser" and finally delete command is not executed. Maybe it waits on commit? What is root of problem?
This SQL command DELETE C_PPC_PLAN WHERE MFG_MONTH='VALUE' is OK.
MFG_MONTH column type is VARCHAR2(16)
First I need call method DeleteMonthPlan and than I need call InsertDatePlan.
private static void DeleteMonthPlan(string monthIndex)
{
try
{
using (var conn = new OracleConnection(GenerateConnectionString()))
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = string.Format("DELETE C_PPC_PLAN WHERE MFG_MONTH='{0}'", monthIndex);
cmd.ExecuteNonQuery();
}
}
catch (Exception exception)
{
throw exception;
}
}
For example this method I use on insert and it is OK.
public void InsertDatePlan(DatePlan dp,
string monthIndex)
{
DeleteMonthPlan(monthIndex);
try
{
using (var conn = new OracleConnection(GenerateConnectionString()))
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.Parameters.Add(":Site", OracleType.VarChar).Value = dp.Site;
cmd.Parameters.Add(":Week", OracleType.VarChar).Value = dp.MfgWeek;
cmd.Parameters.Add(":Month", OracleType.VarChar).Value = dp.MfgMonth;
cmd.Parameters.Add(":Year", OracleType.VarChar).Value = dp.MfgYear;
cmd.Parameters.Add(":Input", OracleType.Number).Value = dp.Input;
cmd.Parameters.Add(":Output", OracleType.Number).Value = dp.Output;
cmd.Parameters.Add(":LMUser", OracleType.VarChar).Value = dp.LmUser;
cmd.Parameters.Add(":PartNo", OracleType.VarChar).Value = dp.PartNo;
cmd.Parameters.Add(":PartNoDesc", OracleType.VarChar).Value = dp.PartNoDesc;
cmd.CommandText = string.Format("INSERT INTO C_PPC_PLAN (CREATE_TIME, SITE, MFG_DAY,MFG_WEEK,MFG_MONTH,MFG_YEAR,INPUT,OUTPUT,LM_TIME,LM_USER,PART_NO,PART_NO_DESC)"
+ " VALUES (to_date('{0}', 'dd-mm-yyyy hh24:mi:ss'), :Site ,to_date('{1}', 'dd-mm-yyyy hh24:mi:ss'),:Week,"
+ ":Month,:Year,:Input,:Output,to_date('{2}', 'dd-mm-yyyy hh24:mi:ss'),:LMUser,:PartNo,:PartNoDesc)"
, dp.CreateTime, dp.MfgDate, dp.LmTime);
cmd.ExecuteNonQuery();
}
}
catch (Exception exception)
{
throw exception;
}
}
I tried use transaction. I call this method on the bottom but is never finish it means that part
trans.Rollback(); or conn.Close(); is never executed.
private static void DeleteMonthPlan(string monthIndex)
{
var conn = new OracleConnection(GenerateConnectionString());
conn.Open();
OracleCommand cmd= conn.CreateCommand();
OracleTransaction trans = conn.BeginTransaction(IsolationLevel.ReadCommitted);
cmd.Transaction = trans;
try
{
cmd.CommandText = "DELETE C_PPC_PLAN WHERE MFG_MONTH='6'";
cmd.ExecuteNonQuery();
trans.Commit();
}
catch (Exception e)
{
trans.Rollback();
}
finally
{
conn.Close();
}
}
try
DELETE FROM C_PPC_PLAN WHERE MFG_MONTH='6'
BTW your code uses "literals" in some places instead of bind variables (params) which makes it vulnerable to SQL injection which is a really serious security problem!