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 :\
Related
We have a requirement to do unit testing using either MS Test or NUnit Framework for our C# code. There are many methods which includes DB call. When trying to do so, I am getting below error:
*{"Could not load file or assembly 'Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=*******' or one of its dependencies. An attempt was made to load a program with an incorrect format."}*
I checked the Oracle version to make sure there is no mismatch, but no success. Also read couple of articles that instead of making DB call one should be using mocking to bypass DB. But with this limitation the coverage is very minimal.
Could anyone please guide to fix the above error. Adding the sample code which i tried just for POC
public class Class1
{
public IEnumerable<ModelClass> GetListOfExceptions()
{
OracleConnection conn = new OracleConnection(Constants.ConnectionString);
try
{
conn.Open();
OracleCommand cmd = new OracleCommand(Constants.<Oracle Query>, conn);
cmd.CommandType = CommandType.Text;
//cmd.CommandType = CommandType.StoredProcedure;
OracleDataReader dr = cmd.ExecuteReader();
ModelClass modelException = null;
List<ModelClass> lst = new List<ModelClass>();
while (dr.Read())
{
modelException = new ModelClass();
modelException.POLICYNO = Convert.ToString(dr.GetValue(1));
modelException.PREMIUM = Convert.ToInt32(dr.GetValue(2));
modelException.AGE = Convert.ToInt32(dr.GetValue(3));
lst.Add(princeException);
}
return lst;
}
catch (Exception)
{
throw;
}
finally
{
conn.Close();
}
}
}
[TestFixture]
public class Class1Tests
{
[Test]
public void GetListOfExceptionsTest()
{
Class1 obj = new Class1();
obj.GetListOfExceptions();
}
}
Most likely the ODP.NET (i.e. Oracle.DataAccess) is not installed on your machine. Or maybe it is installed but you did not install any Oracle Client (e.g. Oracle Instant Client)
Go to this page Oracle Data Access Components - .NET Downloads and download and install the Oracle Data Provider for .NET. Ensure that you download the same version as your Oracle Client in case you installed already one. Ensure also that you have the same architecture, i.e. 32-bit vs. 64-bit as your application.
Finally the issue is fixed after installation to Oracle Client 12.1 (32 bit version).
I am trying to make a simple app that will connect to a database and get some info. I have implented the plugin that allows xamarin app to connect remote mariaDB/MySQL to components. I am using the code below.
public void GetAccountCountFromMySQL()
{
try
{
string sql = " SELECT * FROM Kategorier";
MySqlConnection con = new MySqlConnection("Persist Security Info=False; Server=192.210.241.161; Port=3306; Database=xxxxx; Uid=xxxxx; Pwd=xxxxx;");
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString("Sko"));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I have tried many types of connection strings, also I buileded a simple C# application that connects to the very same database with no problems.
Actual problem was error from MySql "cannot resolve host name" After discussion the decision was not to use this plugin as it is not secured but create a webservice talking to MySql DB and consume it from Android app.
I am very new in C# and now try to find online resource to connect VS C# to mySQL database at server 'localhost', with userid 'root', and password '****', the databasename is 'dlht'.
1.I copied a line of code from youtube and it works:
this.stockTableAdapter.Fill(this.blhsDataSet.stock);
Can anyone explain to me what exactly this is doing? There is no place to put server, password, userid etc... How can it work?
I tried to use the online tutorials to connect to mySQL database
ZetCode C#Tutorial
string cs = #"server=localhost;userid=root;
password=****;database=dlht";
MySqlConnection conn = null;
try
{
conn = new MySqlConnection(cs);
conn.Open();
Console.WriteLine("MySQL version : {0}", conn.ServerVersion);
} catch (MySqlException ex)
{
Console.WriteLine("Error: {0}", ex.ToString());
} finally
{
if (conn != null)
{
conn.Close();
}
}
I run this code at Form1.cs at VS C#. It is always stuck at :
conn = new MySqlConnection(cs);
Why? Thank you so much!
It seems that the proper way to connect to MySql database is this
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
We have a report that has been giving us some serious issues, so I decided to put it into a console application in order to troubleshoot the issues.
The report is just a simple single select from SQL, returning approximately 25 columns,
and our date range can be 3-6 months, returning around 10k rows, so we are not talking about a lot of data.
Here is whats happening, when the report runs, it is timing out from our website, in the console, it takes anywhere from 13-18 mins to finish, the wait seems to happen at the da.Fill(ds);
Now here is the strange thing, it runs approximately 1-3 seconds within SQL Server Management Studio, and when our Delphi developers create a similar application, it is also a few seconds to run, this only happens using .NET
We tried changing from a dataset to loading into a datareader,
using this code..
using (var dr = _command.ExecuteReader())
{
if (dr.HasRows)
{
int i = 0;
while (dr.Read())
{
var startRead = DateTime.Now;
Console.Write("{2}\t{0}\t{1}\t", dr.GetInt32(0), dr.GetString(1), i);
var tookRead = DateTime.Now.Subtract(startRead);
Console.WriteLine("Took: " + tookRead);
i++;
}
}
However it did not help at all, it just displays in chucks but has frequent delays. I'm thinking its SQL, but can't explain why it works fine in Delphi and in SQL Management Studio.
I've tried using .NET 2.0, 3.5 and 4, happens on all frameworks.
Here is my code
public static DataSet GetData()
{
var now = DateTime.Now;
var _command = new SqlCommand();
var _connection = new SqlConnection();
try
{
_connection.ConnectionString = connectionString;
_command.Connection = _connection;
_command.CommandText = storedProcedure;
_command.CommandType = CommandType.StoredProcedure;
_command.CommandTimeout = 60;
if (string.IsNullOrEmpty(_connection.ConnectionString)) { throw new Exception("Connection String was not supplied"); }
_command.Parameters.Add(new SqlParameter("DateFrom", dateFrom));
_command.Parameters.Add(new SqlParameter("DateTo", dateTo));
SqlDataAdapter da;
var ds = new DataSet();
_connection.Open();
var done = DateTime.Now;
da = new SqlDataAdapter(_command);
da.Fill(ds);
if (ds == null) { throw new Exception("DataSet is null."); }
if (ds.Tables.Count == 0) { throw new Exception("Table count is 0"); }
var took = done.Subtract(now);
return ds;
}
catch (Exception ex)
{
File.WriteAllText(Path.Combine(Application.StartupPath, String.Format("Exception{0:MMddyyyy_HHmmss}.log", DateTime.Now)), ex.ToString());
}
finally
{
if (_connection.State != ConnectionState.Closed) { _connection.Close(); }
}
return null;
}
Any ideas? Our DBA is blaming the framework, I'm actually blaming something in SQL.. (maybe statistics, or corrupted db)
Differences in SQL performance between .NET and other clients (SQL Management Studio) are usually down to the connections being configured differently - frequent culprits are ANSI_NULLS; ANSI_PADDING.
Try looking at how the connection is configured in SQL Management Studio, then replicate the same thing in your .NET application.
The information you give doesn't contain enough details to really help...
IF SSMS is really that much faster then the reason could be some session/connection setting - SSMS uses subtly different settings in comparison to .NET.
For some explanation and hints on what could be different/wrong etc. see http://www.sommarskog.se/query-plan-mysteries.html
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/