How to add entity-framework to console application (images are included) - c#

I try to add entity-framework to console application:
I press "add new item" and
then
then
then I added code:
class Program
{
static void Main(string[] args)
{
try
{
Database1Entities db = new Database1Entities();
db.AddToTableTest(new TableTest { name = "name" });
db.SaveChanges();
int count = db.TableTest.Count();
int ui = 9 + 0;
}
catch (Exception e)
{
}
}
}
It gives no error, but I don't see any changes in database.
I described the issue better here

I did the same steps you did to setup a EF model. your database.mdf file has the Copy to Output Directory set to Copy always, that means that every time you hit F5 (build or debug your app) the file is getting replaced by the empty one on your project.
Changing the Copy to Output Directory on the Properties window of the mdf file should solve your problem.
If you use Copy if newer you are going to be persisting any modifications on the contents of the database until you edit the database (mdf) itself.
With Do not copy any change to the mdf file is not going to get reflected on your application and will probably generate problems with EF.
I recommend for this scenario that you use Copy if newer and fill your basic data in the mdf file so you will have it always available.

Related

c# Form Project won't save Setting changes of Console Project

Background
Console Application:
I have a console application that retrieves data from a spreadsheet using the google sheets API. This application is automated by running it every 5 minutes with windows scheduler.
Form Application:
In the same solution I have created a windows form project that can be run manually, outside of the automation process to tweak any settings without disturbing the 5 minute process. (i.e. If we want to change spreadsheet ID to fetch data form a different spreadsheet, or if i want to change the output folder of where the data is being fetched)
My Goal
I'm trying to develop a form project that will edit the "settings.settings" file of another project in the same solution. Below is a screenshot of how i have my solution laied out:
What I've done so far
I've already added a reference from my sheetstocsv project in my SettingsUI Project, and i've successfully created a form that accesses sheetstocsv's Settings and edits them when a save button is clicked. Shown below is the function that's supposed to save the new settings from the form.
private void Save_Button_Click(object sender, EventArgs e)
{
sheetstocsv.Properties.Settings.Default.outputdir = OutputDirectory_TextBox.Text;
sheetstocsv.Properties.Settings.Default.spreadsheetID = SpreadsheetID_Textbox.Text;
sheetstocsv.Properties.Settings.Default.Entity = Entity_Texbox.Text;
sheetstocsv.Properties.Settings.Default.headernum = (int)Columns_NumericUpDown.Value;
string headers = "";
for (int i = 0; i < (int)Columns_NumericUpDown.Value; i++)
{
headers = headers + Columns_DataGridView.Rows[0].Cells[i].Value.ToString() + ",";
}
sheetstocsv.Properties.Settings.Default.headers = headers;
sheetstocsv.Properties.Settings.Default.configured = true;
sheetstocsv.Properties.Settings.Default.Save();
MessageBox.Show("Saving Complete!", "Settings",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
How I'm trying to do it
Below is a code snippet of how i'm only letting the sheetstocsv project continue if the configuration file has configured it first
//Check for if configured
if (Properties.Settings.Default.configured == false)
{
Console.WriteLine("Program has not been configured yet! Please Run SettingsUI first to start this program.");
Console.ReadLine();
Environment.Exit(0);
}
My Problem
Whenever I run my settingsUI, save, and then run my sheetstocsv project the changes that were supposed to be saved are not. and it will not allow the program move foward.
Edit
Below is the full form .cs that shows how i'm editing the properties of the other project
using sheetstocsv;
namespace SettingsUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Columns_DataGridView.RowCount = 1;
Columns_DataGridView.ColumnCount =(int)Columns_NumericUpDown.Value;
}
// Event handlers for other UI elemets here.......
private void Save_Button_Click(object sender, EventArgs e)
{
sheetstocsv.Properties.Settings.Default.outputdir = OutputDirectory_TextBox.Text;
sheetstocsv.Properties.Settings.Default.spreadsheetID = SpreadsheetID_Textbox.Text;
sheetstocsv.Properties.Settings.Default.Entity = Entity_Texbox.Text;
sheetstocsv.Properties.Settings.Default.headernum = (int)Columns_NumericUpDown.Value;
string headers = "";
for (int i = 0; i < (int)Columns_NumericUpDown.Value; i++)
{
headers = headers + Columns_DataGridView.Rows[0].Cells[i].Value.ToString() + ",";
}
sheetstocsv.Properties.Settings.Default.headers = headers;
sheetstocsv.Properties.Settings.Default.configured = true;
sheetstocsv.Properties.Settings.Default.Save();
MessageBox.Show("Saving Complete!", "Settings", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
}
I don't quite have enough info from your question (see comment from Rufus), but I am guessing that your console app launches your WinForm? If this is the case, what is likely happening is this:
1) Console app starts, and loads the config file into memory.
2) Your Winform launches and changes the config file.
3) Console app overwrites the changes to the config file on exit since it read it before the changes were made.
You could just move the winform into your console project, then just do something like this:
Properties.Settings.Default.outputdir = OutputDirectory_TextBox.Text;
...
Adding More Info (Oct 1):
I must be honest, doing what you're doing is a little strange, and I would really rethink referencing an executable to change its default settings. Just because VS lets you do this, doesn't necessarily mean you should. But if you must, there are a couple other things you can try:
1) You can simply parse the xml settings file and change node values of the settings you want to change. System.Xml namespace will make very short work of this. The post below has good examples:
Change xml node value
2) Try wrapping the code that is currently in your button click event handler with some method inside the console project. This way, you're calling a method that changes the settings, rather than trying to change the settings from an external assembly.
Note: neither of those methods will work if your console app is running while you're making changes to its config file. On shut down, the console app will overwrite the settings file with the settings it loaded into memory when it started up. If the console app isn't running, 1) will definitely work.

