Unable to work with SQL Server CE 4.0 - c#

I try to work with a SQL Server CE 4.0 database with my simple console app but it is not working on one of my machine.
OS: Windows Server 2003 Enterprise x64 Edition with Service Pack 2
I have also installed Microsoft SQL Server Compact 4.0 and used its dll (System.Data.SqlServerCe.dll) but every time I got following error
Unable to load the native components of SQL Server C
ADO.NET provider of version 8080. Install the correc
act. Refer to KB article 974247 for more details.
Here is my code
try
{
Console.WriteLine("Started");
var sqlConnectionString = "Data Source=c:\\tde\\22\\22.tde;password='sanjayraj';mode=Read Write;max database size=4091;temp file max size=4091";
_connection = new SqlCeConnection(sqlConnectionString);
_connection.Open();
var sqlStatement = "SELECT * FROM InfoStores WHERE Location = 'Source'";
IDbCommand newCommand = new SqlCeCommand
{
CommandText = sqlStatement,
Connection = _connection,
CommandType = CommandType.Text
};
using (IDataReader reader = newCommand.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error Occured");
Console.WriteLine(ex.Message);
Console.ReadKey();
}
Console.WriteLine("Finished");
Console.ReadKey();

You a referenceing the wrong version of System.data.SqlServerCe.dll, use the one in the C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v4.0\Desktop folder

Related

C# code is unable to connect to Azure SQL database

I am trying to connect to a sample database I have created in Azure using C# (.NET Core 3.1)
I have enabled my IP address within Azure's Firewall rules.
I am able to use VS2019's SQL Server Object Explorer to connect and view the database within with no problems.
However, when I run a simple C# app on the same PC to execute a query to count the number of records in a table, it throws the following exception at the point where the connection is opened (conn.Open());
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - The requested address is not valid in its context.)
The C# code;
using System;
using System.Data.SqlClient;
namespace AzureSql2
{
class Program
{
static void Main(string[] args)
{
string connStr = " Server=tcp:beaconsqlsql.database.windows.net,1433;Initial Catalog=MRP2;Persist Security Info=False;User ID=beaconadmin;Password=********;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
Console.WriteLine("Building connection");
try
{
using (var conn = new SqlConnection(connStr))
{
Console.WriteLine("Creating command");
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT COUNT(*) FROM [dbo].[Table]";
Console.WriteLine("Opening connection");
conn.Open();
Console.WriteLine("Reading database");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Record count: {0}", reader.GetInt32(0));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
}
}
I've tried temporarily turning off the firewall on my PC, but that made no difference.
The fact that SQL Server Object Explorer can connect but the C# code cannot makes it sound like there's a problem with the C# code, but I can't see any differences between it and the samples I've looked at.
I created one Azure SQL database and allowed my client IP like below :-
I created one .Net Console application and ran your code, I replaced
using System.Data.SqlClient
with
using Microsoft.Data.SqlClient
You can use any of the above packages.
Copied connection string from Azure Portal > Azure SQL server > Connection string refer below :-
C# Code:-
using System;
using System.Linq.Expressions;
using Microsoft.Data.SqlClient;
namespace AzureSql2
{
class Program
{
static void Main(string[] args)
{
string connStr = "Server=tcp:sqlservername.database.windows.net,1433;Initial Catalog=sqldbname;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
Console.WriteLine("Building connection");
try
{
using (var conn = new SqlConnection(connStr))
{
Console.WriteLine("Creating command");
using (var command = conn.CreateCommand())
{
command.CommandText = "SELECT * FROM Products";
Console.WriteLine("Opening connection");
conn.Open();
Console.WriteLine("Reading database");
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("Record count: {0}", reader.GetInt32(0));
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
}
}
Output :-
I tried to run the code with the connection string format you mentioned in the comments :-
Data Source=azuresqlservername.database.windows.net;Initial Catalog=databasename;User ID=siliconuser;Password=password;Connect Timeout=30;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
And I was able to run the same code above and got the desired output:-
When I tried to change the Azure SQL server name in the connection string, I got the same error code as yours, refer below :-
Verify if your connection string has any syntax missing and validate it from Azure Portal.
I ended up taking a copy of the project home and running it on my home PC, and it worked correctly and reliably (after telling Azure to allow that IP address as well)
It turned out the answer was embarrassingly obvious - in addition to the standard Windows 10 firewall, my work PC is running another virus protection/firewall software, and that also needed to be told to allow the app thru.
Definitely one to remember for next time... Although I am kind of intrigued that on two occasions (once mentioned above, once afterwards) out of a few hundred attempts the app did manage to get thru and connect.
Thank you everyone for your answers and help.

connection to oracle db gives System.TypeInitializationException' in Oracle.DataAccess.dll?

I trying to connect to an database in a little console application it works. but now i am making a restfull api for school but i am stuck on a runtime error:
System.TypeInitializationException' in Oracle.DataAccess.dll
my code end exception in my output
I tried a lot. checked if the version are correct it is al set up good i think. i am using
[HttpPost("InsertKlok")]
public IActionResult InsertKlok(Klok klkregd)
{
string constr = "Data Source=MydataSource;User Id=MyuserId;Password=Mypassword;";
var query = "Insert INTO KLOK(KLOK_ID, REDEN,INUIT) VALUES(" + klkregd.Klok_Id + ",'" + klkregd.Reden + "','" + klkregd.InUit + "')";
try
{
OracleConnection conn = new OracleConnection(constr);
OracleCommand command = new OracleCommand(query, conn);
conn.Open();
command.ExecuteNonQuery();
Console.WriteLine("Record inserted");
}
catch (Exception e)
{
Console.WriteLine(e);
}
return Ok(klkregd);
}
[Route("klok/")]
[HttpPost("AddKlok")]
public JsonResult AddKlok(Klok klkregd)
{
Console.WriteLine("In registerStudent");
KlokRegistratieAntwoord klkregdreply = new KlokRegistratieAntwoord();
KlokRegistratie.getInstance().Add(klkregd);
klkregdreply.Klok_Id = klkregdreply.Klok_Id;
klkregdreply.Reden = klkregdreply.Reden;
klkregdreply.InUit = klkregdreply.InUit;
return Json(klkregdreply);
}
}
}
`
In my console application i have same code and file for oracle connection but its not working here pls can someone help me
Since you use .net core you can try Oracle.ManagedDataAccess.Core instead of
Oracle.DataAccess; quotation:
Oracle Data Provider for .NET (ODP.NET) Core is an ADO.NET driver that
provides fast data access from Microsoft .NET Core clients to Oracle
databases. ODP.NET Core consists of a single 100% managed code
dynamic-link library
(bold is mine). You can get the assembly via Nuget:
https://www.nuget.org/packages/Oracle.ManagedDataAccess.Core/
Please, have a look at the tutorial from Oracle as well:
https://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/ODPNET_Core_get_started/index.html

Provider for SQL Server is not Register On Local Machine

I used the following code to connect C# with database
string connStr = "Provider=.NET Framework Data Provider for SQL Server"+
" Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True";
try
{
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
using (OleDbCommand cmd = new OleDbCommand(selected_querry, conn))
{
cmd.CommandType = CommandType.Text;
using (OleDbDataAdapter dAdapter = new OleDbDataAdapter(selected_querry, conn))
{
DataSet ds = new DataSet();
try
{
dAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception)
{
MessageBox.Show("Error: Failed to Fill the required data Field from the DataBase.");
return;
}
}
}
}
else
MessageBox.Show("Connection Not Open");
}
}
catch (Exception e)
{
MessageBox.Show("Error: Failed to retrieve the required data from the DataBase."+e);
return;
}
When i run the code i always get the following error
Provider for SQL Server is not Register On Local Machine
With an OleDb connection, you need to specify an OLE DB provider rather than a .NET provider in the connection string and specify the OLE DB connection string keywords Server (instead of Data Source) and Trusted_Connection=yes (instead of Integrated Security=SSPI):
string connStr = "Provider=SQLNCLI11.1"+
";Server=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\\Database1.mdf;Trusted_Connection=Yes";
SQL Server OLE DB providers include:
SQLOLEDB: legacy MDAC/WDAC provider
SQLNCLI: SQL Server 2005 Native client
SQLNCLI10: SQL Server 2008 Native client
SQLNCLI11: SQL Server 2012 Native client
However, in .NET applciations, it is best to use a managed provider. For SQL Server, the .NET Framework Data Provider for SQL Server (a.k.a SqlClient) will perform better, especially with large result sets. Use SqlConnection, SqlCommand, etc. and omit the provider from the connection string since it is implicit. Your connection string should work if you remove the Provider specification.

Cannot connect to oracle server from c#

I have oracle 10g Express Edition installed and I'm trying to connect to it from C#.
I've created a ODBC Data Source called MyOracle from ODBC Data Source Administrator.
I'm using Windows XP and Visual Studio 2008 Express Edition.
Here's my code:
string connString = "dsn=MyOracle;User=user;Password=pass";
OdbcConnection connection = null;
OdbcCommand command = null;
OdbcDataReader reader = null;
try
{
connection = new OdbcConnection(connString);
connection.Open();
connection.Close();
connection.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(string.Format("StackTrace:\n\n{0}\n",ex.StackTrace));
Console.WriteLine(string.Format("Message:\n\n{0}\n", ex.Message));
}
The console output tells me that the problem is at connection.Open();
Here's the output:
Any ideas?
Try to change your connection string to the following:
string connString = "DSN=MyOracle;UID=user;PWD=pass;Integrated Security=no;";

Get the SQL version on the machine running my app

I'm writing in c# (.Net 3.5) and I would like to get the version of the SQL installed in the local machine. It means I don't have a connection string which includes address\username\password, I just need the version of the SQL on the local machine without retrieving data from the databases etc.
I tried to use "Microsoft.SqlServer.Management.Smo.Wmi", but it seems it depends on the SQL version.
Any ideas?
Thanks, KM
EDIT:
Some notes,
I don't want to try/catch each DLL
"Microsoft.SqlServer.Management.Smo.Wmi" (There is different DLL to
different SQL version)
The only detail I need is the SQL version of the machine I'm
running on.
I don't have connection string / user name / password
Try this in powershell:
Get-WmiObject -Namespace "root\Microsoft\SqlServer\ComputerManagement10" -Class SqlServiceAdvancedProperty -ComputerName <SERVERNAME> | Format-Table ServiceName, PropertyName, PropertyNumValue, PropertyStrValue -AutoSize
Use root\Microsoft\SqlServer\ComputerManagement10 namespace for sql server 2008 and above and root\Microsoft\SqlServer\ComputerManagement for 2005 instead.
You can achieve this result from .net using System.Management namespace.
UPDATE
You can use this to detect which kind of SQL Server WMI providers are installed.
public static IEnumerable<string> EnumCorrectWmiNameSpace()
{
const string WMI_NAMESPACE_TO_USE = #"root\Microsoft\sqlserver";
try
{
ManagementClass nsClass =
new ManagementClass(
new ManagementScope(WMI_NAMESPACE_TO_USE),
new ManagementPath("__namespace"),
null);
return nsClass
.GetInstances()
.Cast<ManagementObject>()
.Where(m => m["Name"].ToString().StartsWith("ComputerManagement"))
.Select(ns => WMI_NAMESPACE_TO_USE + "\\" + ns["Name"].ToString());
}
catch (ManagementException e)
{
Console.WriteLine("Exception = " + e.Message);
}
return null;
}
if you want to get SQL Server Insance that installed on your machine you can use this code :
using Microsoft.SqlServer.Management.Smo.Wmi;
....
ManagedComputer mc = new ManagedComputer();
foreach (ServerInstance si in mc.ServerInstances)
{
Console.WriteLine("The installed instance name is " + si.Name);
}
or if you want to get SQL Server Version you can use this code :
try
{
SqlConnection sqlConnection = new SqlConnection(connectionString);
Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(sqlConnection));
switch (server.Information.Version.Major)
{
case 8:
MessageBox.Show("SQL Server 2000");
break;
case 9:
MessageBox.Show("SQL Server 2005");
break;
case 10:
MessageBox.Show("SQL Server 2008");
break;
default:
MessageBox.Show(string.Format("SQL Server {0}", server.Information.Version.Major.ToString()));
break;
}
}
catch (Microsoft.SqlServer.Management.Common.ConnectionFailureException)
{
MessageBox.Show("Unable to connect to server",
"Invalid Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

Categories

Resources