How to create clone of database programatically - c#

I want to create clone of database programatically. My requirement is, I have a default master template of database, I want to create a new database when my application will execute and this new database will be copy of existing master database, just its name will be changed.

One option is to create a backup of the master database and restore it under a different name using a script:
RESTORE DATABASE [CopyOfMaster] FROM
DISK = N'C:\Temp\Master.bak'
WITH FILE = 1,
MOVE N'Master' TO N'C:\Temp\copy.mdf',
MOVE N'Master_log' TO N'C:\Temp\copy_log.ldf',
NOUNLOAD
GO
Explanation of parameters:
DISK - path and file of your backup file
MOVE - you need one line for each file group in the original database. You specify new file name and path for each file group
More reading on MSDN

You need to script your master template database and save the script to a file. Use SQL Server Management Studio, right click on your master template database and select 'script database as'. You will have to change the database name in the script to some identifier which you can perform a string replace to change the name at runtime.
In your code you can load the script file and execute to create your database with a different name. You can make use of the SqlCommand to execute the loaded script (http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx)
You can also make use of the command line 'sqlcmd' utility or SQL Server Management Object(SMO). Although I have not explored any of those options.

Related

Database seems to update during execution, then changes disappear

I'm trying to create a recipe book in C# where I can easily search for what recipes I can make with what ingredients are on hand. This is mostly a learning exercise for me at this point.
Right now, I'm trying to test updating the tables in my database. It seems to work during one instance of the code, but the changes are gone the next time I run it.
So I have a table in my database like this:
I create a small list of example recipes from a json file
var js = new JsonImporter() { SourceDirectory = Path.Combine(Directory.GetCurrentDirectory(), "test_data") };
List<Recipe> recipes = js.ImportData<Recipe>("test_recipes.json");
Connect to my table and InsertAllOnSubmit:
DataContext db = new DataContext(connectionString);
Table<Recipe> db_recipes = db.GetTable<Recipe>();
db_recipes.InsertAllOnSubmit(recipes);
Show how many entries are in the table, submit the changes, refresh the number of entries, and show how many are in the table again:
MessageBox.Show(db_recipes.Count().ToString());
db.SubmitChanges();
db_recipes = db.GetTable<Recipe>();
MessageBox.Show(db_recipes.Count().ToString());
The first messagebox shows 1 (I have one row in the table that I entered manually via the Server Explorer), and the second message says 3. This is what I expect, since I am adding 2 entries.
However, once I run the code again, the message boxes again say 1 and 3, instead of always incrementing by 2. So it seems to me like the database is not saving. Can anybody help me figure out what's going on here?
You never said what database you use but I think it highly likely to be file based, either Access or SQL Server (in "attach the mdf file at runtime" mode)
Often with file based databases we end up setting them up so that there is a version of the db file in the project folder alongside the source code. This is copied to the output directory every time the project is built and the output directory contains the exe and the db. The exe modifies the db in the output folder. The next time it is built / run the blank db from the source code folder is copied over the top of the db that was modified in the output folder
Run your project, get the exe to modify the db, stop the exe and then search the whole project folder (using windows file search) or even the whole hard disk for the name of your db file. You'll figure out what's going on by looking at the file modified dates..
If it is a file based db thing, find the db in CS Solution explorer, click it and set its "copy to output" setting to "copy if newer" so that it only wipes the output db if eg the scheme has changed

Establish connection with downloaded database file [WP8]

I use a local pre-populated database file (added in the project folder) in order to access the needed data. In order to make it work with SQLiteAsyncConnection, one should change the attribute "Build Action" (to "Content") in the properties of the file.
That change is easy when it's a local file added in the IDE.
What about a downloaded database file?
I downloaded a new version of my database and stored it in the IsolatedStorage. When I try to query this db, I get an "SQLiteException" error -the same that I was getting in case I had forgotten to change the above mentioned property.
Any suggestion on that?

Release plan for my application on other machine by using .mdf file

I am using SQL server 2008 R2 and VS2010. I made simple application by using this tools. I attach database as .mdf in my application and deploy that application on other machine its works fine. Now if I plan for new release of my app which some extended features, I can upload Code by DLL, But problem is updating .mdf file, to handle this I am exporting database into .xls sheets (Application have one utility to backup database) and then import into SQL Server to create new .mdf file. Someone have better solution on this? Can I open old version of .mdf file in SQL Server(Third party software) and Execute DML/DDL script on it to make latest code and database compatible ? May I keep .sql file in one of my project code and execute it by some utility..? Any Class in C# which can handle this..?
I did not get your query completely. Do you want to upgrade the DB through the application?
You can of course run .sql files through your application, but I'm not sure it would help you change the Database configuration.
Alternatively, if you already have the updated .mdf file and the database name is same, then you can follow the following steps.
1. Detach the database by SSMS in the third party environment through SSMS.
2. Replace the .mdf, .ldf and .ndf (if any) in the disk.
3. Attach the updated .mdf file.
This will get the new Object definitions as well as data.
As far as I'm aware, there is no process for merging .mdf files, because the SQL Server might not be able to identify the similar objects properly as sys tables may be different, and also would not know which data to keep in the final data base, in case the table structure, constraints or data conflicts occur.
However, looking at your requirement, the best way I can suggest is,
1. Generate the Alter scripts for the tables modified (By right clicking on the object name and using Script Table As.. option). Of course, I assume you have the list of objects modified and the modifications.
2. Connect the two DB servers over network and write an SSIS package or Import data from the old DB to the new one for the tables you want.
Hope this helps.

C#: restore SQL Server DB from a backup inside an embedded resource

I have a file that contains a SQL Server 2012 database backup. I am using this file with a C# WinForms application, that creates a database, restores the backup into it, and then performs some more functions.
I don't want to just add this backup file to my application, because this is a security issue. I was thinking I should add the backup as an embedded resource, and then save it to a temp file, restore from it and delete it.
Is there a better way to do this? Is there a way to access an embedded resource directly through a file path that I can pass to SQL server to use in the RESTORE DATABASE command?
SQL Server has no idea whatsoever about how to restore a database from something living inside an executable. Given that you state that you've considered it be able to be an embedded resource, I am going to assume that it's not a "last known good" backup, but more a "default" backup.
If I am correct in this thinking, then you're basically saying you have a default set-up. If that is the case, you don't need a backup at all, your code just needs to be able to create a database and populate it with certain things to "become" that default state. By embedding a backup as a resource, you are (in my mind) stating that the structure and data is well known, so why go down the RESTORE DATABASE path at all?

Create Databases in a C# application

What is the best way to create databases on C# application, I mean by a click of a button, it will create a database with a different name but the same model?
Currently, I script TSQL onto a C# application, so when I click a button, a new database will be created with the name I defined, it works well, however, it is extremely difficult to maintain, is there a better way to create database on C#?
Regards
You can use SMO to create databases. See MSDN sample.
One way is to just have a copy of your database file (mdf) available for pushing onto a new server. This similiar to what microsoft does with it's Model database. Whenever you create a new database it starts by making a copy of that one.
Your button click could copy the database file to the desired location, rename it as appropriate, then attach it to the running sql server instance. Whenever you need to update the database with a new schema, just copy the mdf to your deployment directory.
Sql Server 2008 Management Studio can generate SQL script for database generation. Save script in text file and later spool it to RDBMS and create database.
This is not too hard to maintain.
To generate script in SqlServer 2008 Management Studio: right click on database -> Tasks -> Create Scripts, click few times and save to file.

Categories