Read Firefox bookmarks using C# - 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

Related

c# odbc update query doesnt work properly

Hi I'm having a lot of truble doing a program in c#
i have to connect to SQLANYWHERE 11 and do an update to a table
could u tell me where I'm wrong?
program go well until i reach the:
int number = wCommand.ExecuteNonQuery(); line
the program doesnt crash but tables get not updated
string dns = "Dsn=dattest;Uid=******;Pwd=******;";
OdbcDataReader reader;
OdbcCommand wCommand;
ODBCClass dst1 = new ODBCClass(dns);
queryins = "UPDATE dba.Sala_export_dati_macchina_produzione SET stato='p'";
// +"WHERE id_prd_lav_ord_lav='"+ id_prd_lav_ord_lav + "'";
wCommand = dst1.GetCommand(queryins);
int number = wCommand.ExecuteNonQuery();
Console.WriteLine("executed "+ number);
this is the odbc class that i'm using
public class ODBCClass
{
OdbcConnection oConnection;
OdbcCommand oCommand;
public ODBCClass(string DataSourceName)
{
oConnection = new OdbcConnection(DataSourceName);
try
{
oConnection.Open();
System.Diagnostics.Trace.WriteLine("Connessione stabilita con il database " + DataSourceName);
}
catch (OdbcException caught)
{
System.Diagnostics.Trace.WriteLine(caught.Message);
}
}
public void CloseConnection()
{
oConnection.Close();
}
public OdbcCommand GetCommand(string Query)
{
oCommand = new OdbcCommand
{
Connection = oConnection,
CommandText = Query
};
return oCommand;
}
public void Dispose()
{
oConnection.Close();
}
}
EDIT
just in case i've tried to change connection string with this pattern:
#"Driver={SQL Anywhere 11};DatabaseName=my_db_name;EngineName=my_server_name;uid=username;pwd=password;LINKs=tcpip(host=host_ip_address)"
and always the system gave me no error on connection in both cases
Ok guys that was kinda strange.
Let me explain the whole thing. I was doing that program for a customer that asked a software which could link my mysql db and a sybase db of another company.
The problem was that the DBMS of that company when is opened on the server block all kind of external editing to the db with which is connected.
So select query worked regularly but update and insert were blocked by that client...
I've passed 4 day with a perfect working program but that company didn't told me this "little" thing.
So be aware of DBMS they are cruel.

What would be a valid OleDbConnection ConnectionString for an uploaded file?

I am certain I have missed something obvious.
A simple task is before me: 'Upload an Excel (2003) file via ASP.NET on a Forms page and push the contents of that file to a DataTable in preparation for data- validation / storage'.
Those operations work fine already when applied to a locally stored edition of the file -- for that I simply utilize the OleDbConnection-ConnectionString "String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;", fileName)" from an OleDbDataAdapter.
However, trying to repeat that with an uploaded edition of the very same file (via a FileUpload control), on the line where I fill the OleDbDataAdapter I receive the error ["The Microsoft Jet database engine could not find the object "Sheet1$". Make sure the object exists and that you spell its name and the path name correctly."] An error so generic and painful -- still I'm unsure where to look next. I am guessing the connection-string structure is illegitimate for an uploaded file.
I searched through StackOverflow and MSDN and even around the web with no success thus far, but the search terms may be overly ubiquitous. Am I required to actually find a local repository for saving the uploaded file to prior to attempting a parse of it's content? Can I not simply construct a connection to a 'file in memory'? In case it concerns the answer, the uploaded files are not anticipated to ever exceed 200 kb in size.
Sincere thanks in advance for any assistance provided...
What I do in this situation is build a Parser class that will temporarily save the file, process it, then delete that temporary file when disposed. Something like:
public class ExcelParser : IDisposable
{
string filename;
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}; Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
public ExcelParser(HttpPostedFile file)
{
filename = String.Format("{0}{1}.xlsx", System.IO.Path.GetTempPath(), Guid.NewGuid().ToString());
file.SaveAs(filename);
}
public MyData Process()
{
OleDbConnection conn = new OleDbConnection(String.Format(connStr, filename));
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * From [Sheet1$]", conn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// Build Data to return
}
reader.Close();
conn.Close();
return data; // Return data you built
}
public void Dispose()
{
File.Delete(filename);
}
}
You could then use it as such:
using (ExcelParser parser = new ExcelParser(file))
{
var results = parser.Process();
// Do stuff
}

Sqlite connecting to remote file using url C#

ive been trying to get my sqlite to read a remote file but is just flatout tells me this isnt supported is there a workaround for this ?
here is the function that gives the error
public void Run(string sql,string check,string file)
{
SQLiteConnection m_dbConnection;
string test = "Data Source=" + file + ";Version=3;";
m_dbConnection = new SQLiteConnection(test);
m_dbConnection.Open();
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
SQLiteDataReader reader = command.ExecuteReader();
if (check == "0")
{
while (reader.Read())
comboBox1.Items.Add(reader["name"] + "." + reader["TLD"]);
comboBox1.SelectedIndex = 0;
}
else
{
proxy = reader["proxyip"].ToString();
check = "0";
}
}
error i get is "URI formats are not supported"
the file variable is filled by one of 2 values.
string filelocal = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\unblocker\\sites.db";
or
string remotefile = "http://127.0.0.1/test.db";
the one that gives the error is the remote file.
The Connection string uses as a datasource the db file which is expected on your local file system, take a look at this example code.
You can transorfm this using:
Uri uriFormatted = new Uri(file);
uriFormatted.AbsolutePath; // Try to use this value instead to call your function
EDIT
SQLite is a local standalone database, that is used for standalone software
Consider using SQLitening:
SQLitening is a client/server implementation of the popular SQLite database.

