Unable to update database .MDF is Read Only - c#

I have a local DB that I have in an application. When I install it on another machine I get the error
Unable to update database.. .mdf is read only.
I was able to get around it by editing my permissions on the .mdf and log file themselves. I did some research and noticed that I may want to install the database to a shared folder. However, I am not sure how to do that and the answers I did come across did not make a whole lot of sense to be.
//My connection string
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|AssetDatabase.mdf;Integrated Security=True");
Any guidance would be greatly appreciated. I am learning.

Just go to the program files and find the folder of the installed program.
Just right click the .mdf file in the folder and click PROPERTIES.
In PROPERTIES TAB -> SECURITY -> you'll see Group or Usernames.
In that select the User to which u want to give Access to the file.
If for that user the PERMISSION is not set to FULL CONTROL.
TO CHANGE PERMISSIONS -> CLICK EDIT.
Now the Group or Username box will open.
In that Select The User -> Select FULL CONTROL in Permission Box.
Now follow the steps for the log file too. IF Needed.
OR
Just install your application in different folder other than ProgramFile(x86)

The MDF file would be readonly either because the readonly file attribute flag is set, in which case you have to unset it, or another program has the MDF file locked as readonly. Are you running a version of SQL server that is using that file?
I've never seen a connection to the MDF file directly, usually it's done via the server, and the server will manage all the IO for the MDF file.
E.g. a typical connection string for SQL Server:
Database=<dbname>;Server=<servername>;MultipleActiveResultSets=True;Connection Timeout=10;User Id=<username>;Password=<password>;
Additional links:
1) Failed to update .mdf database because the database is read-only (Windows application)
2) Failed to update database because it is read-only
3) Failed to update database "*.mdf" because read only EntityFramework
4) http://www.codeproject.com/Questions/183758/Failed-to-update-mdf-database-because-the-database

First stop the SQLEXPRESS service from local-Services menu and then try to move and connect the database again by attaching database option in SQLEXPRESS. it should work. it works for me. :)

I solved the same problem as follows:
While creating "Setup", I manually added my database files database.mdf and database_log.ldf into the Application Folder file. But after adding these files, make sure that the ReadOnly option in the Properties section is False.
Also "connectionString" I use:
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\database.mdf;Integrated Security=True;Connect Timeout=30"

just remove the .mdf file location to c:\ or desktop or anywhere but not in
%program file directory

if your database file on the C volume,
try to move the .mfd file to D volume

Related

publish a project with local database

I created a Windows form applicatie with a local database (.mdf) to store and retrieve data from.
the database where I connect to is:
C:\ProgramData\project\Database.mdf
when I publish my project and place my database file in that folder on a other pc and try to run it I get the error unable to locate a local database runtime installation
my connection string is:
conn.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=""C:\ProgramData\project\Database.mdf"";Integrated Security=True";
so could somebody help me with this problem?
because everything runs fine on my own pc
Did you include the database as "Application File"? If not do the following (at least this is how I am doing it):
Project -> Properties -> Publish -> Application Files
Here set the values for your .mdf and the xx_log.ldf as follows:
Now still in the Publish tab go on Prerequisites. Here you have to check the following depending on what database you are using.
This will download SQL Server Express for the client who is installing your application.
You will also have to change the connection string to a generic path. I suppose the database lies somewhere inside your project folder /bin I guess, not sure anymore. So adjust your connection string to something like:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True
I therfor recommend using a resource file or app.config
But basically i think your problem is that the pc you are installing on does not have SQL Server installed. So just follow the steps above in Prerequisites. The other steps will enable you to deploy the database to the project folder without moving it to a certain folder manually.
I hope this helps.

how to restore a database if there is not any database to restore to it

