Unable to copy file "xxx.mdf" in Visual studio 2010 - c#

I have a project in visual studio 2010 with a database in sql 2008 R2..
I convert this project with crystal report . But when i want run this project this errors happened .
Error 13 Unable to copy file "XXX.mdf" to "bin\x86\Release\XX.mdf". The process cannot access the file 'XX.mdf' because it is being used by another process
Error 25 Unable to copy file "C:\madrase\madrase\entekhab_vahed\entekhab_vahed_log.ldf" to "bin\x86\Release\entekhab_vahed_log.ldf". The process cannot access the file 'C:\madrase\madrase\entekhab_vahed\entekhab_vahed_log.ldf' because it is being used by another process.
Error 12 Could not copy "C:\madrase\madrase\entekhab_vahed\entekhab_vahed.mdf" to "bin\x86\Release\entekhab_vahed.mdf". Exceeded retry count of 10. Failed. entekhab_vahed
i don't know how fix it .

Make sure your database is not open by Visual Studio. If so Disconnect it using Server Explorer in Visual Studio.
Make sure you close the client. There must be no active client using your project
If it still happens, try to run Visual Studio "As Administrator"
SQL Server .mdf file being used by another process

You probably already solved this by the date, but his is my answer for future searches:
Normally the error will tell you the PID of the process who is using the file, you can end the process, but is not recommended, maybe there is other things using him.
This is happening because you didn't close the connection after the end of your code.
Always use
try
{
//do your thing
}
catch (Exception e)
{
//close connection
}
Try to use
using(...context)
{
//do your thing
}
With this the connection will be closed at the end of stack.
You can implement an IDisposable too or add "Connect Timeout=10" to your connection string.

Related

Compact and repair Access DataBase in run time using C# without Access installed

