Creating database with Linq-to-SQL to change the path - c#

I managed to create a database using Linq-to-SQL with the following code:
private static DataClasses1DataContext _dataDC = new DataClasses1DataContext(#"C:\\database1.mdf");
public AddClient()
{
InitializeComponent();
DataContext = this;
_dataDC.CreateDatabase();
}
and this created a new local database on C: .
How can I change the #"C:\\database1.mdf" so that the file is created in the current directory from where I run the program ?

You can use one of these that suits your application and pass it in to new DataClasses1DataContext(HERE);
System.IO.Directory.GetCurrentDirectory();
Environment.CurrentDirectory;
Request.PhysicalPath

Check here how to ge the current directory path. Incude it inside parentheses:
How can I get the application's path in a .NET console application?

Related

Simple how to make a application directory path

Ok I know it is simple but I have forgotten how to do it. I want to create a folder in a directory but if I do "C:\Users\George\AppData\Roaming\myprogram" this only woks for me it will not work with everybody that I send it to
I tried "C:\Users\[User]\AppData\Roaming\Myprogram" but it says access denied so what can I use to make this work for everyone?
Here is the segment of code I am using to do this if it helps :
public Form2()
{
InitializeComponent();
Directory.CreateDirectory(#"C:\Users\[User]\AppData\Roaming\SkypeAdmin");
Directory.CreateDirectory(#"C:\Users\[User]\AppData\Roaming\SkypeAdmin\mem");
}
and I tried :
public Form2()
{
InitializeComponent();
Directory.CreateDirectory(#"C:\Users\User\AppData\Roaming\SkypeAdmin");
Directory.CreateDirectory(#"C:\Users\User\AppData\Roaming\SkypeAdmin\mem");
}
Your approach predefines a path for the folder so the location would only be valid for you and anyone else who has the specified loacation.
You can try this instead:
public Form1()
{
InitializeComponent();
DirectoryInfo di = Directory.CreateDirectory(skypeAdminPath);
DirectoryInfo di2 = Directory.CreateDirectory(skypeMemPath);
}
string skypeAdminPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "SkypeAdmin\\";
string skypeMemPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "SkypeAdmin\\mem\\";
Using Path.Combine:
string skypeAdminPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SkypeAdmin\\");
string skypeMemPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SkypeAdmin\\mem\\");
You can use CommonAppDataPath
string path = Application.CommonAppDataPath;//for folder with version
this may change every version of your application, if you dont want this behavior and you want Same Directory for all the version of your App you can use this
string path = Directory.GetParent(Application.CommonAppDataPath);
the directory will be readily available when your code executes above line, this is created on demand.
Note:
I assume that you want to create some directory for all users and use it. instead of doing so you can used shared Directory and access it from any user.
This is how a sample CommonAppData path look like
C:\ProgramData\MyCompany\WindowsFormsApplicationTest\1.0.0.0
Typically CommonAppDataBase\CompanyName\ProductName\Version
You need to use Enviroment.GetFolderPath for that:
Directory.CreateDirectory(Path.Combine(
Enviroment.GetFolderPath(Enviroment.SpecialFolder.ApplicationData),
#"\SkypeAdmin\"));
Directory.CreateDirectory(Path.Combine(
Enviroment.GetFolderPath(Enviroment.SpecialFolder.ApplicationData),
#"\SkypeAdmin\mem\"));
That does exactly what (I think) you mean to do. Your solution doesn't work because there is no folder called [User] or User in the system, so you can't create a folder in there, and Directory.CreateDirectory doesn't replace that for the user path for you.

Check local directory is a working copy before updating from svn

I am working on extracting svn repository using c# programming. I have added sharpsvn dll to my project and wrote following code
string localFolder= #"C:\Users\Desktop\LocalFolder\Dev\Websites\Service";
SvnClient client = new SvnClient();
SvnUriTarget target = new SvnUriTarget(#"http://svn.user.com/svn/websites/Branches/InternalServices");
SvnInfoEventArgs info;
client.GetInfo(target, out info);
//Specify the repository root as Uri
//Console.WriteLine("Repository version: {0}", info.Revision);
Console.WriteLine("Started checking out. Please wait few minutes");
client.CheckOut(target, localFolder);
//client.Update(localFolder);
I have checked out using 'client.checkout' method and i can update using 'client.update' method.
Let say i have folder 'services' in my machine. I am checking out files/folders initially using 'client.checkout' to this folder.
Next time when i run the program it should update automatically without checkout. How can i know if the service folder has already done a checkout once and now it should update?
You can determine whether a directory is a working copy like this:
public static bool IsWorkingCopy(string path)
{
using (var client = GetSvnClient())
{
var uri = client.GetUriFromWorkingCopy(path);
return uri != null;
}
}

DataDirectory Set up project

I am doing a SETUP project for a C# winforms, sqlite application.
Connection string seems to a bit of a problem. The user will put the Database he wants to work with at a location(which v will tell him). In this example it is "C:\\Program Files(x86)\\DefaultCompany\\RSetup"; The user can work his own copy of the DB.
So I am setting the data directory to this path in the Program.cs Main
This is the only way I can think of. If there is a better way thats grt!!.
App.config
<add name="ConnString" connectionString="|DataDirectory|\MySQlite.db;Compress=True;Version=3"
providerName="System.Data.Sqlite" />
Program.cs
Setting the datadirectory to the path of the executable. Currently hard coded the path of the executable
static void Main()
{
AppDomain.CurrentDomain.SetData("DataDirectory","C:\\Program Files(x86)\\DefaultCompany\\RSetup");
This doesn't seem to be working. It doesn't give any error except the data is not blank. Doesn't seem to be working in both set up and the regular project
Thank you
JC
You could ask the user where the database is located, store that path somewhere (such as User Settings) and then you can retrieve it at any time. This would give the user more flexibility of where to put it and multiple users on the same machine could have their own database if desired.
Here is some pseudocode...
string dbLocation = Properties.Settings.Default.DatabaseLocation;
if (string.IsNullOrWhiteSpace(dbLocation)
{
dbLocation = AskUserForLocation();
Properties.Settings.Default.DatabaseLocation = dbLocation;
Properties.Settings.Default.Save();
}
AppDomain.CurrentDomain.SetData("DataDirectory",dbLocation);
Using this approach you could also add a menu option to allow the user to change the location if desired.
It also gives you the ability to retrieve the value anywhere, including where you create a connection, you can append the path to the location between where you read the connection string and you create a new connection.
SQLiteConnection myConnection = new SQLiteConnection;();
myConnection.ConnectionString = Path.Combine(Properties.Settings.Default.DatabaseLocation, myConnectionString);
myConnection.Open();

Unable retrieve records from SQLite database for smart device application

I am using SQLite.NET with C#[ visual studio 2008] and added the 'System.Data.SQLite.dll' as reference. The following code works with Windows Application for fetching data from my database file into a datagrid.
private void SetConnection()
{
sql_con = new SQLiteConnection("Data Source=emp.db;Version=3;");
}
public DataTable LoadData()
{
SetConnection();
sql_con.Open();
sql_cmd = sql_con.CreateCommand();
string CommandText = "select * from employeedetails";
transaction=sql_con.BeginTransaction();
DA = new SQLiteDataAdapter(CommandText, sql_con);
DS.Reset();
DA.Fill(DS);
DT = DS.Tables[0];
transaction.Commit();
sql_con.Close();
return DT;
}
Invoking in:
private void Form1_Load(object sender, EventArgs e)
{
EmpTable obj = new EmpTable();
this.dataGridView1.DataSource = obj.LoadData();
}
The same code not working with C# 'Smart Device Application'. It shows an exception: no such table 'employeedetails'.
For Smart Device Application I have added the System.Data.SQLite.dll from "SQLite/CompactFramework" folder.
Please help me to resolve this.
Thanks in advance.
I'm not sure if this is what is causing your issue, but we've had issues in the past with mobile devices and sqlite where this solved it:
For an application using the compact framework, you need to include SQLite.Interop.xxx.DLL in your project (in addition to the regular System.Data.SQLite.DLL). Make sure you set the file to copy if newer or copy always.
Keep in mind that you can't set a reference to the interop dll. You must include it in the project by adding it as a file.
For more information check this website under the Distributing The SQLite Engine and ADO.NET Assembly section.
Thank You Guys,
I've resolved the Problem. As 'siyw' said, the problem was the application could not find the "db file".
For windows application,
The db file has to be located in debug folder where the .exe file is generated. So that, no need to specify the path of the DB file.
For Smart Device Application,
The DB file will be generated in the root folder of the device. If we bind the db file with exe means, it wont find it and it will create a new database in root folder.
To avoid that, while crating CAB file we have to create custom folder [ ex. DBfolder ] and put the db file in the folder.
Set the path in the connection String as,
sql_con = new SQLiteConnection("Data Source=DBfolder/emp.db;Version=3;");
Now, the db is found by the Application.
sql_con = new SQLiteConnection("Data Source=emp.db;Version=3;");
I think you need to specify the full path here, and make sure it's correct. If the path is to a non-existent file, it will create a new emp.db database file there instead. This new file will obviously be empty and without any tables, hence it would give a no such table 'employeedetails' exception such as you're getting if you query it.

Get directory where executed code is located

I know that in the same directory where my code is being executed some files are located. I need to find them and pass to another method:
MyLib.dll
Target1.dll
Target2.dll
Foo(new[] { "..\\..\\Target1.dll", "..\\..\\Target2.dll" });
So I call System.IO.Directory.GetFiles(path, "*.dll"). But now I need to get know the path:
string path = new FileInfo((Assembly.GetExecutingAssembly().Location)).Directory.FullName)
but is there more short way?
You may try the Environment.CurrentDirectory property. Note that depending on the type of application (Console, WinForms, ASP.NET, Windows Service, ...) and the way it is run this might behave differently.
Environment.CurrentDirectory returns the current directory, not the directory where the executed code is located. If you use Directory.SetCurrentDirectory, or if you start the program using a shortcut where the directory is set this won't be the directory you are looking for.
Stick to your original solution. Hide the implementation (and make it shorter) using a property:
private DirectoryInfo ExecutingFolder
{
get
{
return new DirectoryInfo (
System.IO.Path.GetDirectoryName (
System.Reflection.Assembly.GetExecutingAssembly().Location));
}
}

Categories