Error tells me I haven't close the connection, but haven't I?

I must have missed something here. I am trying to create a table but I am getting an error telling me that connection is still open. But where??? I have re-read the code but I can't find where the connection is still open...
Problem lays here: objOleDbConnection.Open()
Error say:
You attempted to open a database that is already opened by user 'Admin' on machine 'machine'. Try again when the database is available.
private void sfdNewFile_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
// Creating a ADOX object needed to create
// new MS Access file.
ADOX.Catalog createMSFile = new ADOX.Catalog();
// Creating an object for a table.
Table nTable = new Table();
// Creating an object allowing me connecting to the database.
OleDbConnection objOleDbConnection = new OleDbConnection();
objOleDbConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + sfdNewFile.FileName + ";Persist Security Info=False;Mode=12";
// Creating command object.
OleDbCommand objOleDbCommand = new OleDbCommand();
objOleDbCommand.Connection = objOleDbConnection;
try
{
// Created a new MS Access 2007 file with specified path.
createMSFile.Create("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
sfdNewFile.FileName);
objOleDbConnection.Open();
objOleDbCommand.CommandText = "CREATE TABLE PersonalData (" +
"[DataID] AUTOINCREMENT NOT NULL PRIMARY KEY ," +
"[Type] VARCHAR(40) NOT NULL ," +
"[URL] VARCHAR(40) NOT NULL ," +
"[SoftwareName] VARCHAR(40) NOT NULL ," +
"[SerialCode] VARCHAR(40) NOT NULL ," +
"[UserName] VARCHAR(40) NOT NULL ," +
"[Password] VARCHAR(40) NOT NULL";
objOleDbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
// Displaying any errors that
// might have occured.
MessageBox.Show("Error: " + ex.Message);
}
finally
{
// It is importnat to release COM object, in this very order
// otherwise we eill end up with an error.
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(createMSFile);
// Closing the connection to the database.
objOleDbConnection.Close();
}
}
It seems that the ADOX object should close its connection as well.
Look at the following sample from Microsoft:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms681562(v=vs.85).aspx
Their ADOX object is named cat.
They have the following:
cat.ActiveConnection = Nothing
Which will probably translate to:
createMSFile.ActiveConnection = null
In your code (probably in the first Finally block).
I think it's the ADOX object that makes the difference, before dispoing it, try to set it's ActiveConnection to null.
I must admit that I thought that ADO was really for C++ and VB not .NET technologies.
To quote from here
Caution ADO and ADO MD have not been fully tested in a Microsoft .NET Framework environment. They may cause intermittent issues, especially in service-based applications or in multithreaded applications. The techniques that are discussed in this article should only be used as a temporary measure during migration to ADO.NET. You should only use these techniques after you have conducted complete testing to make sure that there are no compatibility issues. Any issues that are caused by using ADO or ADO MD in this manner are unsupported. For more information, see the following article in the Microsoft Knowledge Base:
840667 You receive unexpected errors when using ADO and ADO MD in a .NET Framework application
On the same page you'll see the following code:
using System;
using ADOX;
namespace ConsoleApplication1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
ADOX.CatalogClass cat = new ADOX.CatalogClass();
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=D:\\AccessDB\\NewMDB.mdb;" +
"Jet OLEDB:Engine Type=5");
Console.WriteLine("Database Created Successfully");
cat = null;
}
}
}
I note in yours that you're not using the ADOX object to do anything and instead attempting to use OleDBCommands instead. If you're going to use ADOX then you should be creating the table using the ADOX object.
You should only open the connection if it is not already opened. Try this:
if (objOleDbConnection.State != ConnectionState.Open)
{
objOleDbConnection.Open()
}
i don't know if this suits you (never used ADOX) but:
http://www.pcreview.co.uk/forums/closing-access-file-created-adox-catalogclass-t1384766.html
tldr:
Marshal.ReleaseComObject(cat);
cat = null;

Connect to AS400 using .NET