I write a program that should run on a lot of machines
I did not installed Access in the machines But I have an access database using on them
When I write and delete data from this Access databases its size grow up so every few days I have to compacts them and to shrink the size
This is the code I using
public void Compacting()
{
try
{
Microsoft.Office.Interop.Access.Application application = new Microsoft.Office.Interop.Access.Application();
string dbName = "";
try
{
dbName = ConfigurationManager.ConnectionStrings["LocalPulserDB"].ConnectionString.Split("Data Source=").Last().Split(";").First();
}
catch (Exception ex)
{
string localDbError = "DataBase location is incorrect ";
System.Windows.MessageBox.Show(localDbError);
Environment.Exit(1);
}
CompactAndRepair(dbName, application);
}
catch (Exception ex)
{
try
{
LocalPulserDBManagerInstance.WriteLog(ex.StackTrace, ex.Message);
}
catch (Exception)
{
}
}
}
private void CompactAndRepair(string accessFile, Microsoft.Office.Interop.Access.Application app)
{
string tempFile = Path.Combine(Path.GetDirectoryName(accessFile),
Path.GetRandomFileName() + Path.GetExtension(accessFile));
app.CompactRepair(accessFile, tempFile, true);
app.Visible = false;
FileInfo temp = new FileInfo(tempFile);
temp.CopyTo(accessFile, true);
temp.Delete();
}
But I got the next error :
{"Retrieving the COM class factory for component with CLSID {73A4C9C1-D68D-11D0-98BF-00A0C90DC8D9} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE))."}
What can I do?
Interop requires Office to be installed on the machine the code is running on, I suspect you won't be able to utilize that method for performing the compact and repair.
https://social.msdn.microsoft.com/Forums/en-US/973ce94f-5235-4be9-a2b1-51ba7d35e1f3/installing-office-primary-interop-assemblies-without-actually-installing-office?forum=innovateonoffice
You may however be able to utilize this standalone tool, "Jet compact utility":
https://learn.microsoft.com/en-us/office/troubleshoot/access/jet-compact-utility-download
You do not need nor even want to create a whole instance of access to just compact. (or even use + pull data from the tables.
Set a reference to the ACE database engine. That way you can pull + use data, and not have to automatic (create) a rather heavy application object like Access. And if you do create a WHOLE instance of Access, then things like VBA code and startup forms run (not only is a that bad since now you have a hidden UI - but you can't answer prompts, and worse that startup code may will have launched a form which in term will open a table, and then you can't compact until such time all tables are closed.
IN vb.net code, this will compact:
Dim ACEEngine As New Microsoft.Office.Interop.Access.Dao.DBEngine
Dim strDatabase As String = "c:\test\test44.accdb"
' you always compact to a copy - you cannot compact "over" the existing database
Dim strTempDB As String = "c:\test\temp.accdb"
Debug.Print("starting compact")
Try
ACEEngine.CompactDatabase(strDatabase, strTempDB)
Debug.Print("compact done")
Catch ex As Exception
Debug.Print(Err.Description)
End Try
Note that:
You can check the error code as per above, since if ANY other users are in the database, then the compact will NOT occur.
The above output if a someone else has the database open?
starting compact
Exception thrown: 'System.Runtime.InteropServices.COMException' in ACETest.exe
You attempted to open a database that is already opened by user 'Admin' on machine
'ALBERTKALLAL-PC'. Try again when the database is available.
So, catch the error. As above shows, you need a interop reference to
C:\Program Files (x86)\Microsoft Visual Studio 12.0\
Visual Studio Tools for Office\PIA\Office14\
Microsoft.Office.interop.access.dao.dll
Just check that err.Number is 0. If the compact occurred, then you can delete or better yet rename the original database, and then rename the "temp" database back to the original name. (A compact + repair from the Access UI does this behind the scenes and actually never overwrites the original file during the compact process as it might fail or not work). You could attempt to check for existing .ldb file (a lock file) before you attempt the compact, but the compact process checks + requires that you have 100% exclusive use of the file, and if the compact can't get exclusive use of the file, then a error message is spit out as per above.
So, just add the assembly reference to your project. You should also force your .net project to x86, and not leave it to "ANY CPU".
the above will work WITHOUT Access having been installed. However, you will need to have the JET or ACE data engine installed. The JET engine is installed on all copies of windows by default - but will ONLY work with mdb files. If you need to compact and use a accDB file, then you will have to install the ACE database engine - but it is a FAR smaller footprint and install then is a whole copy of Access or the run time (both are about the same size and are quite large. As noted, with above, then you don't require Access to have been installed on the computer.
Edit
You can find + install a version of ACE from here:
https://www.microsoft.com/en-us/download/details.aspx?id=54920
Note in above, you are given two choices. (x32 or x64 - so you have to install the version you want. This also suggests you need two versions of your .net code OR YOU CAN find a shortcut way to launch "any" cpu to start as x32 or x64 - HOW you start your .net project will determine if it is running as x32 or x64 if you going to choose "any cpu" as opposed to forcing the .net project (and providing two versions of the project as I have done in the sample link below).
I have a working .net (tiny) .exe file from here that lets you run as x32, or x64, and thus you can quick check which version of ACE you have installed.
link:
https://onedrive.live.com/embed?cid=B18A57CB5F6AF0FA&resid=B18A57CB5F6AF0FA%21101313&authkey=AB-I3mHVZhLmd2Q

SQL Server network interfaces error 52- Unable to locate a database at runtime installation

I am creating a POS system in Windows Forms (C#) in which I use a SQL Server database file (.mdf) to store items (completely offline). When I install the application on my computer, it works fine, but when I install it on my clients PC, an error happens:
(provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation"
I read somewhere that the problem is caused due to the fact that the connection string of the database of my client's PC is different. I tried to add the connection string dynamically on runtime but again it only worked on my computer.
Another reason that might be causing the problem is that I used 'server-based database' since local database option isn't available in Visual Studio 2017 for some reason.
Another solution I looked up stated that I should install SQL Server Express on my client's PC. That also failed (maybe I have to set it up in a way or something).
I also tried adding the database.mdf and database_log files in the setup folder.
Lastly I tried installing 3rd party installers (Advanced installers 15.8 and InstallShield Wizard in VS 2015) which also failed.
(I have provided the code for the connection of database taking place and the connection string)
public void ConnectToDB()
{
DBConnection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\SAIM NASSER\Desktop\app layer\data layer\Database1.mdf; Integrated Security = True");
DBConnection.Open();
ResultSet = new DataSet();
}
If I understand you correct, you want to use LocalDB
That means using Sql Server without installing a full sql server, but just the localdb part from sql server express.
For this to work you need to install the LocalDB Driver, which can be found here
https://www.microsoft.com/en-us/download/details.aspx?id=29062
You need only the ENU\x64\SqlLocalDB.MSI
This is the only thing you need to install in your clients computer, I believe it can also be installed silent, you have to research a bit for that.
And yes, you also should change the connection string on the clients computer, you need to alter it so it points to the MDF file on the clients computer, because that location will probably be different then on your computer
EDIT
To get the connection string working, you can try this
On the clients computer, create a text file and rename the extension to .udl
So for example you have a file test.udl
Now from explorer, double click it, this will open the datalink editor.
From here you can enter/choose different settings, and click on the test connection button.
Once you get a working connection, save it, and open this file with notepad.
Inside you will find the working connection string
Hope this helps

MVC 4 Entity Framework Cannot Connect to Dynamically Created Database from IIS Server

After I hosted my apps in my localhost IIS, suddenly the system gives me error:
Cannot open database "AlvinCMS" requested by the login. The login
failed. Login failed for user 'NT AUTHORITY\SYSTEM'.
The database AlvinCMS is created at runtime. The system has no problem when in debug mode.
Here is my global.asax:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//Check And Init Database
Alvin_CMS.App_Start.DatabaseConfig.Initialize();
......
This is my initialization:
public static void Initialize()
{
Alvin_CMS.Models.AlvinCMSMigrationDBContext migrationDB = new Models.AlvinCMSMigrationDBContext();
try
{
if (!migrationDB.Database.Exists())
{
migrationDB.Database.Initialize(false); //THIS CREATES DATABASE
AlvinCMSExtension.Models.AccountDBContext accountDB = new AlvinCMSExtension.Models.AccountDBContext();
accountDB.Database.Initialize(false);
SetDefaultValue(migrationDB);
}
migrationDB.Database.Initialize(false);
}
catch (Exception e)
{
migrationDB.Database.Delete();
AlvinCMSExtension.Helper.Log(e);
}
}
Here is my context:
public AlvinCMSMigrationDBContext()
: base("DefaultConnection")
{
Database.SetInitializer<AlvinCMSMigrationDBContext>(new CreateDatabaseIfNotExists<AlvinCMSMigrationDBContext>());
}
I set the apps pool to use LocalSystem and I have IntegratedSecurity=true in my connection string. How can I fix this error?
NOTE: If I run this on visual studio development server, it runs fine with no error. Also if I use localDB and run it on IIS Express, it runs fine too. The Problem only exist if I use IIS, even when I debug the program from Visual Studio Local IIS Web Server, then the error is produced
UPDATE
After 4 hours of debugging, finally I know what is wrong. The error exists because the database is not exist. I have another database error that causes the code to enter Exception, so the database is not being created.
The problematic database has this connection string:
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\Public\Documents\Projects\Alvin CMS Project\Alvin CMS\Alvin CMS\App_Data\db\backup\AlvinCMS_Default.mdf";Initial Catalog=AlvinCMS_Default;Integrated Security=True;MultipleActiveResultSets=True
When hosted on IIS, the program cannot attach the database. It causes this error:
{"Unable to open the physical file \"C:\Users\Public\Documents\Projects\Alvin CMS Project\Alvin CMS\Alvin CMS\App_Data\db\backup\AlvinCMS_Default.mdf\". Operating system error 5: \"5(Access is denied.)\".\r\nCannot attach the file 'C:\Users\Public\Documents\Projects\Alvin CMS Project\Alvin CMS\Alvin CMS\App_Data\db\backup\AlvinCMS_Default.mdf' as database 'AlvinCMS_Default'."}
But when I use visual development server, it works fine. So the new question arises, how can I safely attach the database without causing errors when hosted on IIS server?
You can check with following things:
Add Integrated Security=SSPI in your Web.Config
Allow NT AUTHORITY/SYSTEM to server Role as sysadmin.
Goto security > Logins > Select NT AUTHORITY\SYSTEM
Give it the necessary permissions it needs for your app.
Like stated above the updated question, actually there was never be any problem with the database connection. What actually happened was there is an access denied when I tried to access another database, which made the code entered the Exception and never touch the database creation. That is why I cannot login to access the database, because the database was never created.
Then I need to fix the another database which caused the fault. The problem was I cannot attach the database. The access was keep being denied. After I have done some research **I found that I was using LocalDB before I use SQLEXPRESS. I deleted the database from LocalDB, but apparently the localDB is still referencing the database, that is why I got my access denied because the database was still being used by LocalDB. So what I did was to run:
sqllocaldb.exe stop v11.0 from cmd (you can run it from command line in visual studio as well).
Then after that, I can finally attached my database with no problem.

Error while starting Storage Emulator on windows azure

I'm getting the error below while starting the storage emulator. By mistake I deleted the mdf and log files in users/admin folder. It's holding reference someplace and not allowing me to create the DB again. Please help me.
Added reservation for 127.0.0.1:10000/ in user account RaviBorra-PC\Ravi Borra.
Added reservation for 127.0.0.1:10001/ in user account RaviBorra-PC\Ravi Borra.
Added reservation for 127.0.0.1:10002/ in user account RaviBorra-PC\Ravi Borra.
Found SQL Instance (localdb)\v11.0.
Creating database DevelopmentStorageDb201206 on SQL instance '(localdb)\v11.0'.
Cannot create database 'DevelopmentStorageDb201206' : Database 'DevelopmentStorageDb201206' already exists. Choose a different database name..
One or more initialization actions have failed. Resolve these errors before attempting to run the storage emulator again. Please refer to http://go.microsoft.com/fwlink/?LinkID=248088 for more details.
Thank you,
Ravi Krishna B.
Do these steps:
Open cmd.exe (Command Prompt)
Write this:
SqlLocalDb stop "v11.0"
SqlLocalDb delete "v11.0"
and press Enter
Note that "v11.0" is MyInstance.
For more details, visit this link.
This problem may occur if you delete the data file C:\Users\<Username>\DevelopmentStorageDb201206.mdf but do not delete the corresponding database on the LocalDB server instance. One possible solution is:
Connect to the (localdb)\v11.0 instance from SQL Server Management Studio.
Delete the DevelopmentStorageDb201206 database. There will be the error message that the database deletion ended with an error. Ignore this message and refresh the database list manually.
Now you can start the Azure Storage Emulator.
This is not a problem related with Azure components rather LocalDB instance is reporting back to Azure request that DB still exist. Check LocalDB instances in your machine using "sqllocaldb i" first and the delete the instance using "sqllocaldb d 'instance_name'". I could not test it in my machine but this may unblock you if localdb instance is blocking you.
In Windows Azure SDK 1.7, Windows Azure Storage Emulator uses LocalDB instance specific configuration at following location:
%LocalAppData%\DevelopmentStorage\DevelopmentStorage.201206.config
And based on that you will see that v11.0 instance is Windows Azure Storage Emulator specific so verify if that is running and deleting it will let DSInit to create the DB again in LocalDB.
If you have Sql Express installed on your local box then (localdb)\v11.0 is most likely not your local Sql instance. It is more likely {MyComputerName}\SQLEXPRESS.
Going to:
C:\Users\<yourloginname>\AppData\Local\DevelopmentStorage\DevelopmentStorage.201206.config
And changing:
<SQLInstance>(localdb)\v11.0</SQLInstance>
To:
<SQLInstance>{MyComputerName}\SQLEXPRESS</SQLInstance>
solved this error for me.
I hope this helps..
If you already tried and failed perform:
SQLLocalDB stop v11.0
SQLLocalDB delete v11.0
Delete all the files in C:\Users\<accontname>\WAStorageEmulatorDb* (usually one mdf and one ldf)
Create a new account (I called it Azure, with administrative rights)
Run again the installation
Installation completed!
For me this works... I had tried to format the PC before use this way. I supposte my problem is related to my username that contains "invalid" characters like Name 'NickName' Surname while the "Azure" account seems to be OK for him.
I figure it out 'cause somewhere in the log I have a property destination path set to "C:\Users\Name$_" that is far away for the path of my user account folder.
After that you can go on CMD.exe and prompt:
control userpasswords2
From the control you can delete the Azure login without delete the file folders!
Hope it helps!
I simply deleted all the mdf's and ldf's in C:\Users\accountname\ that started with DevelopmentStorage... or WAStorageEmulator.
Re-ran the install and it worked.
This can also be caused by the folder not existing for localDB. It looks like Visual Studio / Azure will not automatically create containing folders. I just copied the path from the error code into explorer and created the directory up to the .MDF file.
In visual studio go to Tools -> Options -> Database Tools-> Data connections and change a localdb instance name from v11.0 to some other name.
I did have SQL Express installed, as Brian Ogden suggested in his answer, but I wanted to try & point Azure Storage Emulator to my SQL Express instance without modifying configuration files.
I did this by running the initialization process for Storage Emulator & passing my server\instance details for SQL Express using the available switches. Below example of the command I executed (from an elevated command prompt):
AzureStorageEmulator.exe init -server MY-PC-NAME -instance MYSQLINST
This created the database successfully (in my SQL Express instance) & got my Storage Emulator working.
I am using a named instance, but I'm thinking this same approach can be used for default instances by omitting the -instance switch.

DB Backup runs in Debug but not Release

I have a small c# wpf app for doing some simple calculations running off a Sql Express 2008 R2 db, and in the setup section is a backup button that runs the code
using (DTZDataContext db = new DTZDataContext())
{
db.ExecuteCommand(string.Format("BACKUP DATABASE DtzDb TO DISK = '{0}'", filename));
}
The connection string I am using is
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\DTZ.mdf;Integrated Security=True;User Instance=True;Database=DtzDb
I have confirmed there are no other open db connections at this point in the application and the backup runs fine in debug, but once I compile for release (running from VS or as standalone) I get the error:
Operating system error 32 “32(failed to retrieve text for this error Reason 15105)” BACKUP DATABASE is terminating abnormally.
How can I fix this, preferably without having to install Sql Management Studio on each machine and attaching the DB? What is the recommended way of doing backups? Why does it work in Debug but not Release.
Many Thanks
My bad... It turns out VS had changed the DataContext connection string to DTZConnectionString1 and made another settings file. Now I am using the correct connection string it is working fine.
No idea why the incorrect one worked in debug but not release.

Categories

Resources