I need to retrieve the Firefox history(url) using C# windows Form application.
I am Using Firefox 17.0.1 version.
I have been tried with DDEClient class and SQLLite database. both are not working.
When I use the DDEClient class I can able to get the active tab URL from the Firefox, when I use the SQLLite Database, it is not working VS2010.
How can I achieve this requirement?
private static Logger logger = LogManager.GetCurrentClassLogger();
private static string dbName = "places.sqlite";
private static int dbColumnUrl = 1;
private static int dbColumnVisitDate = 9;
String strConnection = #"Data Source=" + newPath + #";Version=3;";
using (SQLiteConnection connection = new SQLiteConnection(strConnection))
{
string query = "select * from moz_places;";
using (SQLiteCommand cmd = new SQLiteCommand(query, connection))
{
connection.Open();
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
logger.Info("time: " + dr.GetValue(dbColumnVisitDate));
logger.Info("URL: " + dr.GetValue(dbColumnUrl));
}
}
}
}
Related
We are migrating webparts programmatically.
We used this code in the past but it is not working with modern authentication.
Can you share piece of code for doing this when legacyauth is turned off?
private string DownloadFile(string url)
{
SecureString theSecureString = new NetworkCredential("", _password).SecurePassword;
SharePointOnlineCredentials onlineCredentials = new
SharePointOnlineCredentials(_username, theSecureString);
_authCookieValue = onlineCredentials.GetAuthenticationCookie(new Uri(fileUrl));
using (CookieAwareWebClient client = new CookieAwareWebClient())
{
client.CookieContainer = new CookieContainer();
client.CookieContainer.Add(new Cookie("SPOIDCRL",
_authCookieValue.TrimStart("SPOIDCRL=".ToCharArray()), String.Empty, authority));
string localPath = Path.GetTempPath();
string temporaryGuid = Guid.NewGuid().ToString();
string path = System.IO.Path.Combine(localPath, temporaryGuid);
client.DownloadFile(fileUrl, path);
document = System.IO.File.ReadAllText(path);
System.IO.File.Delete(path);
}
}
etc...
}
We were calling it this way:
string itemWebPartDefUrl = string.Format(
"{0}{1}/_vti_bin/exportwp.aspx?pageurl={2}&guidstring={3}",
_rootPrefixURL,
webServerRelativeUrl,
pageURL,
wpDef.Id.ToString().ToLower()
);
Uri targetSite = new Uri(_context.Web.Url);
string xmlDef = DownloadFile(itemWebPartDefUrl, targetSite.Authority);
How do i write SQL Query Results into excel using Selenium Web Driver + Test NG
Example :
#Test(priority=5)
public void VerifyDataBase() {
try {
String query = "SELECT * FROM [xxx].[dbo].[xxx_FEINProductionCompany] where ProductionCompanyName like'%xxx%'";
System.out.println(query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next()) {
int FEIN_ID = rs.getInt("ACA_FEINProductionCompany_ID");
int FEIN_No = rs.getInt("FEIN");
String ProductionCompanyName = rs.getString("ProductionCompanyName");
String ProductionCompanyShortName = rs.getString("ProductionCompanyShortName");
String ModifiedDate = rs.getString("ModifiedDate");
String Username = rs.getString("Username");
String AddressLine1 = rs.getString("AddressLine1");
String AddressLine2 = rs.getString("AddressLine2");
String City = rs.getString("City");
String State = rs.getString("State");
int Zip = rs.getInt("Zip");
String PhoneNumber = rs.getString("PhoneNumber");
String ContactName = rs.getString("ContactName");
String ContactPhone = rs.getString("ContactPhone");
System.out.println("\nProductionCompanyName is: " + ProductionCompanyName);
System.out.println("\nFEIN is: " + FEIN_No);
System.out.println("\nAddressLine2 is: " + AddressLine2);
System.out.println("\nUsername is: " + Username);
TestUtil.assertEquals(Username, "xxxx","FEINScreen_Username");
TestUtil.assertEquals(AddressLine2, "2500 xx","FEINScreen_AddressLine2");
System.out.println("\nQuery Result Set is: "+ ProductionCompanyName+"\t"+FEIN_No+"\t"+AddressLine2+"\t"+Username);
System.out.println("\t");
}
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
You need to use java library/dependencies like apache poi.
Selenium or TestNG do not have any capability to interact with Excel.
use below link code and pass your sql query data to in it as an Input parameter
Refer:
https://howtodoinjava.com/library/readingwriting-excel-files-in-java-poi-tutorial/
I have an Access MDB File with just one table simply called "Sheet1". Inside Sheet1 I already have the Fields Identified, but I left the table empty of any records.
I'm trying to copy data from a CSV file into the Access Sheet1 table.
The code below works if the table does not already exist, but I get an error at the AccessCommand.ExecuteNonQuery(); line that says
System.Data.OleDb.OleDbException: Table 'Sheet1' already exists.
How do I revise this code so that I can import the CSV data into an empty Table with Fields already identified?
using System.Data.OleDb;
string filename = "MyCSV.csv";
int result = 0;
string dirPath = AppDomain.CurrentDomain.BaseDirectory + "DataBase\\";
string uploaderMDB = dirPath + "MyMDB.mdb";
OleDbConnection AccessConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + uploaderMDB);
AccessConnection.Open();
OleDbCommand AccessCommand = new OleDbCommand("SELECT * INTO [Sheet1] FROM [Text;FMT=Delimited;DATABASE=" + dirPath + ";HDR=No].[" + filename + "]", AccessConnection);
AccessCommand.ExecuteNonQuery();
AccessConnection.Close();
Try it this way.
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.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\your_path_here\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
public OleDbConnection myCon { get; set; }
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
I found a solution (it requires XLSX instead though...) for anyone interested. It uses the
Microsoft.Office.Interop.Access reference instead of OleDb.
string filename = "MyXLSX.xlsx";
string dirPath = AppDomain.CurrentDomain.BaseDirectory + "DataBase\\";
string uploaderMDB = dirPath + "MyMDB.mdb";
string fullPath = dirPath + filename;
Application _accessData = new ApplicationClass();
_accessData.Visible = false;
_accessData.OpenCurrentDatabase(uploaderMDB);
_accessData.DoCmd.OpenTable("SHEET1");
_accessData.DoCmd.TransferSpreadsheet(AcDataTransferType.acImport, AcSpreadSheetType.acSpreadsheetTypeExcel12, "Sheet1", fullPath, true, "MY_NAMED_RANGE");
_accessData.CloseCurrentDatabase();
_accessData.Visible = true;
_accessData.Quit(AcQuitOption.acQuitSaveAll);
System.Runtime.InteropServices.Marshal.ReleaseComObject(_accessData);
_accessData = null;
I have a method which has served me well, but now the queries have changed and I need to add a CommandTimeout to allow for the fact that some of the client machines on which this is executed are a little under-powered. The issue I'm having is the using lines as adding a CommandTimeout doesn't work.
The program itself pulls queries down from an SFTP server each night and then executes the queries against the client DB, writes the results to file then sends the results back to the SFTP server.
I can't improve the efficiency of the query (read only access) on the client machines, so I'm stuck with this method.
public void DumpTableToFile(string connection, string destinationFile, string QueryToExec)
{
string logDirectory = VariableStorage.logDirectory;
string Practice = VariableStorage.Practice;
try
{
SqlConnection conn = new SqlConnection(connection);
conn.Open();
using (var command = new SqlCommand(QueryToExec, conn))
using (var reader = command.ExecuteReader())
using (var outFile = File.CreateText(destinationFile))
{
string[] columnNames = GetColumnNames(reader).ToArray();
int numFields = columnNames.Length;
outFile.WriteLine(string.Join("\t", columnNames));
if (reader.HasRows)
{
while (reader.Read())
{
string[] columnValues =
Enumerable.Range(0, numFields)
.Select(i => reader.GetValue(i).ToString())
.Select(field => string.Concat("", field.Replace("\"", "\"\""), ""))
.ToArray();
outFile.WriteLine(string.Join("\t", columnValues));
}
}
}
}
catch (Exception e)
{
Program log = new Program();
log.WriteToLog(" Error: " + e);
SendEmailReport(Practice + " - Data Collection Error", " Error: " + e);
}
}
OK, found the answer. I had to remove the Using statements.
var command = new SqlCommand(QueryToExec, conn);
command.CommandTimeout = 300;
var reader = command.ExecuteReader();
var outFile = File.CreateText(destinationFile);
I have a situation where I have to convert excel single column to utf-8 and then to base64. I have gone through several post which suggests how to read excel file.
Reading Excel files from C#
But I am not sure that in my situation which is the best approach.
I have big files of 2MB.
Kindly suggest me.
I got the solution
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bgw.RunWorkerAsync();
var myConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\Language_Batch1_OneClick.xls';Extended Properties=Excel 8.0;"); ;
var myCommand = new OleDbCommand();
var upCommand = new OleDbCommand();
int i = 0;
try
{
string sql = null;
myConnection.Open();
myCommand.Connection = myConnection;
sql = "select ANSWER_CODE,Punjabi from [Batch_Lang_1$]";
myCommand.CommandText = sql;
var dataReader = myCommand.ExecuteReader();
while (dataReader.Read())
{
var langText = Convert.ToBase64String(Encoding.UTF8.GetBytes(dataReader["Punjabi"].ToString()));
if (langText.Length >= 1000)
{
continue;
}
var ansCode = dataReader["ANSWER_CODE"].ToString();
sql = "update [Batch_Lang_1$] set Punjabi= '" + langText + "' where ANSWER_CODE='" + ansCode + "'";
upCommand.Connection = myConnection;
upCommand.CommandText = sql;
upCommand.ExecuteNonQuery();
i++;
}
}
}
}