I am trying to build a .NET web application using SQL to query AS400 database. This is my first time encountering the AS400.
What do I have to install on my machine (or the AS400 server) in order to connect?
(IBM iSeries Access for Windows ??)
What are the components of the connection string?
Where can I find sample codes on building the Data Access Layer using SQL commands?
Thanks.
You need the AS400 .Net data provider. Check here:
https://www-01.ibm.com/support/docview.wss?uid=isg3T1027163
For connection string samples, check here:
https://www.connectionstrings.com/as-400/
Also, check out the redbook for code examples and getting started.
http://www.redbooks.ibm.com/redbooks/pdfs/sg246440.pdf
Following is what I did to resolve the issue.
Installed the IBM i Access for Windows. Not free
Referred the following dlls in the project
IBM.Data.DB2.iSeries.dll
Interop.cwbx.dll (If Data Queue used)
Interop.AD400.dll (If Data Queue used)
Data Access
using (iDB2Command command = new iDB2Command())
{
command.Connection = (iDB2Connection)_connection;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue(Constants.ParamInterfaceTransactionNo, 1);
command.CommandText = dynamicInsertString;
command.ExecuteScalar();
}
Connection String
<add name="InterfaceConnection"
connectionString="Data Source=myserver.mycompany.com;User ID=idbname;Password=mypassxxx;
Default Collection=ASIPTA;Naming=System"/>
UPDATE
i Access for Windows on operating systems beyond Windows 8.1 may not be supported. Try the replacement product IBM i Access Client Solutions
IBM i Access Client Solutions
As mentioned in other answers, if you have the IBM i Access client already installed, you can use the IBM.Data.DB2.iSeries package.
If you don't have the IBM i Access software, you can leverage JTOpen and use the Java drivers. You'll need the nuget package JT400.78 which will pull in the IKVM Runtime.
In my case I needed to query a DB2 database on an AS400 and output a DataTable. I found several hints and small snippets of code but nothing comprehensive so I wanted to share what I was able to build up in case it helps someone else:
using com.ibm.as400.access;
using java.sql;
var sql = "SELECT * FROM FOO WITH UR";
DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());
Connection conn = DriverManager.getConnection(
"jdbc:as400:" + ServerName + ";prompt=false", UserName, Password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int ct = md.getColumnCount();
DataTable dt = new DataTable();
for(int i=1; i<=ct; i++)
dt.Columns.Add(md.getColumnName(i));
while (rs.next())
{
var dr = dt.NewRow();
for (int i = 1; i <= ct; i++)
dr[i - 1] = rs.getObject(i);
dt.Rows.Add(dr);
}
rs.close();
The conversion from RecordSet to DataTable is a little clunky and gave me bad flashbacks to my VBScript days. Performance likely isn't blinding fast, but it works.
Extremely old question - but this is still relevant. I needed to query our AS/400 using .NET but none of the answers above worked and so I ended up creating my own method using OleDb:
public DataSet query_iseries(string datasource, string query, string[] parameterName, string[] parameterValue)
{
try
{
// Open a new stream connection to the iSeries
using (var iseries_connection = new OleDbConnection(datasource))
{
// Create a new command
OleDbCommand command = new OleDbCommand(query, iseries_connection);
// Bind parameters to command query
if (parameterName.Count() >= 1)
{
for (int i = 0; i < parameterName.Count(); i++)
{
command.Parameters.AddWithValue("#" + parameterName[i], parameterValue[i]);
}
}
// Open the connection
iseries_connection.Open();
// Create a DataSet to hold the data
DataSet iseries_data = new DataSet();
// Create a data adapter to hold results of the executed command
using (OleDbDataAdapter data_adapter = new OleDbDataAdapter(command))
{
// Fill the data set with the results of the data adapter
data_adapter.Fill(iseries_data);
}
return iseries_data;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
And you would use it like so:
DataSet results = query_iseries("YOUR DATA SOURCE", "YOUR SQL QUERY", new string[] { "param_one", "param_two" }, new string[] { "param_one_value", "param_two_value"});
It returns a DataSet of the results returned. If anyone needs/wants a method for inserting/updating values within the IBM AS/400, leave a comment and I'll share...
I'm using this code and work very good for me!
Try
Dim sqltxt As String = "SELECT * FROM mplib.pfcarfib where LOTEF=" & My.Settings.loteproceso
dt1 = New DataTable
Dim ConAS400 As New OleDb.OleDbConnection
ConAS400.ConnectionString = "Provider=IBMDA400;" & _
"Data Source=192.168.100.100;" & _
"User ID=" & My.Settings.usuario & ";" & _
"Password=" & My.Settings.contrasena
Dim CmdAS400 As New OleDb.OleDbCommand(sqltxt, ConAS400)
Dim sqlAS400 As New OleDb.OleDbDataAdapter
sqlAS400.SelectCommand = CmdAS400
ConAS400.Open()
sqlAS400.Fill(dt1)
grid_detalle.DataSource = dt1
grid_detalle.DataMember = dt1.TableName
Catch ex As Exception
DevExpress.XtraEditors.XtraMessageBox.Show("ComunicaciĆ³n Con El AS400 No Establecida, Notifique a Informatica..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End Try
I recently found the ADO.Net driver available on NuGet. I have the iSeries client access installed on my PC, so I can't say if it works as a standalone, but it does connect. Theonly problem is I can't actually see any tables or procedures. I think there may be a schema or library or something I still haven't gotten down to. I will post if I find the answer. Meanwhile I can still get to the server and write most of my code with the NuGet adapter.
Check out http://asna.com/us/ as they have some development tools working with SQL and the AS400.

Categories

Resources