i am asking this question because i do not know what to search.
you know there is a database that we restore back up file to it. if database deleted what we can do? for example we developed a program. and we backed up the database info's. after that all files of us such as database and software deleted(not backup file). now if we later want to restore database using backup file and we do not have database(MDF file) what we can do now?
thanks.
You need to create a blank database and restore using the backup file to that database.
Check the Restore a Database Backup or details.
From SQL Management Studio, right-click on the 'databases' node. Pick "Restore database."
Click "device" and then the browse button on the far-right.
Browse for your .BAK file and double-click on it.
Once selected, pull-down on the 'database' under "destination." You should see the database in the backup. Select it.
Change any settings - log/mdf destination, etc. and GO!
This is how we deploy new staging servers from production backups all the time.

"Cannot attach the file" error when deleting a database from the App_Data folder with LocalDb in MVC?

I am using LocalDb and I just want to delete my database.
I was under the impression that due to the way that LocalDb works I would just be able to access the *.mdf and *.ldf files that the local DB instance has created in my App_Data folder (I am using MVC5 by the way).
And that next time I start the application and use it they would just create new files and I would have a new database. But when I delete the files I get the following message...
Cannot attach the file 'c:\users\exitos\documents\visual studio
2013\Projects\xxxxxxxxxxxxxxxxxxxxxx\xxxxxxxxxxxxxxxxxxxxxx\App_Data\aspnet-xxxxxxxxxxxxxxxxxxxxxx-20140118101721.mdf'
as database 'aspnet-xxxxxxxxxxxxxxxxxxxxxx-20140118101721'.
Why? I did a reset to my initial commit using GIT to make sure the entire solution folder was 'box fresh' and I still get the problem. I even stopped the Sql Server Express from running and killed all Sql processes and still the same problem.
Is the .ldf and .mdf file written to the registry or something?
I changed the name of the file in the .config and it worked but I don't want to have to keep doing that. I just want to tear down my database by physically deleting it...
This is not obvious but it is advised that you should not delete the physical .mdf and .log files outside of the SQL Server Object Explorer in Visual Studio or in SQL Server Management Studio.
If this happens you can un-register it by using the object explorer.
Go to Server Explorer > data connections, find the db and delete it from there.
Visual studio will then re-create the db next time without an issue.
I learnt about this from a video by Scott Allen but he's also documented it here.
http://odetocode.com/blogs/scott/archive/2012/08/15/a-troubleshooting-guide-for-entity-framework-connections-amp-migrations.aspx

Automatically install access database when creating setup file in c#

