It's my first try to to read test data for my automated test scripts from excel sheet using oledbconnection with Dapper. Whatever i do, i get invalid argument exception. I need to select the cell from column C based on the values in columns A and B. Here is the code:
class ExcelDataAccess
{
public static string TestDataFileConnection()
{
var fileName = ConfigurationManager.AppSettings[#"Path\TestData.xlsx"];
var con = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source = {0}; Extended Properties='Excel 12.0 Xml;HDR=YES;'", fileName);
return con;
}
public static UserData GetTestData(int TestCaseNumber, string Key)
{
using (var connection = new OleDbConnection(TestDataFileConnection()))
{
connection.Open();
var query = string.Format("select * from [DataSet$] where [TestCaseNumber]='{0}' and [Key]='{1}'", TestCaseNumber, Key);
var value = connection.Query<UserData>(query).FirstOrDefault();
connection.Close();
return value;
}
}
}
In the UserData class I get and set public variables with the table headers.
Thanks for any help!
I'm guessing this line is the problem:
var fileName = ConfigurationManager.AppSettings[#"Path\TestData.xlsx"];
Do you really have an entry in your app.config with a key of Path\TestData.xlsx? Can you show that line of your app's .config file?
I think you may have used the wrong key. Double check your entries in the appSettings section of your app's .config file.
Related
I am using a method(GetConnectionString()) in a class(Utility.cs) as part of another method(fillDT()) in another class(Function.cs).
internal class Utility
{
internal static string GetConnectionString()
{
//Util-2 Assume failure.
string returnValue = null;
//Util-3 Look for the name in the connectionStrings section.
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Assignment_new.Properties.Settings.connString"];
//If found, return the connection string.
if (settings != null)
returnValue = settings.ConnectionString;
return returnValue;
}
}
class Functions
{
public static DataTable fillDT(string sqlstatement) //Fills the datatable with data from sqlstatement
{
string connstr = Assignment_new.Utility.GetConnectionString();
SqlConnection con = new SqlConnection(connstr);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlstatement, con);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Whenever I call Functions.fillDT(#"sql statement"), the error pops out saying connection string is not initialized.
Make sure you use proper config files to save your connection string. I see you are tagging this question as WinForms, so your connection string should be inside App.Config file not in Web.Config. If this a web application then you should do the opposite, keep it in Web.Config file at the top most directory.
Also, if this is a desktop application and you are using App.Config file to save your settings, make sure that file is copied to your output directory, where the executable stays (usually the same name as the executable. i.e <EXNAme>.exe.config). Otherwise when the application runs, it won't find it.
You just checked your connection string to be null. Check string.IsNullOrEmpty() to see if it's not null. Besides, you need to set breakpoint and check if the connection string value you see in your app.config actually retrieved in your code and it is correct.
I'm trying to use *.dbf (dBase IV) file to fetch some needed geodata from it (shapefiles).
The strange thing is that dBase JET OleDb 4.0 provider is telling me, that there isn't such an object, but it does exist!
Proof:
http://s21.postimg.org/eaj4h91uv/image.png
Source-code:
static void Test()
{
const string path = "C:\\buildings.dbf";
string conStr = String.Format("Provider = Microsoft.Jet.Oledb.4.0; Data Source = {0}; Extended Properties = \"dBase IV\"", Path.GetDirectoryName(path));
var connection = new OleDbConnection(conStr);
connection.Open();
var command = new OleDbCommand(string.Format("select NAME from {0}", Path.GetFileName(path)), connection);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var str = (string)reader["NAME"];
}
}
connection.Close();
}
static void Main()
{
try
{
Test();
}
catch (Exception exc)
{
Console.WriteLine(exc);
}
}
It APPEARS you have a good connection string... The connection string should point to the PATH ONLY where the .dbf files are located. However, even as a test, having this .dbf file in the ROOT of C:\ MIGHT be posing as a problem, I would for grins, just move it into a sub-folder off the root, such as C:\TEST\buildings.dbf
Next, the query once connection is open to the current "path", it can see any .dbf table in that path. You should only need
var command = new OleDbCommand("select NAME from buildings", connection);
The ".dbf" is implied for querying. The only other problem that MIGHT be causing the problem is 'NAME' is a reserved word and probably needs name (tics) wrapped around it so it knows the actual COLUMN NAME and not the reserved word.
Different providers may have issue with the tic marks, so you may need to wrap in [name] square brackets instead.
OK, I've been working on this since late last night and early this morning. I am trying to insert some data into a SQL Server CE database. I am at the end of my rope.
Here is the code I am trying to implement:
public static void InsertData(string sqlStatement)
{
try
{
//string strConn = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
//string StartupPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Remove(0, 6); // remove file:\\
//string connectionString = #"Data Source=Database1.sdf";
//string connectionString = #"Data Source = |DataDirectory|\Database1.sdf";
//string connectionString = #"Data Source = C:\Users\My\Documents\Visual Studio 2012\Projects\VIN_Decoder\VIN Decoder\VIN Decoder\Database1.sdf"
//string connectionString = string.Format("Data Source={0}; Persist Security Info=False;", Path.Combine(Application.StartupPath, "Database1.sdf"));
//THIS ONE ACTUALLY WORKS!!!!!!!!!!!! :
//string connectionString = #"Data Source = C:\Users\My\Documents\Visual Studio 2012\Projects\VIN_Decoder\VIN Decoder\VIN Decoder\Database1.sdf"
string connectionString = Properties.Settings.Default.Database1ConnectionString;
SqlCeConnection sqlceCon = new SqlCeConnection(connectionString);
sqlceCon.Open();
SqlCeCommand sqlCeCom = new SqlCeCommand(sqlStatement, sqlceCon);
sqlCeCom.ExecuteNonQuery();
sqlCeCom.Dispose();
sqlceCon.Close();
}
catch (Exception e)
{
}
}
You can see all of the commented connection strings to see what I have tried. The strange thing is that I can simply use the following connection string in another method (a SELECT statement, not an INSERT INTO statement) that gets a single value from the data and it works fine.
string connectionString = #"Data Source = |DataDirectory|\Database1.sdf";
I have tested the query directly and like the comment says, the static path does work so that tells me my query is good. But of course I need something relative for publishing and multi-developer development.
Most of the connection strings I have tried allow the try block to complete with no errors, but the data doesn't get inserted.
Any suggestions?
I searched my heart out before posting this question, but Simon is right about similarity. However, we're going to have a better answer here. Corak is correct. I set property to not copy, deleted copy in bin\debug folder and app wouldn't run in debug mode because it couldn't find db even though paths all point to other file location. App is looking for copy in bin\debug. Ultimately, it was working all along. I recommend someone to make a connection to the copy in bin\debug so they can test values in the Server Explorer. Thanks for your help Corak and everyone else.
/*If your solution is web application, make sure Database1.sdf location path is under the
* App_Data folder
* Web.Config <add name="LocalDB" connectionString="Data Source=|DataDirectory|\Database1.sdf"/>
*/
protected string ConnString
{
get
{
return ConfigurationManager.ConnectionStrings["LocalDB"].ToString();
}
}
/*
* or you can use try absolute path as connectionstring
* modify your directory path as PhysicalApplicationPath result
*/
public string BaseDirConnString
{
get
{
if ((HttpContext.Current == null) || (HttpContext.Current.Request == null))
{
throw new ApplicationException("...");
}
return #"Data Source=" + HttpContext.Current.Request.PhysicalApplicationPath + "VIN Decoder\\Database1.sdf";
}
}
protected SqlCeConnection SqlCeConnection
{
get
{
var connection = new SqlCeConnection(BaseDirConnString);
connection.Open();
return connection;
}
}
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.
I'm creating the database file using the following method.
public bool CreateDatabaseFile()
{
try
{
Stream file = File.Create(DBPath);
file.Close();
return true;
}
catch (Exception)
{
return false;
}
}
But when I call
public void CreateDatabaseStruct()
{
var queries = new List<string>
{
"create table contacts (\"name\" nvarchar,\"emails\" nvarchar);",
"create table errors (\"code\" int, message nvarchar);"
};
foreach (string query in queries)
{
var con = new SqlCeConnection(connectionString);
con.Open();
var cmd = con.CreateCommand();
cmd.CommandText = query;
cmd.ExecuteNonQuery();
con.Close();
}
}
it returns
The specified locale is not supported on this operating system [LCD - 1].
How do I fix this?
UPDATE
The connection string:
public static readonly string DBPath = "db.sdf";
public static readonly string connectionString = String.Format("Data Source={0}; Password=...", DBPath);
the solution is create it using SqlCeEngine.CreateDatabase().
Are you specifying a locale ID in your connection string via LCD=#### (where #### is a supported 4 digit LCID number)? If so, are you sure it is supported on your operating system?
If not, perhaps you have your operating system set to a different culture, that is not supported by the database.
Please post your connection string and give some more information on which O/S you are using (as mentioned by #MusiGenesis).