C# Not saving data in MS Access Database [duplicate]

I have following C# code in a console application.
Whenever I debug the application and run the query1 (which inserts a new value into the database) and then run query2 (which displays all the entries in the database), I can see the new entry I inserted clearly. However, when I close the application and check the table in the database (in Visual Studio), it is gone. I have no idea why it is not saving.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
string fileName = "FlowerShop.sdf";
string fileLocation = "|DataDirectory|\\";
DatabaseAccess dbAccess = new DatabaseAccess();
dbAccess.Connect(fileName, fileLocation);
Console.WriteLine("Connected to the following database:\n"+fileLocation + fileName+"\n");
string query = "Insert into Products(Name, UnitPrice, UnitsInStock) values('NewItem', 500, 90)";
string res = dbAccess.ExecuteQuery(query);
Console.WriteLine(res);
string query2 = "Select * from Products";
string res2 = dbAccess.QueryData(query2);
Console.WriteLine(res2);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
class DatabaseAccess
{
private SqlCeConnection _connection;
public void Connect(string fileName, string fileLocation)
{
Connect(#"Data Source=" + fileLocation + fileName);
}
public void Connect(string connectionString)
{
_connection = new SqlCeConnection(connectionString);
}
public string QueryData(string query)
{
_connection.Open();
using (SqlCeDataAdapter da = new SqlCeDataAdapter(query, _connection))
using (DataSet ds = new DataSet("Data Set"))
{
da.Fill(ds);
_connection.Close();
return ds.Tables[0].ToReadableString(); // a extension method I created
}
}
public string ExecuteQuery(string query)
{
_connection.Open();
using (SqlCeCommand c = new SqlCeCommand(query, _connection))
{
int r = c.ExecuteNonQuery();
_connection.Close();
return r.ToString();
}
}
}
EDIT: Forgot to mention that I am using SQL Server Compact Edition 4 and VS2012 Express.
It is a quite common problem. You use the |DataDirectory| substitution string. This means that, while debugging your app in the Visual Studio environment, the database used by your application is located in the subfolder BIN\DEBUG folder (or x86 variant) of your project. And this works well as you don't have any kind of error connecting to the database and making update operations.
But then, you exit the debug session and you look at your database through the Visual Studio Server Explorer (or any other suitable tool). This window has a different connection string (probably pointing to the copy of your database in the project folder). You search your tables and you don't see the changes.
Then the problem get worse. You restart VS to go hunting for the bug in your app, but you have your database file listed between your project files and the property Copy to Output directory is set to Copy Always. At this point Visual Studio obliges and copies the original database file from the project folder to the output folder (BIN\DEBUG) and thus your previous changes are lost.
Now, your application inserts/updates again the target table, you again can't find any error in your code and restart the loop again until you decide to post or search on StackOverflow.
You could stop this problem by clicking on the database file listed in your Solution Explorer and changing the property Copy To Output Directory to Copy If Newer or Never Copy. Also you could update your connectionstring in the Server Explorer to look at the working copy of your database or create a second connection. The first one still points to the database in the project folder while the second one points to the database in the BIN\DEBUG folder. In this way you could keep the original database ready for deployment purposes and schema changes, while, with the second connection you could look at the effective results of your coding efforts.
EDIT Special warning for MS-Access database users. The simple act of looking at your table changes the modified date of your database ALSO if you don't write or change anything. So the flag Copy if Newer kicks in and the database file is copied to the output directory. With Access better use Copy Never.
Committing changes / saving changes across debug sessions is a familiar topic in SQL CE forums. It is something that trips up quite a few people. I'll post links to source articles below, but I wanted to paste the answer that seems to get the best results to the most people:
You have several options to change this behavior. If your sdf file is part of the content of your project, this will affect how data is persisted. Remember that when you debug, all output of your project (including the sdf) if in the bin/debug folder.
You can decide not to include the sdf file as part of your project and manage the file location runtime.
If you are using "copy if newer", and project changes you make to the database will overwrite any runtime/debug changes.
If you are using "Do not copy", you will have to specify the location in code (as two levels above where your program is running).
If you have "Copy always", any changes made during runtime will always be overwritten
Answer Source
Here is a link to some further discussion and how to documentation.

How to insert data into a local datatable in C#? [duplicate]

I have following C# code in a console application.
Whenever I debug the application and run the query1 (which inserts a new value into the database) and then run query2 (which displays all the entries in the database), I can see the new entry I inserted clearly. However, when I close the application and check the table in the database (in Visual Studio), it is gone. I have no idea why it is not saving.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
string fileName = "FlowerShop.sdf";
string fileLocation = "|DataDirectory|\\";
DatabaseAccess dbAccess = new DatabaseAccess();
dbAccess.Connect(fileName, fileLocation);
Console.WriteLine("Connected to the following database:\n"+fileLocation + fileName+"\n");
string query = "Insert into Products(Name, UnitPrice, UnitsInStock) values('NewItem', 500, 90)";
string res = dbAccess.ExecuteQuery(query);
Console.WriteLine(res);
string query2 = "Select * from Products";
string res2 = dbAccess.QueryData(query2);
Console.WriteLine(res2);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
class DatabaseAccess
{
private SqlCeConnection _connection;
public void Connect(string fileName, string fileLocation)
{
Connect(#"Data Source=" + fileLocation + fileName);
}
public void Connect(string connectionString)
{
_connection = new SqlCeConnection(connectionString);
}
public string QueryData(string query)
{
_connection.Open();
using (SqlCeDataAdapter da = new SqlCeDataAdapter(query, _connection))
using (DataSet ds = new DataSet("Data Set"))
{
da.Fill(ds);
_connection.Close();
return ds.Tables[0].ToReadableString(); // a extension method I created
}
}
public string ExecuteQuery(string query)
{
_connection.Open();
using (SqlCeCommand c = new SqlCeCommand(query, _connection))
{
int r = c.ExecuteNonQuery();
_connection.Close();
return r.ToString();
}
}
}
EDIT: Forgot to mention that I am using SQL Server Compact Edition 4 and VS2012 Express.
It is a quite common problem. You use the |DataDirectory| substitution string. This means that, while debugging your app in the Visual Studio environment, the database used by your application is located in the subfolder BIN\DEBUG folder (or x86 variant) of your project. And this works well as you don't have any kind of error connecting to the database and making update operations.
But then, you exit the debug session and you look at your database through the Visual Studio Server Explorer (or any other suitable tool). This window has a different connection string (probably pointing to the copy of your database in the project folder). You search your tables and you don't see the changes.
Then the problem get worse. You restart VS to go hunting for the bug in your app, but you have your database file listed between your project files and the property Copy to Output directory is set to Copy Always. At this point Visual Studio obliges and copies the original database file from the project folder to the output folder (BIN\DEBUG) and thus your previous changes are lost.
Now, your application inserts/updates again the target table, you again can't find any error in your code and restart the loop again until you decide to post or search on StackOverflow.
You could stop this problem by clicking on the database file listed in your Solution Explorer and changing the property Copy To Output Directory to Copy If Newer or Never Copy. Also you could update your connectionstring in the Server Explorer to look at the working copy of your database or create a second connection. The first one still points to the database in the project folder while the second one points to the database in the BIN\DEBUG folder. In this way you could keep the original database ready for deployment purposes and schema changes, while, with the second connection you could look at the effective results of your coding efforts.
EDIT Special warning for MS-Access database users. The simple act of looking at your table changes the modified date of your database ALSO if you don't write or change anything. So the flag Copy if Newer kicks in and the database file is copied to the output directory. With Access better use Copy Never.
Committing changes / saving changes across debug sessions is a familiar topic in SQL CE forums. It is something that trips up quite a few people. I'll post links to source articles below, but I wanted to paste the answer that seems to get the best results to the most people:
You have several options to change this behavior. If your sdf file is part of the content of your project, this will affect how data is persisted. Remember that when you debug, all output of your project (including the sdf) if in the bin/debug folder.
You can decide not to include the sdf file as part of your project and manage the file location runtime.
If you are using "copy if newer", and project changes you make to the database will overwrite any runtime/debug changes.
If you are using "Do not copy", you will have to specify the location in code (as two levels above where your program is running).
If you have "Copy always", any changes made during runtime will always be overwritten
Answer Source
Here is a link to some further discussion and how to documentation.

sqlclient fails to execute anything except select statements [duplicate]

I have following C# code in a console application.
Whenever I debug the application and run the query1 (which inserts a new value into the database) and then run query2 (which displays all the entries in the database), I can see the new entry I inserted clearly. However, when I close the application and check the table in the database (in Visual Studio), it is gone. I have no idea why it is not saving.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlServerCe;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
string fileName = "FlowerShop.sdf";
string fileLocation = "|DataDirectory|\\";
DatabaseAccess dbAccess = new DatabaseAccess();
dbAccess.Connect(fileName, fileLocation);
Console.WriteLine("Connected to the following database:\n"+fileLocation + fileName+"\n");
string query = "Insert into Products(Name, UnitPrice, UnitsInStock) values('NewItem', 500, 90)";
string res = dbAccess.ExecuteQuery(query);
Console.WriteLine(res);
string query2 = "Select * from Products";
string res2 = dbAccess.QueryData(query2);
Console.WriteLine(res2);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
class DatabaseAccess
{
private SqlCeConnection _connection;
public void Connect(string fileName, string fileLocation)
{
Connect(#"Data Source=" + fileLocation + fileName);
}
public void Connect(string connectionString)
{
_connection = new SqlCeConnection(connectionString);
}
public string QueryData(string query)
{
_connection.Open();
using (SqlCeDataAdapter da = new SqlCeDataAdapter(query, _connection))
using (DataSet ds = new DataSet("Data Set"))
{
da.Fill(ds);
_connection.Close();
return ds.Tables[0].ToReadableString(); // a extension method I created
}
}
public string ExecuteQuery(string query)
{
_connection.Open();
using (SqlCeCommand c = new SqlCeCommand(query, _connection))
{
int r = c.ExecuteNonQuery();
_connection.Close();
return r.ToString();
}
}
}
EDIT: Forgot to mention that I am using SQL Server Compact Edition 4 and VS2012 Express.
It is a quite common problem. You use the |DataDirectory| substitution string. This means that, while debugging your app in the Visual Studio environment, the database used by your application is located in the subfolder BIN\DEBUG folder (or x86 variant) of your project. And this works well as you don't have any kind of error connecting to the database and making update operations.
But then, you exit the debug session and you look at your database through the Visual Studio Server Explorer (or any other suitable tool). This window has a different connection string (probably pointing to the copy of your database in the project folder). You search your tables and you don't see the changes.
Then the problem get worse. You restart VS to go hunting for the bug in your app, but you have your database file listed between your project files and the property Copy to Output directory is set to Copy Always. At this point Visual Studio obliges and copies the original database file from the project folder to the output folder (BIN\DEBUG) and thus your previous changes are lost.
Now, your application inserts/updates again the target table, you again can't find any error in your code and restart the loop again until you decide to post or search on StackOverflow.
You could stop this problem by clicking on the database file listed in your Solution Explorer and changing the property Copy To Output Directory to Copy If Newer or Never Copy. Also you could update your connectionstring in the Server Explorer to look at the working copy of your database or create a second connection. The first one still points to the database in the project folder while the second one points to the database in the BIN\DEBUG folder. In this way you could keep the original database ready for deployment purposes and schema changes, while, with the second connection you could look at the effective results of your coding efforts.
EDIT Special warning for MS-Access database users. The simple act of looking at your table changes the modified date of your database ALSO if you don't write or change anything. So the flag Copy if Newer kicks in and the database file is copied to the output directory. With Access better use Copy Never.
Committing changes / saving changes across debug sessions is a familiar topic in SQL CE forums. It is something that trips up quite a few people. I'll post links to source articles below, but I wanted to paste the answer that seems to get the best results to the most people:
You have several options to change this behavior. If your sdf file is part of the content of your project, this will affect how data is persisted. Remember that when you debug, all output of your project (including the sdf) if in the bin/debug folder.
You can decide not to include the sdf file as part of your project and manage the file location runtime.
If you are using "copy if newer", and project changes you make to the database will overwrite any runtime/debug changes.
If you are using "Do not copy", you will have to specify the location in code (as two levels above where your program is running).
If you have "Copy always", any changes made during runtime will always be overwritten
Answer Source
Here is a link to some further discussion and how to documentation.

Wix - File is locked for delete after opening its database

I have some problems while trying using WindowsInstaller library or Wix Microsoft.Deployment.WindowsInstaller.
I'm, getting exception that the file being used by the process and I cannot delete it even though I've closed all record,view and database and disposed them.
try
{
string currentDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string msiPath = "PathTo\MyMSI.msi";
using (InstallPackage installPackage = new InstallPackage(msiPath, DatabaseOpenMode.ReadOnly))
{
string query = "SELECT * FROM Property WHERE Property = 'ProductVersion'";
using (View view = installPackage.OpenView(query))
{
view.Execute();
using (Record record = view.Fetch())
{
string version = record.GetString(2);
Console.WriteLine(version);
record.Close();
}
view.Close();
}
installPackage.Close();
}
File.Delete(msiPath);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
And still I get the following:
Access to the path 'PathTo\MyMSI.msi' is denied.
I've also tried with the object
Database
Any help will be appreciated.
I was able to figure out what is blocking the delete action.
It appears that the file was in read only.
I don't know why I got this kind of exception but the following solved it:
//removing read only from file in order to interact with it
FileInfo fileInfo = new FileInfo(msiPath);
if (fileInfo.IsReadOnly)
{
fileInfo.IsReadOnly = false;
}
Hope it will help others.
I appreciate everyone who helped here for your time.
Below are some steps you could follow for ur problem :
Wait a minute and try deleting the file again, sometimes Windows or the program using the file may still be closing and therefore still using the file you're attempting to delete.
Close and Explorer window and re-open.
Locate the program using the file and close it. If you're uncertain what program is using the file, close all programs until you're able to delete the file.
Try using unlocker, a free software program designed to unlock any file being used by Windows or other programs without restarting the computer.
Reboot the computer. If after closing all programs you're still unable to delete the file, it's likely that something in the background is still using the file.
If after rebooting the computer you're still unable to delete the file, boot the computer into Safe Mode and delete the file.
Thanks

Categories