I Have created a c# application which is using access database.
I have deploy the application successfully.
what I want is install the access database automatically in other users computer automatically.
I have tried to change the app.config files connection string and no use..:(
help me
Not sure what you mean, but if your database is part of your solution you can copy it to the output directory:
You have to be more specific. Did you install the application using installer? Copying and pasting?
Maybe these would help:
StackOverflow - "How to install visual studio 2010 setup project with MS Access database on a computer which is not having Office 2010 installed?"
CodeProject - Deploy your Application and Database
MSDN Forums - "How to attach sql database file to creating .exe setup in c#"
Copy the access db to a folder in programdata with the setup. Connect to this db in your code. You don't need a connectionstring in app.config if the user is not allowed to specify the db path.
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
Your setup should be able to deploy to a programdata folder.
If you want to create .exe Setup Project of your Dot Net Application which is using MS Access DATA BASES. then simply follow this steps. Please read this one for a moment before to proceed these steps.Connect with MS Access Data Base in Dot net.
When you are going to create the exe file then your data base connection string should be like this(means there should be no directory in #"Data source, Just direct put the name of your data base, because in .exe file when you add your data base file, then it is in the same directory.
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data source=MyDataBase.accdb";
Right click on your solution file. (like in Solution Explorer "Solution 'MyProject' ")
Select Add -->New Project -->Other Project Types
Select "Setup"
A New project will be added named setup (with a new tab added to
editor as File System )
Now right click on application folder -->select add -->select folder
new folder will be added under application folder * Now Right click
on newly added folder -->select add -->select file * Add File dialog
will be popup
Select your Db file (means from a "Browse" Button there go and select your Access Data Base )
Select Setup project and build.. Now your
installer will have your DB.
You can also install it from there.

Create sql server compact file in appdata folder

I am developing a simple piece of software which uses Entity Framework code first and sql server compact 4. At the moment this setup works. Entity framework creates the sql server compact file if it doesn't yet exists. The path to the database is defined from within a connectionstring which is stored inside the app.config file. It is build up like this:
<connectionStrings>
<add name="DataContext"
connectionString="Data source=Database.sdf;"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
However, I want to place the database in a folder within the current user's Application Data folder (the C:\Users\User\AppData\Roaming folder on my win7 machine). I've tried setting the Data source of the connectionstring to something like %APPDATA%\Database.sdf, but this doesn't work, I get an "Illegal characters in path" exception.
I want to stick with the connectionstring method, because I'd like to use a different database for my unit tests than with my actual application. This way it is easy to modify the database by placing an app.config file in the root of the project.
Can someone steer me in the right direction?
Use below:
AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
<connectionStrings>
<add name="DataContext"
connectionString="Data source=|DataDirectory|Database.sdf;"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
connectionString="Data source=Database.sdf;"
This tells your app to look for Database.sdf in your app’s current working directory; which could be anywhere and may not be writeable. You need to look at a location you specify:
connectionString="Data source=|DataDirectory|Database.sdf;"
ADO.NET looks for pipe characters in connection strings and expands them to the value of the property of that name in the application’s domain. So what’s the value of the DataDirectory property? It’s supposed to be set by whatever deployed your application:
.MSI installers set it to the app installation folder. If you allow the user to choose the installation folder, they choose the DataDirectory as well. This is why you should always use |DataDirectory| and never a hard-coded path.
ClickOnce defines a special data folder in your project.
Web apps use the App_Data folder.
The Visual Studio debugger uses the debug folder.
Any Visual Studio files in your project with a “copy to output directory” property will be copied to DataDirectory. In most cases DataDirectory will be a read-only folder. This is fine if your data is read-only, but if you want to write to it you will have to copy your data to a writeable location. Probably the best place is Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData)). There are several ways of doing this:
If you are creating an empty new data file, just use your API’s standard CREATE DATABASE or new SqlCeConnection() or whatever.
If you want to start with a pre-populated seed or starter database, include the seed database in your project . In your application startup, check if the database exists in the SpecialFolder.ApplicationData folder and, if not, copy it there.
If you search the web for sample code on creating local database you will run across a lot of bad advice. Do not do the following:
new SqlCeConnection(#"Data source=c:\users\me\myApp\Database.sdf;"); // Do NOT do this!
I hope I don’t have to explain why hard-coding the path to your data is wrong; but be aware that unless you specify a full path in your connection string, the path is relative to your current working directory.
using (var conn = new SqlCeConnection(#"Data source=|DataDirectory|Database.sdf;"))
{
conn.Open();
// No No No! This throws an Access Exception for Standard users,
// and gets deleted when you repair the app!
var cmd = conn.CreateCommand("INSERT INTO Table (column1, column2) VALUES (#p1, #p2)");
...
}
Do not try to modify the data in DataDirectory. Not only is this directory not always modifiable by users, it is owned by the installer not by the user. Repairing or uninstalling the application will delete all the user’s data; users don’t like that. Instead, copy the installed data to a folder writable by the user and make all changes to the copy.
AppDomain.CurrentDomain.SetData("DataDirectory",
// Wrong, this overwrites where the user installed your app!
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
Do not change the value of DataDirectory in your code, it is set by the installer and if you change it you won’t know where your data was installed. If you are creating an empty database, just open it in your final location. If you are going to make a copy, open the installed database, save it to the user’s location, close the installed database, and open the copy.
I also discourage saving data to Environment.SpecialFolder.CommonApplicationData. This may not be writable by users, and unless there is a very very good reason all users must be allowed to change other users’ data, each user should have their own database.

Categories

Resources