I am creating a Excel Addin through which i want to access a database. code is as follows
[ExcelFunction("My First Excel-DNA Function")]
public static string GreetFunction(string name)
{
GetConnection();
return "Hello" + " " + name;
}
public static void GetConnection()
{
//db = new SQLiteConnection("Data Source="+System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\Database\\XLSQLiteDemo.sqlite");
db = new SQLiteConnection("Data Source=Database/XLSQLiteDemo.sqlite");
try
{
db.Open();
cmd = db.CreateCommand();
System.Windows.MessageBox.Show("Connection created");
}
catch (SQLiteException ex)
{
System.Windows.MessageBox.Show(ex.ToString());
}
}
so when i give absolute path like c:/test/firstlibrary.../XLSQLiteDemo.sqlite it works.
but when i use relative path like db = new SQLiteConnection("Data Source=Database/XLSQLiteDemo.sqlite");
it throws an exception: unable to open database file error code 14.
the code which is in comment i.e.
//db = new SQLiteConnection("Data Source="+System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\Database\\XLSQLiteDemo.sqlite");
also doesn't work i.e. it calculates the absolute path but when i tried to debug; debugging is automatically terminated after db.Open();
and output in excel sheet is also #Value which indicates some error.
#adrino may be the "file" word in your string is the problem.remove it.
string relativePath = #"Database\XLSQLiteDemo.sqlite";
string currentPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
string absolutePath = System.IO.Path.Combine(currentPath, relativePath);
absolutePath=absolutePath.Remove(0, 6);//this code is written to remove file word from absolute path
string connectionString = string.Format("Data Source={0}", absolutePath);
this works on my machine.tell me if its correct.
Related
I just want the directory to open to "project_name\Scripts(sub_folder)\merge.sql"
I can't get rid of 'C:' and I cant get the actually data file to appear.
I received an"System.io.directorynotfoundexcpetion".
Here's my code:
private void MergeQuery()
{
//might need to change C: drive directory
//string derefQuery = #"\.\mergeSQL.sql";
using (SqlConnection mer = new SqlConnection(#"Data Source = address_name; Initial Catalog = catalog_name; Integrated Security=SSPI"))
{
{
mer.Open();
string path = Path.GetDirectoryName("\\project_name\\Scripts\\mergeSQL.sql ");
string mergeScript = System.IO.File.ReadAllText(path);
System.Collections.Generic.IEnumerable<string> commandStrings = Regex.Split(mergeScript, #"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (string commandString in commandStrings)
{
if (commandString.Trim() != "")
{
using (var command = new SqlCommand(commandString, mer))
{
command.ExecuteNonQuery();
}
Label2.Text = "Query merged";
}
}
}
}
first, there is an error in line
string path = Path.GetDirectoryName("\\project_name\\Scripts\\mergeSQL.sql ");
In that line you're getting directory path from file path, so path variable becomes \\project_name\\Scripts\\ or something similar. On next line you're trying to read file from that path variable, not from file.
What you need is to get path relative to web site root and then read file, like this
string path = HostingEnvironment.MapPath("~/Scripts/mergeSQL.sql ");
string mergeScript = System.IO.File.ReadAllText(path);
this way asp.net will get correct path from your website root's subfolder.
I would like to know if it's possible to ignore a file or a part of my code during a commit. To develop my solution I actually use two different computers, each using his own connection string to the database.
//Informations - DB
private const String _SERVER = "localhost";
private const String _DATABASE = "dbname";
private const String _UID = "";
private const String _PASSWORD = "";
//DB connection
public static MySqlConnection v_DBConnection;
public static void InititializeDB()
{
String v_ConnectionString = null;
MySqlConnectionStringBuilder v_MySqlConnectionStringBuilder;
try
{
v_ConnectionString = null;
v_MySqlConnectionStringBuilder = new MySqlConnectionStringBuilder();
v_MySqlConnectionStringBuilder.Server = _SERVER;
v_MySqlConnectionStringBuilder.UserID = _UID;
v_MySqlConnectionStringBuilder.Password = _PASSWORD;
v_MySqlConnectionStringBuilder.Database = _DATABASE;
//CONNECTION CHAIN
v_ConnectionString = v_MySqlConnectionStringBuilder.ToString();
v_DBConnection = new MySqlConnection(v_ConnectionString);
}
catch (Exception exception)
{
MessageBox.Show("InititializeDB fail due to:" + exception.ToString());
}
}
I would like during a commit ignore the file containing the string or exclude a part of the code (connection string).
I tried to add the file containing my connection chain in my .gitignore file but I'm not sure, I did'nt understandhow the .gitignore file work.
# Ignored files
DBConnection.cs
My database is located outside the application folder
Example:
Database: SampleApplication\Database\Database.sqlite
Application: SampleApplication\Application\program.cs
My code is as below.
string relativePath = #"SampleApplication\Database\Database.sqlite";
string currentPath;
string absolutePath;
string connectionString;
currentPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
absolutePath = Path.Combine(currentPath, relativePath);
connectionString = string.Format("Data Source={0};Version=3;Pooling=True;Max Pool Size=100;", absolutePath);
m_dbConnection = new SQLiteConnection(connectionString);
m_dbConnection.Open();
Alright, I figured it out guys.
string relativePath = #"Database\Database.sqlite";
var parentdir = Path.GetDirectoryName(Application.StartupPath);
string myString = parentdir.Remove(parentdir.Length -34, 34);
string absolutePath = Path.Combine(myString, relativePath);
string connectionString = string.Format("Data Source={0};Version=3;Pooling=True;Max Pool Size=100;", absolutePath);
m_dbConnection = new SQLiteConnection(connectionString);
m_dbConnection.Open();
I removed the characters from the parentdir till SampleApplication\ and added it with the relativePath. That makes an absolutePath to the database.
The number 34 in the third line signifies how many characters to be remove from the end of parentdir.
try this
var parentdir =Path.GetDirectoryName(System.Windows.Forms.Application.StartupPath);
I guess you need to modify your connection string, so for basic connect to SQL LITE DATABASE, you would do this:
Data Source=c:\mydb.db;Version=3;
enter code here
In memory database:
Data Source=:memory:;Version=3;New=True;
With password
Data Source=c:\mydb.db;Version=3;Password=myPassword;
You could do this also in your c# code:
var connectionString = #"data source=c:\TestData\testsqldata.s3db; Version=3;"
connection = new SQLiteConnection(connectionString);
connection.Open();
In an ASP CORE project if your db is in Data folder, write the following code in startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyContext>(options =>
options.UseSqlite("Data Source=" +
Path.Combine(Directory.GetCurrentDirectory(), "Data\\sqlite.db"))
);
}
I have a public string I need to use throughout my program.
public string connectionString = null;
I assign the value as below:
internal string accessString()
{
return connectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=" + DBFileName + ";" +
#"Persist Security Info=False";
}
When I run the method the first time the value is correct, however once the execution of the method is complete the value returns to null.
internal void selectDB()
{
try
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
DBFileName = choofdlog.FileName;
connectionString = accessString();
Saveproducts();
}
MessageBox.Show(connectionString);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}//select db ends
The above method gets the value perfectly.
internal void writeContents()// read all the text files to the Data base
{
try
{
MessageBox.Show(connectionString);
}
}
This method above returns null, even though its run after the second method has successfully assigned a value to connectionString.
How can I fix this, I don't want to use static
Use the Session for storing the Connection string or you can use the
connectionString as Static variable
then it will not reset the value.
How can I change this so that the method creates this value throughout
the program
You could do this, accessString now always return valid connection string.
public string connectionString = null;
accessString();
internal string accessString()
{
return string.IsNullOrEmpty(connectionString)?
#"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=" + DBFileName + ";" +
#"Persist Security Info=False" : connectionString;
}
I am quite new to using C# for reading Excel data. I am using Microsoft.ACE.OLEDB.12.0 to read an excel sheet data. But my problem is the sheet starts from the cell B4 (instead of usual A1) and hence I am facing difficulties while reading the data. Following is my method:
public static DataSet GetExcelFileData(String fileNameWPath, String sheetName, String rangeName, String fieldList, String whereClause)
{
DataSet xlsDS = new DataSet();
String xlsFields = String.Empty;
String xlsWhereClause = String.Empty;
String xlsSqlString = String.Empty;
String xlsTempPath = #"C:\temp\";
//Copy File to temp folder locations....
String xlsTempName = Path.GetFileNameWithoutExtension(fileNameWPath);
xlsTempName = xlsTempName.Replace(".", String.Empty).Replace(" ", "_").Replace("-", "_").Replace("&", String.Empty).Replace("~", String.Empty) + ".xls";
//Check if sqlFields and Where Clause is Empty....
if (String.IsNullOrEmpty(fieldList))
xlsFields = "*";
else
xlsFields = fieldList;
if (!String.IsNullOrEmpty(whereClause))
xlsWhereClause = whereClause;
//String oleDBConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source ={0};Extended Properties=\"Excel 8.0; IMEX=1\"", xlsTempPath + Path.GetFileName(xlsTempName));
String oleDBConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=NO;IMEX=0\"", xlsTempPath + Path.GetFileName(xlsTempName));
OleDbConnection xlsConnect = null;
try
{
File.Copy(fileNameWPath, xlsTempPath + Path.GetFileName(xlsTempName), true);
xlsConnect = new OleDbConnection(oleDBConnString);
OpenConnection(xlsConnect);
//Get Worksheet information
DataTable dbSchema = xlsConnect.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1)
{
throw new Exception(String.Format("Failed to get worksheet information for {0}", fileNameWPath));
}
DataRow[] sheets = dbSchema.Select(String.Format("TABLE_NAME LIKE '*{0}*'", sheetName.Replace("*", String.Empty)));
if (sheets.Length < 1)
{
throw new Exception(String.Format("Could not find worksheet {0} in {1}", sheetName, fileNameWPath));
}
else
{
string realSheetName = sheets[0]["TABLE_NAME"].ToString();
//Build Sql String
xlsSqlString = String.Format("Select {0} FROM [{1}${2}] {3}", xlsFields, sheetName, rangeName, xlsWhereClause);
//xlsSqlString = String.Format("Select {0} FROM [{1}${2}] {3}", xlsFields, sheetName, "", xlsWhereClause);
OleDbCommand cmd = new OleDbCommand(xlsSqlString, xlsConnect);
OleDbDataAdapter adapter = new OleDbDataAdapter(xlsSqlString, xlsConnect);
adapter.SelectCommand = cmd;
adapter.Fill(xlsDS);
return xlsDS;
}
}
catch (FormatException ex)
{
throw ex;
}
catch (Exception ex2)
{
if (ex2.Message.ToLower().Equals("no value given for one or more required parameters."))
{
throw new Exception(String.Format("Error in Reading File: {0}. \n Please Check if file contains fields you request Field List: {1}", fileNameWPath, xlsFields));
}
throw new Exception(String.Format("Error in Reading File: {0}\n Error Message: {1}", fileNameWPath, ex2.Message + ex2.StackTrace));
}
finally
{
CloseConnection(xlsConnect);
File.Delete(xlsTempPath + Path.GetFileName(xlsTempName));
}
}
Also, I have tried using the older veriosn of Jet Engine: Microsoft.Jet.OLEDB.4.0 and it works fine. But since we have migrated to 64 bit server, we must use the latest OleDb 12.0 engine. Everytime I specify a range ("B4:IV65536") and try to read data, I get the following exception:
"The Microsoft Office Access database engine could not find the object 'Report1$B4:IV65536'. Make sure the object exists and that you spell its name and the path name correctly."
Also, please note that I have tried many permutations-combinations of HDR, IMEX (setting them to Yes/No & 0/1 respectively but that hasn't helped).
Please suggest me a workaround.
Thanks,
Abhinav