Error on add reference to SQLite.Interop.dll - c#

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.

Related

SQLCipher integration into Xamarin.Forms; SQLite Library doesn't support encryption exception

I am implementing SQLCipher into a Xamarin.Forms application. I thought everything was working until I noticed that the DB that was being created by the X.F. application was actually a SQLite3 DB w/o encryption or a password. After looking into it for a while, I haven't been able to find a solution. I am encountering an exception that says
System.InvalidOperationException: 'You specified a password in the connection string, but the native SQLite library you're using doesn't support encryption.'
I currently have 4 projects in this solution. The standard 3 in XamarinForms (Default PCL for cross platform stuff, Project.Android, and Project.iOS). In addition to those 3, I have a custom PCL that is labeled Project.Core. This PCL is responsible for all DataAccess since it implements the Repository Pattern, Unit Of Work, DbContext, etc.
In this 4th project, and within my DbContext.cs class, I have this:
// Added for more context
using System;
using System.IO;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Xamarin.Forms;
private SqliteConnection connection;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string connStr = Path.Combine(
path1: Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
path2: "App.db");
string passStr = deviceIdentifier;
string path = Path.GetDirectoryName(connStr);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// Check if db file exists
if (!File.Exists(connStr))
{
FileStream stream = File.Create(connStr);
stream.Close();
}
// DOCS => https://learn.microsoft.com/en-us/dotnet/standard/data/sqlite/encryption?tabs=netcore-cli
// => https://www.bricelam.net/2016/06/13/sqlite-encryption.html
var connectionString = new SqliteConnectionStringBuilder()
{
DataSource = connStr,
Mode = SqliteOpenMode.ReadWriteCreate,
Password = passStr
}.ToString();
// NOTE: THIS IS WHERE THE EXCEPTION IS THROWN!!!
// THE CODE BELOW THIS IS AN ALTERNATE ROUTE THAT DOENS'T WORK EITHER
**connection.Open();**
// This code doesn't throw anything, but it doesn't key the DB either
using (SqliteCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT quote($password);";
command.Parameters.AddWithValue("$password", passStr);
string escapedPassword = (string)command.ExecuteScalar(); // Protects against SQL injection
command.CommandText = "PRAGMA key = " + escapedPassword /*+ ";"*/;
command.Parameters.Clear();
command.ExecuteNonQuery();
}
#if DEBUG
optionsBuilder.EnableSensitiveDataLogging();
#endif
optionsBuilder.UseSqlite(connection);
SQLitePCL.Batteries_V2.Init();
}
Through my research it appears there might be an issue with one of the SQLite/SQLCipher packages in this PCL (the PCL is targeting .NET Standard 2.0 for reference).
I currently have:
Microsoft.Data.Sqlite.Core 3.1.1 (w/ dependencies on Microsoft.Data.Sqlite.dll & SQLitePCLRaw.core 2.0.2)
SQLitePCLRaw.bundle_sqlcipher 1.1.14 (w dependencies on SQLitePCLRaw.core 2.0.2, SQLitePCLRaw.batteries_sqlcipher.dll, SQLitePCLRaw.batteries_v2.dll)
A couple of other things to note:
When viewing SQLitePCL namespace, it shows the package as being sqlitepclraw.bundle_e_sqlite3 instead of having a reference to sqlcipher.
\.nuget\packages\sqlitepclraw.bundle_e_sqlite3\2.0.2\lib\netstandard2.0\SQLitePCLRaw.batteries_v2.dll
I believe there may be an issue with that dependency, but I'm not sure and would appreciate any assistance!
Thanks in advance.
PS - Can provide more information as requested
Found a working solution.
After looking into the packages, I found that replacing the existing SQLitePCLRaw bundle package with SQLitePCLRaw.bundle_zetetic found here, resolved the issues connecting and maintaining an encrypted database.
Working code snippet is:
// StringBuilder here, and the SqliteConnection below are
// from the Microsoft.Data.Sqlite namespace v3.1.1
var connectionString = new SqliteConnectionStringBuilder()
{
DataSource = connStr,
Mode = SqliteOpenMode.ReadWriteCreate,
Password = passStr
}.ToString();
connection = new SqliteConnection(connectionString);
connection.Open();

