I am trying to connect to Oracle in a 32-bit Console Application. I am getting the following erorr. The code (with the exception of host, username, and password change) is below. It is a simple two function project.
Any help will be appreciated.
I am using C# in Visual Studion 2010 Premium and Oracle 10g. I can connect to the database with Oracle SQL Developer with the information set in the connection string.
---------------ToString--------------------------
--Oracle.DataAccess.Client.OracleException at Oracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32 errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx* pOpoSqlValCtx, Object src, String procedure)
at Oracle.DataAccess.Client.OracleException.HandleError(Int32 errCode, Oracle
Connection conn, IntPtr opsErrCtx, Object src)
at Oracle.DataAccess.Client.OracleConnection.Open()
at ConsoleApplication1.Program.GetConnection() in c:\users\maholt\documents\visual studio 2010\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 61
---------------Message---------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Oracle.DataAccess.Client;
namespace ConsoleApplication1
{
class Program
{
static OracleConnection conn;
static void Main(string[] args)
{
OracleConnection connC = GetConnection();
conn = connC;
simpleQuery();
Console.WriteLine("DONE");
}
public static void simpleQuery()
{
OracleCommand cmd = new OracleCommand("select count(*) as total from console.client");
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
try
{
cmd.Connection.Open();
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(Convert.ToString(reader["total"]));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
cmd.Dispose();
}
}
public static OracleConnection GetConnection()
{
Oracle.DataAccess.Client.OracleConnection rtn = null;
try
{
string connstr = "Data Source=//10.10.10.10:1521/PRD2_OLTP;User Id=user; Password=pass;";
rtn = new Oracle.DataAccess.Client.OracleConnection(connstr);
if (rtn.State != System.Data.ConnectionState.Open)
{
rtn.Open();
}
}
catch (Exception ee)
{
Console.WriteLine("-------------------------------------------------");
Console.WriteLine("---------------ToString--------------------------");
Console.WriteLine("--" + ee.ToString());
Console.WriteLine("---------------Message---------------------------");
Console.WriteLine("--" + ee.Message);
Console.WriteLine("-------------------------------------------------");
}
return (rtn);
}
}
}
SQL Developer uses effectively JDBC connection... so it is not really comparable with what happens in .NET :-(
Regarding the Oracle versus .NET version compatibility - I found this rather problematic esp. since the clients don't have always the option to update according to Oracle roadmap...
After researching some I switched to using the Devart components - support everything from Oracle 7.3 up to 11gR2 in .NET 2 up with 32 and 64 bit and come with a "direct-mode option" which means if need be I can run my app without any Oracle client being installed on the machine... not affiliated, just a happy customer...
First - Oracle doesn't support 10g with .net 4.0. You must use 11.2.0.2 or higher to be compliant with Oracle's supported versions.
Second - The problem is you probably don't have ODP.Net installed correctly. This can mean it isn't installed, it was installed to a second instance, or it failed to copy on or more files during installation.
I have some blog posts about these items along with a link to some connection testing applications I wrote. Feel free to use them.
https://tsells.wordpress.com/category/oracle/
Related
I am unable to create Entity Models from database.
It is first time using MySQL from VS2017.
I am following tutorial at
1) https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-intro.html
2) https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-entity-framework-winform-data-source.html
3) https://dev.mysql.com/doc/connector-net/en/connector-net-entityframework60.html
I installed MySQL on local machine. I installed NuGet packages MySql.Data, MySql.Data.Entity, and MySql.Web (all version 6.9.11).
In tutorial No.2, while adding “ADO.Net Entity Data Model”, I get upto this window
I click next and then window silently close without producing any Data Models.
This means I don’t see the window below.
I assume my connection strting and web.config file is OK as I can successfully execute code bellow and get result “Samoa -- Malietoa Tanumafili II”
`
using System;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
public class Tutorial2
{
public static void Main()
{
string connStr = "server=localhost;user=root;database=world;port=3306;password=******";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
string sql = "SELECT Name, HeadOfState FROM Country WHERE Continent='Oceania'";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr[0]+" -- "+rdr[1]);
}
rdr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
conn.Close();
Console.WriteLine("Done.");
}
}`
Please guide what I am doing wrong.
This is a known bug in MySQL Connector/NET: bug 89338. According to that bug report, there's a bug in the wizard code that should be fixed in the next version, 6.10.7.
I'm trying to connect to SQL server using C#.
Its working good in Windows.
the problem is when I run it in Ubuntu 16 using Mono It doesn't work and collation error happen. Here is the error:
here is my whole C# code :
private SqlConnection CreareConnection()
{
try
{
SqlConnection conn = new SqlConnection("data source=192.168.1.25;initial catalog=MesterCoin;persist security info=True;user id=sa;password=147;");
conn.Open();
return conn;
}
catch (Exception ex){throw ex;}
}
public List<Balance> GetUnAssigned()
{
var result = new List<Balance>();
try
{
var cmd = new SqlCommand("select * from Balance", CreareConnection());
var rows = cmd.ExecuteReader();
while (rows.Read())
result.Add(new Balance() { Id = int.Parse(rows["Id"].ToString()) , Address = rows["Address"].ToString() });
}
catch (Exception ex) { throw ex; }
return result;
}
I have installed mono using this link :
http://www.mono-project.com/download/#download-lin
And SQL server version is 2014.
The program works with Latin collations but not with Arabic And Persian.
Mono is a fantastic system but the developers can only implement so much at once, looking at their SQLClient they have come a long way but some of the features aren't quite feature parity with windows yet.
If this is a new project, and isn't super complex maybe have a look at .NET Core - it runs on Ubuntu now instead of having to run through mono.
Apart from that you may be stuck in a horrible situation of either keeping with windows, abandoning your current collation or looking at another database engine :\
I need to connect to a Oracle DB (external) through Visual Studio 2010. But I dont want to install Oracle on my machine.
In my project I referenced: System.Data.OracleClient. But its not fulfilling the need.
I have an "Oracle SQL Developer IDE" in which I run SQL queries against oracle db.
I have this code so far:
private static string GetConnectionString()
{
String connString = "host= serverName;database=myDatabase;uid=userName;pwd=passWord";
return connString;
}
private static void ConnectingToOracle()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM myTableName";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["MYFIELD"];
Console.WriteLine(myField);
}
}
}
So far I read these blogs:
http://st-curriculum.oracle.com/tutorial/DBXETutorial/index.htm
http://blogs.msdn.com/b/kaevans/archive/2009/07/18/connecting-to-oracle-from-visual-studio.aspx
So far I have not downloaded anything from Oracle. What steps should I take to make this happen?
First off you need to download and install ODP from this site
http://www.oracle.com/technetwork/topics/dotnet/index-085163.html
After installation add a reference of the assembly Oracle.DataAccess.dll.
Your are good to go after this.
using System;
using Oracle.DataAccess.Client;
class OraTest
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
OraTest ot= new OraTest();
ot.Connect();
ot.Close();
}
}
You can use Oracle.ManagedDataAccess NuGet package too (.NET >= 4.0, database >= 10g Release 2).
Using Nuget
Right click Project, select Manage NuGet packages...
Select the Browse tab, search for Oracle and install Oracle.ManagedDataAccess
In code use the following command (Ctrl+. to automatically add the using directive).
Note the different DataSource string which in comparison to Java is
different.
// create connection
OracleConnection con = new OracleConnection();
// create connection string using builder
OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder();
ocsb.Password = "autumn117";
ocsb.UserID = "john";
ocsb.DataSource = "database.url:port/databasename";
// connect
con.ConnectionString = ocsb.ConnectionString;
con.Open();
Console.WriteLine("Connection established (" + con.ServerVersion + ")");
The next approach work to me with Visual Studio 2013 Update 4
1- From Solution Explorer right click on References then select add references
2- Assemblies > Framework > System.Data.OracleClient > OK
and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE
OracleConnection oraConnection = new OracleConnection(#"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}
and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method
public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;
if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:
Install Oracle Client , and add bin location to Path environment varaible of windows
OR
Copy
oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version),
oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll
I want to make a simple query on an Oracle database from .net using similar code to this.
using System;
using System.Data;
using Oracle.DataAccess.Client;
class Sample
{
static void Main()
{
// Connect to Oracle
string constr = "User Id=scott;Password=tiger;Data Source=AKI1.WORLD";
OracleConnection con = new OracleConnection(constr);
con.Open();
// Display Version Number
Console.WriteLine("Connected to Oracle " + con.ServerVersion);
// Read REF CURSOR into DataSet
DataSet ds = new DataSet();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = "GetComplexTabPkg.GetEmp";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_dep", OracleDbType.Int16).Value = 20;
cmd.Parameters.Add("p_ref", OracleDbType.RefCursor).Direction
= ParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.TableMappings.Add("Emp", "Emp");
da.Fill(ds);
// Close and Dispose OracleConnection
con.Close();
con.Dispose();
// Show Message
Console.WriteLine("DataSet filled");
}
}
My only concern is does the Oracle Client need to be installed on the web server that is running this code? It's my first time using this and I would like to avoid any obvious issues that can be prevented. Thanks.
Yes, Oracle Client need to be installed in web server. The work around will be to ship your application with Instant Oracle Client
On my Own I just install 64-bit Oracle Data Access Components (ODAC) Downloads, which seems to be lighter than Oracle Client.
I have SQL server express 2008 SP1 on windows 7 (Version 6.1 Build 7601: Service Pack 1) and visual studio 2010.
I am attempting to create a Stored Procedure CLR for inserting a file into a file stream using the following code.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Security.Principal;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void sp_fileController(String friendlyName, String filePath)
{
SqlParameter fDataParam = new System.Data.SqlClient.SqlParameter("#fData", SqlDbType.VarBinary, -1);
SqlParameter fNameParam = new System.Data.SqlClient.SqlParameter("#fName", SqlDbType.NVarChar, 300);
WindowsIdentity newId = SqlContext.WindowsIdentity;
WindowsImpersonationContext impersonatedUser = newId.Impersonate();
try
{
string cs = #"Server=[myservername];Integrated Security=true";
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlTransaction objSqlTran = con.BeginTransaction();
//string sql = "INSERT INTO fileStreamTest VALUES ((Cast('' As varbinary(Max))), #fName, default); Select fData.PathName() As Path From fileStreamTest Where fId = SCOPE_IDENTITY()";//OUTPUT inserted.fid
SqlCommand insertFileCommand = con.CreateCommand();
insertFileCommand.Transaction = objSqlTran;
insertFileCommand.CommandText = "INSERT INTO fileStreamTest.dbo.fileStreamTest (RowGuid, fData) VALUES (#FileID, CAST ('' as varbinary(max)))";
Guid newFileID = Guid.NewGuid();
insertFileCommand.Parameters.Add("#FileID", SqlDbType.UniqueIdentifier).Value = newFileID;
insertFileCommand.ExecuteNonQuery();
SqlCommand getPathAndTokenCommand = con.CreateCommand();
getPathAndTokenCommand.Transaction = objSqlTran;
getPathAndTokenCommand.CommandText =
"SELECT fData.PathName(), GET_FILESTREAM_TRANSACTION_CONTEXT() " +
"FROM fileStreamTest.dbo.fileStreamTest " +
"WHERE rowGuid = #FileID";
getPathAndTokenCommand.Parameters.Add("#FileID", SqlDbType.UniqueIdentifier).Value = newFileID;
SqlDataReader tokenReader = getPathAndTokenCommand.ExecuteReader(CommandBehavior.SingleRow);
tokenReader.Read();
SqlString filePathName = tokenReader.GetSqlString(0);
SqlBinary fileToken = tokenReader.GetSqlBinary(1);
tokenReader.Close();
SqlFileStream sqlFile = new SqlFileStream(filePathName.Value, fileToken.Value, System.IO.FileAccess.ReadWrite);
sqlFile.Close();
objSqlTran.Rollback();
//objSqlTran.Commit();
con.Close();
}
}
finally
{
impersonatedUser.Undo();
}
}
};
However when it gets to the line:
SqlFileStream sqlFile = new SqlFileStream(filePathName.Value, fileToken.Value, System.IO.FileAccess.ReadWrite);
I get:
A .NET Framework error occurred during execution of user-defined routine or aggregate "sp_fileController":
System.ComponentModel.Win32Exception: The request is not supported
System.ComponentModel.Win32Exception:
at System.Data.SqlTypes.SqlFileStream.OpenSqlFileStream(String path, Byte[] transactionContext, FileAccess access, FileOptions options, Int64 allocationSize)
at System.Data.SqlTypes.SqlFileStream..ctor(String path, Byte[] transactionContext, FileAccess access, FileOptions options, Int64 allocationSize)
at System.Data.SqlTypes.SqlFileStream..ctor(String path, Byte[] transactionContext, FileAccess access)
at StoredProcedures.sp_fileController(String friendlyName, String filePath)
Can anyone tell me how to fix this issue? Is simply that I cannot execute the code in this manner with sql 2008 express edition?
I think I have found working solution here:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/f49def09-3b47-4e54-8a53-2dd47762821e/filestream-on-windows-server-2012-the-request-is-not-supported?forum=sqldatabaseengine
To sum up: Adding registry key solved the problem on SQL Server 11.0.7001:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters\FsctlAllowlist]
"FSCTL_SQL_FILESTREAM_FETCH_OLD_CONTENT"=dword:0x00092560
As odd as it sounds Microsoft intentionally blocked the use of the SqlFileStream class usages inside SQL CLR assemblies (even if you grant EXTERNAL_ACCESS or declare the assembly as UNSAFE) as you can read in Microsoft Connect issue 768308.
However you can access the FILESTREAM as a stream by the means of the SqlBytes type (a really nice tip found on a blog post).. at least for read-only use, I've never tried writing.
I copy-past the code in case the blog disappears (in a slightly improved version with proper disposal of objects):
using System;
using System.IO;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Security.Cryptography;
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, SystemDataAccess = SystemDataAccessKind.None)]
public static SqlBinary Hash(SqlBytes source, SqlString hashAlgorithmName)
{
if (Source.IsNull)
{
return null;
}
using (HashAlgorithm ha = GetHashAlgotithm(hashAlgorithmName.Value))
using (Stream stream = Source.Stream)
{
return new SqlBinary(ha.ComputeHash(source.Stream));
}
}
}
I can confirm this definitely works for read-only access. I've never tried for write access (I'm writing FILESTREAM data from an external C# Windows Service or Web Application).