How to deploy a database programatically with C# - c#

I have a database project in my solution and the requirement is simple (not so sure about the implementation).
Is there a way to deploy the database project programatically?
PS: I don't mean attach an MDF file. I mean deploy the database to a SQL Server instance.

You can add the script for create the database as an "Embedded Resource" then execute it when needed with the standard ExecuteNonQuery(...). But you probably need to upgrade it in the future so the idea is, a part the first drop, have some table somewhere keeping the schema version, then have multiple embedded resource contatining script to jump to one version to the next one. When the service start check the version against the expected one, if not the same launch the needed script(s) to reach the current version.

You can use plain sql commands to achieve this.
http://msdn.microsoft.com/en-us/library/49b92ztk(v=vs.80).aspx
http://www.codeproject.com/Articles/16231/Deploy-your-Application-and-Database
Best regards

Create the database SQL however you like and include it in your project. Then simply execute the SQL script against the server.
I use this when I include SQLite databases in my project.

Related

C# application using a Local database with stored procedures

I am trying to develop a simple C# application which use a database. I am currently using MS Server 2008, but I found a portability issue since running the application on different computers would require MS Server to be installed. Also, my database makes use of stored procedures.
What other database types I can use in order to overcome this problem (n.b. it must use stored procedures)?
If I am to use MS Server 2008, assuming it is installed on every pc, how can I copy my .mdf file in order to be accessible? (i.e. install it on application load ?)
UPDATE
From this website, I found the following connection string :
Attach a database file on connect to a local SQL Server Express instance ...
Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
I presume that this will copy the .mdf file from my folder.
Hence, I am using the following connection string but to no success ...
Server=.\SQLExpress;AttachDbFilename=...... database path.... ;Database=TrieDB.mdf; Trusted_Connection=Yes;
Directory lookup for the file "... database path... " failed with the operating system error 5(Access is denied.).
Cannot attach the file '... database path...' as database 'TrieDB.mdf'
Most "certified" database engines requires you to actually install the engine.
Most "certified" database engines enable the use of stored procedures.
In order to have the .mdf file on more machines you can simply copy it and afterwards use the sql management studio to attach the file to the engine, but that is not an ideal solution if you planning to distribute your application in many places, the ideal solution will be to create an installation package and fix that it is automaticlly being done from the installation and undone when you uninstall.
imho: You insist on stored procedure with a de-centeralized solution - do notice that this is a rather rare tactic - it has the smell of a wrong path..
But I can't be sure unless you provide some more information.
There are really two general designs to do something like what you're describing. Either have a centralized database that all copies of the application (and/or multiple applications) access, or create an installation package complete with the database (which is generally only accessed by a single application).
Personally, if you don't want to, or can't, use a centralized database solution, I would suggest changing your philosophy about stored procedures and looking into SQL Server Compact. I found this article discussing the reasons why SQL Server Compact doesn't have sprocs, which I think will be useful to you, even if you decide you really need them.
That said, if you need to install a database with your app, you can create a setup package within Visual Studio, of you could also look into using WiX.
You can detach the database, copy over and attach the mdf file on the destination database.

publishing the database with the project

How can I publish the application database along with it?
I'm using Visual Studio 2008 with C# language.
The database has the log-in information needed in order to go in the MdiParent and do tasks there. The same database is where employee records would also be saved...
I'm currently developing an employee information system.
The easiest option it to use a file based database and distribute it with your application, unless you need the data to be shared between all users of the applications as it changes.
SqlLite and SQL Server CE are both file based.
What is your db engine? For MySQL, I use the utility mysqldump. You then can use the source command in a scripted installer to deploy your db from the dump file.
With SQLSERVER, I use the Import/Export tool that comes with SQLSERVER to script out the db with any data that I want to have deployed with the database. I then run the script on the db in my installer.
You have several options. The question is, what are you using for an installer? NSIS, Visual Studio Setup Projects? etc... How you answer that will determine the best approach for how to deploy your database.
You can also do as #oded recommends though I have never done this except for with basic ASP.NET sites and the sqlexpress db that come with the VS project. Usually, I find that whether or not it is a good idea to use the file just depends on your complexity.

How should I generate Database table on a fresh application install?