The type or namespace name 'OleDbConnection' could not be found (are you missing a using directive or an assembly reference?)

I am trying to parse from excel format to json.Below is the tried code I am getting problem with "OleDbConnection". I tried different solutions but nothing seems to work.
using System;
using System.Linq;
using System.Data;
using System.Data.OleDb;
using System.Data.Common;
using Newtonsoft.Json;
using System.IO;
namespace ResumeParsing
{
class Program
{
static void Main(string[] args)
{
var pathToExcel = #"C:\Users\Admin\Desktop\resumeexcelformat.xlsx";
var sheetName = "Sheet1";
var destinationPath = #"C:\path\to\save\json\file.json";
//Use this connection string if you have Office 2007+ drivers installed and
//your data is saved in a .xlsx file
var connectionString = $#"
Provider=Microsoft.ACE.OLEDB.12.0;
Data Source={pathToExcel};
Extended Properties=""Excel 12.0 Xml;HDR=YES""
";
//Creating and opening a data connection to the Excel sheet
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = $"SELECT * FROM [{sheetName}$]";
using (var rdr = cmd.ExecuteReader())
{
//LINQ query - when executed will create anonymous objects for each row
var query = rdr.Cast<DbDataRecord>().Select(row => new {
Prefix = row[1],
FirstName = row[2],
MiddleName = row[3],
Surname = row[4]
});
//Generates JSON from the LINQ query
var json = JsonConvert.SerializeObject(query);
//Write the file to the destination path
File.WriteAllText(destinationPath, json);
}
}
}
}
}
Through google I tried to add reference but in my project there is no assembly option and it is showing "no items found" in that to check whether system.data is checked or not.See the image also. Can any please tell how to resolve this error?
Important is adding System.Data.dll, because OleDb needs it.
But in your code sample you are already doing it.
Please try to remove the nuget package, clean project, close VS, reinstall package and do a rebuild.

.NET Framework compatibility issue with Oracle Data Access

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

Need an example of sqlite with Monodroid

Can anyone point me to an example of using sqlite with Monodroid? I've been unable to find even one.
I obviously need to add a SQLite demo to the ApiDemo sample.
Since I don't know when that'll happen, here's the quick and dirty version:
However, to use the following code you must be targeting Android 2.2 or later to use Mono.Data.Sqlite. If you need to target an earlier Android version, you should look into a fully managed replacement, such as managed-sqlite.
Furthermore, this example is using Mono.Data.Sqlite.dll, which is included in the MonoDroid SDK.
First, edit your project assembly references and add a reference for Mono.Data.Sqlite.dll and System.Data.dll.
Second, within your source code, add:
using System.Data;
using Mono.Data.Sqlite;
Finally, use ye normal ADO.NET code:
string dbPath = Path.Combine (
Environment.GetFolderPath (Environment.SpecialFolder.Personal),
"items.db3");
bool exists = File.Exists (dbPath);
if (!exists)
SqliteConnection.CreateFile (dbPath);
var connection = new SqliteConnection ("Data Source=" + dbPath);
connection.Open ();
if (!exists) {
// This is the first time the app has run and/or that we need the DB.
// Copy a "template" DB from your assets, or programmatically create one.
var commands = new[]{
"CREATE TABLE [Items] (Key ntext, Value ntext);",
"INSERT INTO [Items] ([Key], [Value]) VALUES ('sample', 'text')"
};
foreach (var command in commands) {
using (var c = connection.CreateCommand ()) {
c.CommandText = command;
c.ExecuteNonQuery ();
}
}
}
// use `connection`...
// here, we'll just append the contents to a TextView
using (var contents = connection.CreateCommand ()) {
contents.CommandText = "SELECT [Key], [Value] from [Items]";
var r = contents.ExecuteReader ();
while (r.Read ())
MyTextView.Text += string.Format ("\n\tKey={0}; Value={1}",
r ["Key"].ToString (), r ["Value"].ToString ());
}
connection.Close ();

