I need to connect with Remote Database from Xamarin application [duplicate] - c#

I'm having trouble with my code to access a MySQL Database. Everytime I try to open my connection, a System.TypeInitializationException is thrown by MySql.Data.MySqlClient.Replication.ReplicationManager. Here is my code:
DataTable results = new DataTable("Results");
using (MySqlConnection connection = new MySqlConnection("SERVER=127.0.0.1;DATABASE=foo;UID=bar;PASSWORD=foobar;"))
{
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
command.Connection.Open(); //throws System.TypeInitializationException
command.ExecuteNonQuery();
using (MySqlDataReader reader = command.ExecuteReader())
results.Load(reader);
}
}
Edit: I guess MySQL Driver was corrupt. After an upgrade from Windows 7 to Windows 10 everything worked fine.

I had the same problem but when i installed the MySql.Data.dll using Nuget then the problem is solved
Install MySql.Dll file from Nuget,
not from MySQL Website.

Your connection string format is wrong. Try this :
static string cs = #"server=localhost;user id=bar;password=foobar;database=foo;";
DataTable results = new DataTable("Results");
using (MySqlConnection connection = new MySqlConnection(cs))
{
using (MySqlCommand command = new MySqlCommand(queryString, connection))
{
command.Connection.Open(); //throws System.TypeInitializationException
command.ExecuteNonQuery();
using (MySqlDataReader reader = command.ExecuteReader())
results.Load(reader);
}
}

In my case, it raised error only in production. It was due to a wrong assumption in the MySql.Data package. It for some reason seems to demand to be in the same folder as the orchestrating dll (it was referencing another dll which was referencing MySql). I resolved my issue by removing MySql.Data and instead installing MySqlConnector package as suggested in here.

Related

Error while trying to use Microsoft.ACE.OLEDB.12.0

I am trying to read data from an Excel .xlsx spreadsheet and put it into a datagridview.
However when ever I run my code it gives me the following error:
System.InvalidOperationException: 'The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.'
After some googling it looks like its something to do with the version of excel i have installed (I have Office 2019 Pro installed on my machine) but I dont really know how to rectify it. I have tried changing the version number to various things on the "Microsoft.ACE.OLEDB.12.0" bit of my code but with no success. Im not 100% sure how this works, is it my version of Excel installed on my machine that matters or is it some kind of library I should have that I need to get within visual studio?
My code is as follows:
DataTable rs = new DataTable();
using (var odConnection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=c:\myfile.xlsx;Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';"))
{
odConnection.Open();
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = odConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
using (OleDbDataAdapter oleda = new OleDbDataAdapter(cmd))
{
oleda.Fill(rs);
dataGridView4.DataSource = rs;
dataGridView4.Font = new Font("MS Sans Serif", 8);
}
}
odConnection.Close();
}
The last time I battled with this issue my problem was 32 bit/64 bit, I think you should check that first. Also read the documentation here

.Net Core - SQL Server Geography data type exception

I am trying to use the new Microsoft.Data.SqlClient in my .Net Core application. Whenever I select a column that has a datatype of Geography, I get the following error.
Unable to cast object of type 'Microsoft.SqlServer.Types.SqlGeography' to type 'Microsoft.Data.SqlClient.Server.IBinarySerialize'.'
To reproduce, I created a database on my computer (SQL2019) with one table:
DROP TABLE IF EXISTS geotest
GO
CREATE TABLE geotest (g GEOGRAPHY)
GO
INSERT INTO geotest (g)
VALUES
( 0xe6100000010cec51b81e854b4040ec51b81e852b58c0 ),
( 0xe6100000010c6666666666a64740713d0ad7a3905ec0 )
I create a console application project (Visual Studio 2019, .Net Core 3.1) and add the NUGET package: Microsoft.Data.SqlClient
Here is my sample app:
using System;
using Microsoft.Data.SqlClient;
namespace TestWithOtherSQL
{
class Program
{
static void Main(string[] args)
{
SqlConnection conn = new SqlConnection("Data Source=localhost;Initial Catalog=joe;Trusted_Connection=True;");
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = #"SELECT g FROM geotest";
SqlDataReader sr = cmd.ExecuteReader();
while (sr.Read())
{
var a = sr[0];
}
conn.Close();
Console.WriteLine("Hello World!");
}
}
}
It throws the error on this line:
var a = sr[0];
Unable to cast object of type 'Microsoft.SqlServer.Types.SqlGeography' to type 'Microsoft.Data.SqlClient.Server.IBinarySerialize'.'
Troubleshooting:
If I change out the Nuget package to System.Data.SqlClient and include package Microsoft.SqlServer.Types (change the using to System.Data.SqlClient) The same code works.
So why don't I just do that? Good question... My actual database is on Azure SQL DB and I need to use Microsoft.Data.SqlClient to support ActiveDirectory Password Authentication (that does not work with System.Data.SqlClient) - but that's a different issue....
Also Microsoft.Data.SqlClient is the "new" ".NetCore" way of doing things. Not a huge issue for me right now, but not sure if that would work if we ported to Linux are tried to run in an Azure function.

Unable to connect to database using Oracle.ManagedDataAccess and Windows Native Authentication

