.NET Framework compatibility issue with Oracle Data Access - c#

I'm working on a C# project in Visual Studio 2012 on Windows 10 and Oracle 11g.
In order to connect my c# project I had to install Oracle Data Access Components_ODTwithODAC121024 and everything worked fine.
I updated the target .NET framework of my project to 3.5, and now I get this error:
Could not load file or assembly 'Oracle.DataAccess, Version=2.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. An attempt was made to load a program with an incorrect format.
After really long search and test I think that caused by incompatibility issue.
I tried to enable .NET Framework 3.5 through Programs and Features -> Turn Windows features on or off.
I tried to read reference and importing the Oracle.DataAccess.dll from
C:\app\Samer\product\11.2.0\dbhome_1\ODP.NET\bin\2.x
and I also used the Oracle.DataAccess.dll that comes with Oracle Data Access Components
My project works fine when I disable the method that deals with oracle commands.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
namespace backup_Check_v01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Read_const_File();
}
//Method for Reading Constants File
public void Read_const_File()
{
string File_Path;
File_Path = #"s:\test\result";
Get_File_info(File_Path);
}
//Method for reading file information ex(File Name,Size,and creation date..etc)
public void Get_File_info(string para1)
{
FileInfo info = new FileInfo(para1);
richTextBox1.AppendText(Environment.NewLine + "File Name: " + Path.GetFileNameWithoutExtension(info.Name));
richTextBox1.AppendText(Environment.NewLine + "File Size (Bytes): " + info.Length.ToString());
richTextBox1.AppendText(Environment.NewLine + "Creation Time: " + info.CreationTime.ToString());
richTextBox1.AppendText(Environment.NewLine + "Last Access: " + info.LastAccessTime.ToString());
richTextBox1.AppendText(Environment.NewLine + " **************************** ");
search_for_string(para1);
}
public void search_for_string(string para2)
{
string keywords = "sb_0501_Thu.dmp";
string oradb = "Data Source=sb_1901;User Id=sb_1901;Password=sb00;";
StreamReader sr = new StreamReader(para2);
richTextBox1.AppendText(Environment.NewLine + sr.ReadToEnd());
if (!richTextBox1.Text.Contains(keywords))
{
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into backup_check(REC_ID,OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null,'keywords',0,'SBank',sysdate)";
int rowsupdated = cmd.ExecuteNonQuery();
if (rowsupdated == 0)
{ MessageBox.Show("NONE"); }
else
{ MessageBox.Show("Done"); }
conn.Dispose();
}
else
{
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into backup_check(REC_ID,OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null,'keywords',1,'SBank',sysdate)";
int rowsupdated = cmd.ExecuteNonQuery();
if (rowsupdated == 0)
{ MessageBox.Show("NONE"); }
else
{ MessageBox.Show("Done"); }
conn.Dispose();
}
}
}
}

You refer to ODP.NET version 2.121.2.0. but it seems you have installed Oracle Client 11.2. The versions have to match with each other (at least the major version number)
Open your *.csproj file and set reference of Oracle.DataAccess like this:
<Reference Include="Oracle.DataAccess">
<SpecificVersion>False</SpecificVersion>
</Reference>
Attributes like Version=... or processorArchitecture=... are not required. Your application will load the correct Oracle.DataAccess.dll depending on selected architecture and target .NET framework

Related

Error on add reference to SQLite.Interop.dll

