ObjectContext.Translate not working in oracle 19 version - oracle

this is my function that translate result from db to object classe.
public static List<T> GetListBySP<T>(string pSPName, params object[] pParamArray)
{
List<T> res = null;
//string connStr = ConfigurationManager.ConnectionStrings[sConnStr].ConnectionString;
string connStr = DbFactory.ConnStr;
using (OracleConnection conn = new OracleConnection(connStr))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandText = pSPName;
cmd.CommandType = CommandType.StoredProcedure;
FillParameters(cmd.Parameters, pParamArray);
cmd.Parameters.Add("pCursor", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
using (var db = DbFactory.CreateRo())
{
try
{
cmd.Connection.Open();
var reader = cmd.ExecuteReader();
res = ((IObjectContextAdapter)db).ObjectContext.Translate<T>(reader).ToList<T>();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Connection.Close();
}
}
}
}
return res;
}
after update oracle version to 19.
exaption throw on line
res = ((IObjectContextAdapter)db).ObjectContext.Translate<T>(reader).ToList<T>();
the exeption is:
An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
the project run on .net framework 4.6.2

Related

Giving this error XLWorkbook': type used in a using statement must be implicitly convertible to 'System.IDisposable'

This code giving a error XLWorkbook': type used in a using statement must be implicitly convertible to 'System.IDisposable' how to resolve it.
using (XLWorkbook wb = new XLWorkbook()) this line giving the error.
I have also added assembly reference ClosedXML but its not working
Is there any way to resolved this issue?
using System.Web;
using System.Data.SqlClient;
using System.IO;
using ClosedXML.Excel;
using System.Web.Mvc;
using SHIPVICTUAL.Controllers;
namespace SHIPVICTUAL.Controllers
{
public class shipController : Controller
{
// GET: ship
public ActionResult Index()
{
return View();
}
public ActionResult ExportToExcel(FormCollection formCollection)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
try
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings.Get("DBShipVictual"));
cmd = new SqlCommand("Reports_rdlc", con);
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
dt.TableName = "Report";
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-disposition", "attachment;ReportList.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
{
}
}
}
catch
{
}
return View();
}
}
} ```

Crystal Report ExportToStream Failing with Object Reference not set to an instance

I have a very simple app that takes in No parameters in the attempt to return PDF.
The crystal Reports were authored using CR IX and I had to update the web service code to use Crystal Report for Visual studio 13. I am able to set parameters, as well as being able to login and verify that login credentials are correct.
public string TestReport()
{
try
{
var p = new List<KeyValuePair<string, string>> {
new KeyValuePair<string, string>("Product", "03R95-01"),
new KeyValuePair<string, string>("Product_Rev", "E-V001")
};
var reportParameters = new ParameterField[2];
var rpt = InitializeReport("testReport", p);
var s = rpt.ExportToStream(ExportFormatType.PortableDocFormat);
return "Stream exists";
}
catch (Exception ex)
{
return $"{ex.Message}|{ex.StackTrace}";
}
}
The Initialize Report method is:
private ReportDocument InitializeReport(string svrId, string reportName, List<KeyValuePair<string, string>> parameters)
{
var uid = "userId";
var pwd = "pwd";
var svr = "serverId";
var db = "DBNAME";
var reportFolder = "c:\\CrystalTest\\ReportFolder";
var reportFile = Path.Combine(reportFolder, $"{reportName}.rpt");
var rpt = new ReportDocument
{
FileName = reportFile
};
rpt.Load(reportFile);
var conInfo = new ConnectionInfo
{
UserID = uid,
Password = pwd,
ServerName = svr,
DatabaseName = db
};
foreach (Table t in rpt.Database.Tables)
{
try
{
var loginInfo = t.LogOnInfo;
loginInfo.ConnectionInfo = conInfo;
t.ApplyLogOnInfo(loginInfo);
if(!t.TestConnectivity())
{
throw new Exception($"{t.Name} failed login");
}
}
catch (Exception ex)
{
throw;
}
}
rpt.VerifyDatabase();
return rpt;
}
I have verified that an error is thrown when userid/pass combinations are incorrect.
I get the following error when I run this.
Object reference not set to an instance of an object.| at
CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportToStream(ExportRequestContext
reqContext) at
CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportOptions
options) at
CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportFormatType
formatType) at ICEWS4.maintenance.TestReport() in
C:\CrystalTest.cs:line 724
I learned of the fix.
I had CR for VS 13 SP 29.
The Runtime installed on the server was 13 SP 23
I was told by SAP to update to SP 30.
After updating my code, and installing the runtime, I was able to export to PDF as desired.

Getting error while consuming Web API in Xamarin forms cross platform

Getting below error while consuming web API in Xamarin forms "Cannot convert from Login to System.Net.Http.HttpCompletionOption"
I'm new to mobile development ,please help me in completing the above code for consuming the API's in Xamarin cross platform.
Below is the code for WEB API
public class DBLoginController : ApiController
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db_test"].ConnectionString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = null;
[HttpGet]
[ActionName("getCustomerInfo")]
public DataTable Get()
{
DataTable dt = new DataTable();
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tbl_admin";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
adp = new SqlDataAdapter(cmd);
dt.TableName = "tbl_admin";
adp.Fill(dt);
con.Close();
}
catch
{
}
return dt;
}
[HttpPost]
public int Login([System.Web.Http.FromBody] Login lgn)
{
int ret = 0;
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select count(*) from tbl_admin where username='"+lgn.username+"'username and password='"+ lgn.password + "'";
cmd.Connection = con;
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
ret = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
catch
{
}
return ret;
}
}
Below is the code for consuming API in xamarin form
private async void BtnLogin_Clicked(object sender, EventArgs e)
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://********.com/api/DBLogin/getCustomer");
Login lgn = new Login { username = txtUsername.Text.ToString(), password = txtPassword.Text.ToString() };
var response = client.GetAsync("api/Login/Login").Result;
var a = response.Content.ReadAsStringAsync();
if (a.Result.ToString().Trim() == "0")
{
messageLabel.Text = "Invalid login credentials.";
}
else
{
await Navigation.PushModalAsync(new Page2());
}
}
}
}
please help
Thanks in advance

Call is not passing from controller to model in web api

I am totally new in web api. I have created web api simply to retrive data from oracle DB with the help of few articles which i found on internet. I am trying to find out error since morning but no success till now. When i try to run the code, it dont give any error or anything. Debugger passed to my DB class and stops. Below is my controller code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data;
using System.Data.SqlClient;
namespace iLearnWebApi.Controllers
{
public class ValuesController : ApiController
{
DAL.DBAccess dblayer = new DAL.DBAccess();
public DataSet Getrecord(int programid)
{
DataSet ds = dblayer.GetRecordbyid(programid);
return ds;
}
} }
And below is my DBClass code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
using System.Configuration;
using System.Data.Odbc;
using Oracle.ManagedDataAccess.Client;
namespace iLearnWebApi.DAL
{
public class DBAccess
{
OracleParameter[] _objOraParam;
OracleConnection con = new OracleConnection();
//--- Get Records By Program ID
public DataSet GetRecordbyid(int progid)
{
DataSet ds = new DataSet();
try
{
_objOraParam = new OracleParameter[2];
_objOraParam[0] = new OracleParameter("p_Program_ID", OracleDbType.Int32);
_objOraParam[0].Direction = ParameterDirection.Input;
_objOraParam[0].Value = progid;
_objOraParam[1] = new OracleParameter("RCT_OUT", OracleDbType.RefCursor);
_objOraParam[1].Direction = ParameterDirection.Output;
ds = ExecuteDataset(con, CommandType.StoredProcedure, "ILS_USP_PROGRAM_DATA", _objOraParam);
}
catch (Exception ex)
{
LogError("GetRecordbyid", ex.Message.ToString());
throw ex;
}
finally
{
con.Close();
}
return ds;
}
// Execute Data
private DataSet ExecuteDataset(OracleConnection con, CommandType procname, string commandText, params OracleParameter[] objOraParam)
{
//create a command and prepare it for execution
OracleCommand cmd = new OracleCommand();
PrepareCommand(cmd, con, (OracleTransaction)null, procname, commandText, objOraParam);
//create the DataAdapter & DataSet
OracleDataAdapter da = new OracleDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);
cmd.Dispose();
//return the dataset
return ds;
}
//---- Used To Prepare Oracle command
private void PrepareCommand(OracleCommand command, OracleConnection connection, OracleTransaction transaction, CommandType commandType, string commandText, OracleParameter[] commandParameters)
{
//if the provided connection is not open, we will open it
string con_string = ConfigurationManager.ConnectionStrings["OracleConnectionString"].ConnectionString;
if (connection.State != ConnectionState.Open)
{
connection.ConnectionString = DecryptString(con_string, "CFSENC");
connection.Open();
}
//associate the connection with the command
command.Connection = connection;
//set the command text (stored procedure name or Oracle statement)
command.CommandText = commandText;
//if we were provided a transaction, assign it.
if (transaction != null)
{
command.Transaction = transaction;
}
//set the command type
command.CommandType = commandType;
//attach the command parameters if they are provided
if (commandParameters != null)
{
AttachParameters(command, commandParameters);
}
return;
}
// Used For Attaching Parameter To Command
private void AttachParameters(OracleCommand command, OracleParameter[] commandParameters)
{
foreach (OracleParameter p in commandParameters)
{
//check for derived output value with no value assigned
if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null))
{
p.Value = DBNull.Value;
}
command.Parameters.Add(p);
}
}
// Used For Decryption Of Encrypted String
private string DecryptString(string con_string, string key)
{
byte[] plainBytes = null;
try
{
string passWord = key;
string strInput = con_string;
byte[] encryptBytes = Convert.FromBase64String(strInput);
MemoryStream ms = new MemoryStream(strInput.Length);
//Using triple des for decryption
TripleDESCryptoServiceProvider tDesCsp = new TripleDESCryptoServiceProvider();
// Creating decryption IV and Key using the key supplied by the user
tDesCsp.IV = new byte[8];
PasswordDeriveBytes pdb = new PasswordDeriveBytes(passWord, new byte[0]);
tDesCsp.Key = pdb.CryptDeriveKey("RC2", "MD5", 128, new byte[8]);
CryptoStream deEnStream = new CryptoStream(ms, tDesCsp.CreateDecryptor(), CryptoStreamMode.Write);
//write the decrypted data to the stream
deEnStream.Write(encryptBytes, 0, encryptBytes.Length);
deEnStream.FlushFinalBlock();
plainBytes = new byte[ms.Length];
ms.Position = 0;
//reading the decrypted stream and write it into the byte array
ms.Read(plainBytes, 0, (int)ms.Length);
deEnStream.Close();
}
catch (Exception err)
{
string sErr = err.ToString();
throw new Exception("Error decrypting string.");
}
return Encoding.UTF8.GetString(plainBytes);
}
// For Writing Log Files
private void LogError(string header, string error)
{
string strPath;
string strActualError;
StreamWriter objErrWriter;
DateTime objDt = DateTime.Now;
string strDate;
strDate = objDt.ToString("ddMMyyyy");
try
{
// Get Actual Path of "Error" stored in Web.config
strPath = ConfigurationManager.AppSettings["sPathErrorLog"];
//Generates Path & LogFile Name of ErrorLog
strPath = strPath + strDate + ".log";
// Generates Error Message
strActualError = DateTime.Now + " : " + header + " : " + error;
// Creation of File.
objErrWriter = new StreamWriter(strPath, true, System.Text.Encoding.ASCII);
objErrWriter.WriteLine("");
objErrWriter.WriteLine(strActualError);
objErrWriter.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}}
Can anyone please tell me what mistake i have done in above code.
This sounds like a routing issue (without seeing your route config).
Try changing: public DataSet Getrecord(int programid)
To: public DataSet Get(int id)
And call: localhost:60908/api/Values/1

SqlException was unhandled(incorrect syntax error)

When I try to enter login, the program is sending me throw section & writing something about incorrect synxtax error '='.
public bool personelEntryControl(string password, int UserId)
{
bool result = false;
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Select * from Personeller ID=#Id and PAROLA=#password", con);
cmd.Parameters.Add("#Id", SqlDbType.VarChar).Value = UserId;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = password;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
result = Convert.ToBoolean(cmd.ExecuteScalar());
}
catch (SqlException ex)
{
string hata = ex.Message;
throw;
}
return result;
}
public void personelGetbyInformation(ComboBox cb)
{
cb.Items.Clear();
bool result = false;
SqlConnection con = new SqlConnection(gnl.conString);
SqlCommand cmd = new SqlCommand("Select * from Personeller ", con);
if (con.State == ConnectionState.Closed) ;
{
con.Open();
}
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
cPersoneller p = new cPersoneller();
p._PersonelId = Convert.ToInt32(dr["ID"]);
p._PersonelGorevId = Convert.ToInt32(dr["GOREVID"]);
p._PersonelAd = Convert.ToString(dr["AD"]);
p._PersonelSoyad = Convert.ToString(dr["SOYAD"]);
p._PersonelParola = Convert.ToString(dr["PAROLA"]);
p._PersonelKullanıcıAdı = Convert.ToString(dr["KULLANICIADI"]);
p._PersonelDurum = Convert.ToBoolean(dr["DURUM"]);
cb.Items.Add(p);
}
dr.Close();
con.Close();
}
You appear to be trying to filter with your cmd SQLCommand. However, you left out the keyword WHERE, hence the incorrect syntax error. It should be something like:
SqlCommand cmd = new SqlCommand("Select * from Personeller WHERE ID=#Id and PAROLA=#password", con)

Resources