I am having trouble connecting to an Oracle database using Oracle.ManagedDataAccess and Windows Native Authentication.
I am developing on a workstation from which I am able to connect to the same database using NTS via the PL/SQL Developer, and via C# code using non-managed Oracle.DataAccess. This leads me to I believe that there is nothing fundamentally wrong with either the database, workstation or the account. Now I am trying to evaluate if it's possible to switch to Oracle.ManagedDataAccess in our solution.
I've tried the following so far:
Created a new blank project OracleManagedAccessTest
Under references added the NuGet package Oracle.ManagedAccessTest v19.3.1 (the latest at the time of writing)
Update the <dataSource> tag in the App.config to match the entry in the tnsnames.ora (to make the C# project self-contained and not relying on external component)
Added <setting name="sqlnet.authentication_services" value="NTS"/> tag under <oracle.manageddataaccess.client><version number="*"><settings> in the App.config
I am using the following minimal code to test the connection:
try
{
using (OracleConnection conn = new OracleConnection("Data Source=EDBDEVD;User Id=/;"))
{
conn.Open();
}
}
catch (OracleException ex)
{
Console.WriteLine("Exception Message: " + ex.Message);
}
The attempt to connect fails with the following error: "ORA-01017: invalid username/password; logon denied"
This looks almost like too simple of a problem, yet I can't seem to resolve it, or find a workable solution online. Any help would be greatly appreciated.
Try this one:
string oradb = "Data Source=ORCL;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "select department_name from departments where department_id = 10"; cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
label1.Text = dr.GetString(0);
see also: https://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/GettingStartedNETVersion/GettingStartedNETVersion.htm

Writing queries for a PostgreSQL DB

To start, here's what I got so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql; // Npgsql .NET Data Provider for PostgreSQL
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
NpgsqlConnection conn = new NpgsqlConnection ("Server=127.0.0.1;Port=5432;UserId=postgres;Password=test;Database=dbab;") ;
conn.Open() ;
// Define a query
NpgsqlCommand cmd = new NpgsqlCommand("set schema 'data'; select test_run.id from test_run;", conn);
cmd.ExecuteNonQuery();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
}
// Close connection
conn.Close();
System.Console.WriteLine("Press any key to close...");
Console.ReadKey();
}
}
}
Whenever I run this, I get NpgsqlException was unhandled. Under that it says:
An unhandled exception of type 'Npgsql.NpgsqlException' occurred in Npgsql.dll
Additional information: External component has thrown an exception.
When I click view detail, this shows: {"42P01: relation \"test_run\" does not exist"}
When I saw this, I thought maybe my query somehow messed up, but it actually is fine because I ran it in pgAdmin with no problems finding 'test_run' table.
I installed Npgsql -Version 3.0.5 and Mono.Security 3.2.3.0 with Nuget. I also added to two .dll's (not sure how to check this) into the GAC.
In addition, I uninstalled Npgsql, installed it again, but instead got version 2.2.3, and still ran into the same problem. I'm now back with version 3.0.5.
I'm not sure how to fix this, please help.
EDIT:
As jackmott said, I needed to split up the queries. Here's what I did:
NpgsqlCommand cmd = new NpgsqlCommand("set schema 'data';", conn);
cmd.ExecuteNonQuery();
NpgsqlCommand cmd2 = new NpgsqlCommand("select test_run.id from test_run;", conn);
cmd2.ExecuteNonQuery();
And it works.
instead of set schema try:
set search_path to 'schema'
Which is what set schema should alias to, but perhaps that alias doesn't work in NpgSQL
The other thing I would try is to run the set search_path as it's own command, then run the query as the next command..
Third thing to check, is if the user has permissions to read that table in that schema.

MissingManifestResourceException through SmartDeviceProject?

I am new to SmartDeviceProject. So When i try to connect MySQL to my project, MissingManifestResourceException through in Connection.open in below code?.
string connectionString = "server=192.168.1.100;database=mcubic;User Name=mcubic;Password=mcs#2011$;";
string query = "select b.Outlet_Master_Name from mcs_user_outlet a,outlet_master b where a.Mcs_User_Outlet_User_Id=3 and a.Mcs_User_Outlet_Outlet_Id = b.Outlet_Master_Id";
MySqlConnection connection = new MySqlConnection(connectionString);
MySqlCommand command = new MySqlCommand(query, connection);
connection.Open();
MySqlDataReader Reader = command.ExecuteReader();
while (Reader.Read())
{
comboBox1.Items.Add(Reader[0].ToString());
}
connection.Close();
How do i solve this,. I am imported MySql.Data.CF.dll for this project.
Via Krish Kapadia from MSDN forums:
Solution :
MySql's version 5.2.7.0 is the stable version. I use dll of this version. Other versions have many problems. so first I download dll of that version from mysql site.
here is the link :
http://dev.mysql.com/downloads/connector/net/5.2.html
I have inserted one entry in 'mysql.user' table in which hostname will be '%' (means any user can connect to mysql). If you don't want to insert entry with hostname then you have to insert for all ip addresses who should be allowed to connect to mysql.
After inserting entry in 'mysql.user', I restarted MySQL service.
And then trying to connect to mysql and Connected....
source:
http://social.msdn.microsoft.com/Forums/eu/netfxcompact/thread/66f6386a-9963-4c2f-8d39-1c507a26a6c7

Categories

Resources