I'm needing read some cookies of a specific site and I found a code on internet that probably can help me. This code uses some methods specifics of SQLite and for make this is necessary add references to some SQLite dlls, but the trouble is, when I will go add SQlite.Interop.dll, this generates a error that says:
A reference to 'C:\Program Files\System.Data.SQLite\2012\bin\SQLite.Interop.dll' could not be added. Please make sure that the file is accessible, and that it is a valid assembly or COM component.
So, someone can help me to solve this trouble. I already saw in several sites on internet somethings relative to it but until now, I don't had sucess.
This is code that I found, and he have need of SQLite dll file reference, like I said above.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static public IEnumerable<Tuple<string, string>> ReadCookies(string hostName)
{
if (hostName == null) throw new ArgumentNullException(hostName);
var dbPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + #"\Google\Chrome\User Data\Default\Cookies";
if (!System.IO.File.Exists(dbPath)) throw new System.IO.FileNotFoundException("Cant find cookie store", dbPath);
var connectionString = "Data Source=" + dbPath + ";pooling=false";
using (var conn = new System.Data.SQLite.SQLiteConnection(connectionString))
using (var cmd = conn.CreateCommand())
{
var prm = cmd.CreateParameter();
prm.ParameterName = hostName;
prm.Value = hostName;
cmd.Parameters.Add(prm);
cmd.CommandText = "SELECT name,encrypted_value FROM cookies WHERE host_key = " + hostName;
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var encryptedData = (byte[])reader[1];
var decodedData = System.Security.Cryptography.ProtectedData.Unprotect(encryptedData, null, System.Security.Cryptography.DataProtectionScope.CurrentUser);
var plainText = Encoding.ASCII.GetString(decodedData);
yield return Tuple.Create(reader.GetString(0), plainText);
}
}
conn.Close();
}
}
static void Main(string[] args)
{
var list = ReadCookies("facebook.com");
foreach (var item in list)
Console.WriteLine("{0} | {1}", item.Item1, item.Item2);
Console.WriteLine();
Console.ReadLine();
}
}
}
Add the package using NuGet
Install-Package System.Data.SQLite
It will download and add the appropriate references for SQLite. It looks like you are trying to add the wrong references. You should be adding references to binaries like the Core / EF6 / Linq from the SQLLite binaries.
I had the same error and I was able to resolve it with the following steps:
Go to the location (i.e) "C:\Program Files\System.Data.SQLite\2015\bin" and you will see SQLite.Interop.dll and SQLite.Interop
Copy these two files and then go to the your application bin location (i.e) "........\SQliteExample\SQliteExample\bin\Debug" and paste them there.

Unrecognized database format

I would like to ask, why I get this exception when I try to connect excel 2000/3 and also 2010?
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
namespace md1_connect
{
class Program
{
static void Main (string[] args)
{
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"Book1.xls\"";
OleDbConnection MyConn = new OleDbConnection(ConnectionString);
OleDbCommand cmd = new OleDbCommand("SELECT * FROM[Sheet2$]", MyConn);
MyConn.Open();
OleDbDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
Console.WriteLine(dataReader.GetDouble(0));
}
MyConn.Close();
}
}
}
You need to tell the provider you're using Excel 97-2003 (xls as opposed to xlsx) by appending:
Extended Properties="Excel 8.0"
E.g.
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"Book1.xls\";Extended Properties=\"Excel 8.0\"";
I dont know what the exception is but I may know what you are talking about. You are probably compiling as x64 bit, please force it to run as 32 bit (x86). I believe that setting can be set in your Project Properties under Build Options

What is the namespace while creating a MS Access database using C#

I am exporting a gridview to MS Access but I am facing some problems.
What namespace I should be using while creating a MS access database in C#?
For playing with Microsoft office realated document like MS-Access or MS-Excel you need to add
using System.Data.OleDb
write some code
OleDbConnection conn = new OleDbConnection();
then right click on the class name (e.g. OleDbConnection) and select resolve or you can use shortcut ctrl + .
In this specific case you need to add
using System.Data.OleDb
You need to add reference to this namespace in your project System.Data.OleDb
and then use it on you file like this
using System.Data.OleDb
The System.Data.OleDb namespace needs to be added in your c# file. You can refer the below detailed sample which help you to learn more about MS Access data storage and retrieval through C#.
Link to Refer
I am using 2 namespace
using ADOX;
Using ADODB;
yes i am using namespace
using System.Data.OLEDB; with 2 namespace
using ADOX;
using ADODB; with this code
ADOX.Catalog cat = new ADOX.Catalog();
ADOX.Table table = new ADOX.Table();
//Create the table and it's fields.
table.Name = "Table1";
table.Columns.Append("PartNumber", ADOX.DataTypeEnum.adVarWChar, 6); // text[6]
table.Columns.Append("AnInteger", ADOX.DataTypeEnum.adInteger, 10); // Integer
try
{
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=d:/m2.accdb;" + "Jet OLEDB:Engine Type=5");
cat.Tables.Append(table);
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" + "Data Source=d:/m2.accdb");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Table1([PartNumber],[AnInteger]) VALUES (#FirstName,#LastName)";
cmd.Parameters.Add("#FirstName", OleDbType.VarChar).Value = "neha";
cmd.Parameters.Add("#LastName", OleDbType.VarChar).Value = 20;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
result = false;
}
cat = null;

C#: annoying mistake during making back up of sql database