I've been working on a CMS based in ASP.NET MVC2 using a poco based linq-to-sql repository that is connected to a SQL 2008 database.
I'm nearing completion on the CMS and now I'm thinking about deployment. Ideally, I would like the install process to be something like this:
Copy CMS solution to server location
Create empty database
Change db connection string in web.config to new database
Run script to create db tables (including relationships, constraints, and default data).
I'm not sure where to start with this kind of project. I have limited experience working with Stored Procedures. If it's possible to do this progmatically in C# that would be preferable because it would be easier for me to work with.
Any thoughts on where I should start with this?
Edit - New thoughts
I wonder how difficult it would be to just have a database file (mdf?) that could just be renamed and copied to the sql server. Is that even possible?
I would suggest scripting out the creation of your new database and including it as a step in your application install.
You can let SQL Enterprise manager do a lot of the work for you to generate the script too. If you are using enterprise manager just right click your database and select:
Tasks -> Generate Scripts
In that wizard select your database and the "Script all objects in selected database". That will end up generating a create script for your entire dB.
You can then take that script file and include it as a resource in your setup program, and run it during setup to create out your full dB.
A good thing to think about if you are going this route is Type data. You may want to include another script step that will populate your type data as the 1st script will only generate your dB, tables, and procs.
The two ways I can think of doing this off the top of my head are:
1) Web Setup projects - Similar to this post here and add your own custom actions
2) Make it so the first time your application runs it searches for a DB and if one is not found it gives you the option to add the DB/Connection String.
Both of these can be done in C#. You won't be using Stored Procedures until you have a DB setup because that is where the SPROCS reside.
Embedding the database is probably your best bet. You can use an .mdb, or SQLite or similiar. If your using .mdb, just create a template .mdb, then make it a resource of the project. Then you can copy it to the destination and modify it from there.
I would use SQLite, as its open source, and then you don't have to mess with changing the connection string because you'll just be using the program's install directory to store it.

I need to create the same database on many server instances

SQL Server 2008, Visual Studio 08 and C#
The task is to create the same database on multiple servers. If it were only two or three tables I would have done it manually but there are more than 50 tables in the database..
So I thought why not create a backup and restore the backup file wherever needed
error
the file is in use! ( although the backup is not in use, the error is saying that the actual db is in use! YES IT IS, i cannot close the server each time i want to restore the backup on other servers!)
So what should I do, please give your ideas
And also note
Whatever you say should be achievable using SMO objects also
thank you
[REVISED - I need to learn to read better]
I'm not certain about SMO Objects, but given that SMO can work like other SQL Server functionality, what we do for our project is to use a Database Project that deploys to our servers automatically. This probably requires Database Edition (VS 2008) or higher...premium in 2010. If you have that, it's definitely a nice option to create a DB project. Then, you just set it up to do a schema compare (and you might be able to do a data compare as well if you need that...?) during deployment. Auto-deployment is harder to setup initially, but once it's setup, you're good to go with single click deployments...we use TFS to deploy right now, but I hear good things about TeamCity:
http://www.jetbrains.com/teamcity/
Kevin
Use
usp_killDBConnections #DBName=''DbName''
before you run restore operation. The command will kill all DB connection before Restore, which is important during restoration.
Prior to running the restore, you can run the stored procedure 'sp_who2' and it will list the current connections to the database. If you are going to overwrite the DB anyways, for each of those connections you can issue a 'kill ' to forceably close the connections.
I also recall there being some "close all existing connections" option when using the restore GUI in Sql management studio.

How to install and setup a database with .NET?

I am currently working on a project that include the use of SQLServer. I would like to know what strategy I should use when I install the software to build the database? I need to set up the tables, the stored procedures and the users.
Does my software need to make a check on start up to see if the database exist and then if it doesn't, create it up?
Is there any way that I could automate this when I install SQLServer?
Thank you.
EDIT
Ok right now I have plenty of nice solution, but I am really looking for a solution (free or open source would be awesome) that would allow me to deploy a new application that needs SQLServer to be freshly installed and setuped to the needs of the software.
RedGate software offers SQL Packager which gives you option to produce a script/.exe to deploy whole db including everything (stored procedures, tables etc) from one single .exe. If you can afford it and want to have easy way to do it (without having to do it yourself) it's the way to go ;-)
Easy roll-out of database updates across your client base
Script and compress your schema and data accurately and quickly
Package any pre-existing SQL script as a .exe, or launch as a C# project
Simplify deployments and updates for SQL Server 2000, 2005 and 2008
You could use migration framework like Migrator.Net, then you could run the migrations every time your application starts. The good thing about this approach is that you can update your database when you release a new version of your software.
Go take a look at their Getting started page. This might clear up the concept.
I have succesfully used this approach to solve the problem you are confronted with.
You do all of that with the SQL scripts. And then your installation program runs them against the customer's SQL Server.
You can write a T-SQL script that only creates objects when they do not exist. For a database:
if db_id('dbname') is null
create database dbname
For a stored procedure (see MSDN for a list of object types):
if object_id('spname', 'P') is null
exec ('create procedure dbo.spname as select 1')
go
alter procedure dbo.spname
as
<procedure definition>
The good thing about such scripts is that running them multiple times doesn't create a problem- all the objects will already exist, so the script won't do anything a second time.
Setting up the server is pretty straight forward if you're using MS SQL Server. As for creating the database and tables, you generally only do this once. The whole point of a database is that the data is persistent, so if there's a chance that the database won't exist you've either got a) major stability problems, or b) no need for an actual database.
Designing the database, tables, and procedures is an entire component of the software development process. When I do this I usually keep all of my creation scripts in source control. After creation you will write the program in such a way that it assumes the database already exists - checking for connectivity is one thing, but the program should never think that there is no database at all.
you can make a script from all of objects that exist in your db. after that you can run this script from your code.
when you create your db script with script wizard in sql server, in "choose script options" section, set "Include If Not Exist" to yes. with this work done only if db not exists.

Categories