Read Firefox bookmarks using C#

Using C#, I need to get all Firefox bookmarks for importing them into our database. How can I do this?
I'm aware of the SO question, Read FF 3 bookmarks in Java, but the answers there all seem to revolve around Java database drivers, and I'm not sure that some of those answers aren't Java-specific.
My primary question is, "How can I read Firefox bookmarks in C#?"
Secondary questions: I see \%user profile%\application data\mozilla\firefox\profiles\bookmarkbackups\bookmarks-[date].json files -- can I just parse that? If so, are there any existing parsers for that?
Rhetorical lamenting question: Why can't this be as easy as IE, where I just read the .url files in \%user profile%\favorites? Bah.
Use the SQLite driver for .Net and access the file places.sqlite it can be found at
Application Data/Mozilla/Firefox/Profiles/$this_varies/places.sqlite
on my computer. It should not be hard for you to locate on your target computers.
Edit 1:
Here is a snip of code that prints out urls from the database:
using System.Data.SQLite; // downloaded from http://sourceforge.net/projects/adodotnetsqlite
namespace sqlite_test
{
class Program
{
static void Main(string[] args)
{
var path_to_db = #"C:\places.sqlite"; // copied here to avoid long path
SQLiteConnection sqlite_connection = new SQLiteConnection("Data Source=" + path_to_db + ";Version=3;New=True;Compress=True;");
SQLiteCommand sqlite_command = sqlite_connection.CreateCommand();
sqlite_connection.Open();
sqlite_command.CommandText = "select * from moz_places";
SQLiteDataReader sqlite_datareader = sqlite_command.ExecuteReader();
while (sqlite_datareader.Read())
{
// Prints out the url field from the table:
System.Console.WriteLine(sqlite_datareader["url"]);
}
}
}
}
Edit 2:
As tip. I really must recommend the SQLite Manager plugin for firefox. It's very useful for working with sqlite databases.
Surely it works the same way as suggested in the Java question, just get the SQLite .NET provider and use that to access the FF database file.
There's a SQLite driver for .Net. Once you get that working I'd imagine the solution would be the same in both .Net and Java.
I had to rework this slightly for my project http://www.codertakeout.com. Hope this revision helps clarify a few things thanks to some suggestions from around the web.
using System.Data.SQLite; // need to install sqlite .net driver
String path_to_db = #"C:\Documents and Settings\Jeff\Application Data\Mozilla\Firefox\Profiles\yhwx4xco.default\places.sqlite";
String path_to_temp = System.IO.Path.GetTempFileName();
System.IO.File.Copy(path_to_db, path_to_temp, true);
SQLiteConnection sqlite_connection = new SQLiteConnection("Data Source=" + path_to_temp + ";Version=3;Compress=True;Read Only=True;");
SQLiteCommand sqlite_command = sqlite_connection.CreateCommand();
sqlite_connection.Open();
sqlite_command.CommandText = "SELECT moz_bookmarks.title,moz_places.url FROM moz_bookmarks LEFT JOIN moz_places WHERE moz_bookmarks.fk = moz_places.id AND moz_bookmarks.title != 'null' AND moz_places.url LIKE '%http%';";
SQLiteDataReader sqlite_datareader = sqlite_command.ExecuteReader();
while (sqlite_datareader.Read())
{
System.Console.WriteLine(sqlite_datareader[1]);
}
sqlite_connection.Close();
System.IO.File.Delete(path_to_temp);
Visit http://myexps.blogspot.com for the implementation in java.
import java.sql.*;
public class helloWorld {
public static void main(String[] args) throws Exception {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:/home/deepak/.mozilla/firefox/yvf7p20d.default/places.sqlite//");
if(conn==null)
{
System.out.println("ERROR");
}
System.out.println(conn.toString());
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select * from moz_bookmarks;");
while (rs.next()) {
System.out.println("id = " + rs.getString("id"));
System.out.println("keyword = " + rs.getString("keyword_id"));
System.out.println("title = " + rs.getString("title"));
}
rs.close();
conn.close();
}
}
This will be the java implementation

Categories

Resources