I am trying to make my application which have aim to make backup of database on disk and also send it through ftp or mail.
So I made a research and finally I wrote project of Windows service and another project in console which is making a backup of database. Both are working well and both are written in the same Visual Studio but when I am trying to put code of making backups in Windows service it doesn't work. I can't understand why. I tried put code instead of example (which is creating a file and writing one line there and this part is working well) and I even tried to make another method to do it and then call this method.
Windows service is completely the same as here and in the SpadesAdminService class instead of
System.Diagnostics.EventLog.WriteEntry("SpadesAdminSvc",
ServiceName + "::Execute()");
I made this code (is working well - making an empty file on my disk every 5 seconds, should be written "text to file" but files are appearing !):
using (FileStream fs = File.OpenWrite("C:\\place\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".txt"))
{
Byte[] napis = new UTF8Encoding(true).GetBytes("text to files"));
fs.Write(napis, 0, napis.Length);
}
My class of making back up (alone is also working well):
namespace makeBackUpConsole
{
class Program
{
static void Main(string[] args)
{
string dbname = "exampleToniDatabase";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=GRAFIKA-2\SQLEXPRESS;Integrated Security=True;" + "Database=exampleToniDatabase";
string destdir = "C:\\place\\";
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("C:\\place\\");
}
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("Backup database successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error During backup database!");
}
}
}
}
I am copying this class instead of my code to making txt files and Windows Service is not working. Here is a code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace toni.exampleService.Services
{
public class exampleAdminService : exampleServiceBase
{
public exampleAdminService()
{
this.ServiceName = "exampleAdminSvc";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
}
protected override void OnStop()
{
base.OnStop();
}
protected override int Execute()
{
//using (FileStream fs = File.OpenWrite("C:\\development\\toni\\dd\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".txt"))
//{
// Byte[] napis = new UTF8Encoding(true).GetBytes("DzieƄ i godzina: " + DateTime.Now.ToString("ddMMyyyy_HHmmss"));
// fs.Write(napis, 0, napis.Length);
//}
string dbname = "exampleToniDatabase";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=GRAFIKA-2\SQLEXPRESS;Integrated Security=True;" + "Database=exampleToniDatabase";
string destdir = "C:\\place\\";
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("C:\\place\\");
}
try
{
sqlcon.Open();
sqlcmd = new SqlCommand("backup database " + dbname + " to disk='" + destdir + "\\" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".Bak'", sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
MessageBox.Show("Backup database successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error During backup database!");
}
return 0;
}
}
}
Of course all libraries as well linked.
Looking for any advice, please help me.
Thank you in advance and have a nice day.
edit:
Hey, problem solved.
I created a database account (not Windows account) in sql management studio and I putted this account User Id and Password directly into my code in C# in Windows Service.
Anyway maybe somebody will use my code :)
Thanks for reply.
Have you checked that a Windows Service has permissions to write a file in the location you are specifying. Services don't necessarily run as a user, so don't assume that where you can write a file your service can too.
Have you tried writing to a folder underneath c:\ProgramData?
If you don't know precisely what the problem is then you need to find out. Try adding System.Diagnostics.Debugger.Launch(); at service startup and then track the changes inside the debugger.
The Windows Service you have programmed is using "Integrated Security" for your SQL Server.
If you don't want to enter login credentials in your code, you should either set the executing user to your local account or grant the required user (e.g. LocalSystem) access to your database in your SQL Management Studio.
Usually a Windows Service is running as LocalSystem, LocalService or NetworkService. Just change the setting for your Windows Service in services.msc

ExcelDNA and Mysql

I'm new to C#, creating excel plugins and also new to ExcelDNA. I got the examples working on http://exceldna.codeplex.com/wikipage?title=Getting%20Started. The UDF "MultiplyThem" works as expected.
When I modify example #3 on that site to grab data from a mysql database. I reference not only ExcelDna.Integration.dll but also MySql.Data.dll in my project. I then compile it with this statement:
c:\windows\microsoft.net\framework\v2.0.50727\csc.exe /target:library /reference:ExcelDna.Integration.dll /reference:MySql.Data.dll TestLib.cs
When I open up the excel-add in and start typing in my UDF(in this case, "=MultiplyThem()") there is no UDF called "MultiplyThem". Why did it suddenly stop working? Here's my C# code:
using ExcelDna.Integration;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
public class MyFunctions
{
[ExcelFunction(Description = "Grabs data from database", Category = "Useful functions")]
public static string MultiplyThem(string[] args)
{
string connString = "Server=localhost;Port=3306;Database=test;Uid=root;password=pword";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT field_value FROM customers";
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
string myvariable = "bad";
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
myvariable = reader["field_value"].ToString();
}
return myvariable;
}
}
And my Test1.dna file (I am targeting .NET Framework 4 in my project):
<DnaLibrary RuntimeVersion="v4.0">
<ExternalLibrary Path="TestLib.dll"/>
</DnaLibrary>
Excel-DNA does not currently support string arrays as parameters. If you change the string[] args to object[] args it should be fine.

Categories

Resources