Is it possible to set the connection string of crystal report from the properties.settings of a winform in c# like the following?
this is just my assumptions
rpt.connectionString = Properties.Settings.Default.ConnectionString
This is my code for managing logins/connectionstrings (dbLogin is just a simple class for storing information, you can replace that with string values).
//Somewhere in my code:
foreach (CrystalDecisions.CrystalReports.Engine.Table tbCurrent in rdCurrent.Database.Tables)
SetTableLogin(tbCurrent);
//My set login method
private void SetTableLogin(CrystalDecisions.CrystalReports.Engine.Table table)
{
CrystalDecisions.Shared.TableLogOnInfo tliCurrent = table.LogOnInfo;
tliCurrent.ConnectionInfo.UserID = dbLogin.Username;
tliCurrent.ConnectionInfo.Password = dbLogin.Password;
if(dbLogin.Database != null)
tliCurrent.ConnectionInfo.DatabaseName = dbLogin.Database; //Database is not needed for Oracle & MS Access
if(dbLogin.Server != null)
tliCurrent.ConnectionInfo.ServerName = dbLogin.Server;
table.ApplyLogOnInfo(tliCurrent);
}
In case you already have a successfull connectiont to SQL Server, you may use the following static method to set your report connection based on your SqlConnection:
using System.Text;
using CrystalDecisions.Shared;
using System.Data.SqlClient;
namespace StackOverflow
{
public class MyCrystalReports
{
// This method will allow you may easily set report datasource based on your current SqlServerConnetion
public static void SetSqlConnection(CrystalDecisions.CrystalReports.Engine.ReportClass MyReport, SqlConnection MySqlConnection)
{
// You may even test SqlConnection before using it.
SqlConnectionStringBuilder SqlConnectionStringBuilder = new SqlConnectionStringBuilder(MySqlConnection.ConnectionString);
string ServerName = SqlConnectionStringBuilder.DataSource;
string DatabaseName = SqlConnectionStringBuilder.InitialCatalog;
Boolean IntegratedSecurity = SqlConnectionStringBuilder.IntegratedSecurity;
string UserID = SqlConnectionStringBuilder.UserID;
string Password = SqlConnectionStringBuilder.Password;
// Of course, you may add extra settings here :D
// On Crystal Reports, connection must be set individually for each table defined on the report document
foreach (CrystalDecisions.CrystalReports.Engine.Table Table in MyReport.Database.Tables)
{
CrystalDecisions.Shared.TableLogOnInfo TableLogOnInfo = Table.LogOnInfo;
TableLogOnInfo.ConnectionInfo.ServerName = ServerName;
TableLogOnInfo.ConnectionInfo.DatabaseName = DatabaseName;
TableLogOnInfo.ConnectionInfo.IntegratedSecurity = IntegratedSecurity;
if (IntegratedSecurity != true)
{
TableLogOnInfo.ConnectionInfo.UserID = UserID;
TableLogOnInfo.ConnectionInfo.Password = Password;
}
Table.ApplyLogOnInfo(TableLogOnInfo);
}
}
}
}
Related
I have query to dynamically create database.
private void ExecuteNonQuery(string sql)
{
using (var connection = new SqlConnection(_connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = sql;
command.ExecuteNonQuery();
}
}
private void CreateDatabase(string databaseName)
{
try
{
ExecuteNonQuery($"CREATE DATABASE {databaseName}");
}
catch (Exception e)
{
throw new Exception($"Can't create database '{databaseName}'");
}
}
Database will be created using my existing connection , But I need to create connection string for this new database to run migration and for various other purposes.
How is it possible ?
Update
Its actually for purpose where users can fill a form to create a new database where they can give their existing connection string or if they don't have one in hand we build it for them
use this function to get a connection to the new database:
private SqlConnection NewDatebaseConnection(string databaseName)
{
SqlConnection connection = new SqlConnection(_connectionString);
connection.ChangeDatabase(databaseName);
return SqlConnection;
}
To save new connection, you can use ConnectionStringBuilder with existing connection, change the name of database and save it to app.config.
1.Helper method to get connection string:
string GetConnectionString(string name) =>
ConfigurationManager.ConnectionStrings[name].ConnectionString;
2.Helper method which saves new connection string to app.config:
void CreateNewConnectionString(string baseName, string newName, string newDatabaseName)
{
// Get the connection string a new connection will be based on
string baseConnString =
ConfigurationManager.ConnectionStrings[baseName].ConnectionString;
// For simplicity of manipulations with connection strings,
// we use SqlConnectionStringBuilder, passing it an existing connection string
var connBuilder = new SqlConnectionStringBuilder(baseConnString);
// Change existing database name to the new database name
connBuilder.InitialCatalog = newDatabaseName;
// Create new settings, holding our new connection string
var newConnection = new ConnectionStringSettings(newName, connBuilder.ToString());
// Save new connection string
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings.Add(newConnection);
config.Save(ConfigurationSaveMode.Modified);
}
3.Usage
private void CreateDatabase(string databaseName)
{
try
{
// Create database using "main" connection string
ExecuteNonQuery($"CREATE DATABASE {databaseName}", "main");
// Create new connection string "my_db" based on "main"
CreateNewConnectionString("main", "my_db", databaseName);
}
catch (Exception e)
{
throw new Exception($"Can't create database '{databaseName}'");
}
}
If you are using EF, you should have a context to work with, something like the following:
public class MyContext : DbContext
{
public MyContext():base("myConnectionStringName")
{
}
}
The constructor has a parameter that specifies connection name or a connection string. So, you can obtain a context for any connections string you want:
using (var db = new MyContext("connection_string_containing_new_db")
{
// do stuff with the context
}
You should consider using a factory that builds such contexts:
class MyContextFactory
{
MyContext CreateContextForDatabase(string dbName)
{
var builder = new SqlConnectionStringBuilder();
builder["Data Source"] = "server\\instance";
builder["integrated Security"] = true;
builder["Initial Catalog"] = dbName;
return new new MyContext(builder.ConnectionString);
}
}
The code uses SqlConnectionStringBuilder to construct (from scratch) the connection string. An alternative is to parse a static connection string using var builder = new SqlConnectionStringBuilder(staticConnectionString) and only change the Initial Catalog.
I have a problem in showing report using Crystal Report. I don't have a problem in my local pc, but when i try to run my report in another machine (PC) crystal report always shows logon screen like this below :
Based on screen shot above, the information only shows the server name, loginID and password, database was disable. So I can't show the data from report even I fill the correct loginID and password, because I can't fill database name (database fill box was disabled by default).
I develop this report using microsoft visual studio 2010, and I set the target framework = 3.5. For SQL Server, I used SQL Server 2014.
As for the other PC specs that I use to test this report is a windows server 2012 with SQL Server 2014.
I also have already install the CRRuntime_64bit_12_0_15 in this machine.
I used this code to show the report :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using CrystalDecisions;
using CrystalDecisions.CrystalReports;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
namespace SGLCreditControlReport
{
public partial class FrmPreview : Form
{
string BranchID, Department, Period1, Period2, AssetClass;
string server, dbname, userdb, passdb;
public FrmPreview(string branchID, string Department, string AssetClass, string Period1, string Period2)
{
InitializeComponent();
this.BranchID = branchID;
this.Department = Department;
this.Period1 = Period1;
this.Period2 = Period2;
this.AssetClass = AssetClass;
server = Properties.Settings.Default.server;
dbname = Properties.Settings.Default.dbname;
userdb = Properties.Settings.Default.userid;
passdb = Properties.Settings.Default.passid;
}
private void FrmPreview_Load(object sender, EventArgs e)
{
this.crystalReportViewer1.Refresh();
}
private void FrmPreview_Shown(object sender, EventArgs e)
{
ExecuteReport(this.BranchID, this.Department, this.AssetClass , this.Period1, this.Period2);
}
private void ExecuteReport(string branchID, string department, string assetClass, string periodMonth, string periodYear)
{
string periodFix = periodYear + periodMonth;
TableLogOnInfo tblLogOnInfo = new TableLogOnInfo();
TableLogOnInfos tblLogOnInfos = new TableLogOnInfos();
ConnectionInfo conInfo = new ConnectionInfo();
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load(#"rptAssetList.rpt");
loadReport(tblLogOnInfo, tblLogOnInfos, conInfo, rptDoc, branchID, department, assetClass, periodMonth, periodYear);
}
private void loadReport(TableLogOnInfo tblLogOnInfo, TableLogOnInfos tblLogOnInfos, ConnectionInfo conInfo, ReportDocument rptDoc, string branchID, string department, string assetClass, string periodMonth, string periodYear)
{
conInfo.ServerName = server;
conInfo.DatabaseName = dbname;
conInfo.UserID = userdb;
conInfo.Password = passdb;
string periodFix = periodYear + periodMonth;
string query;
Tables tbls = rptDoc.Database.Tables;
foreach (Table CrTable in tbls)
{
tblLogOnInfo = CrTable.LogOnInfo;
tblLogOnInfo.ConnectionInfo = conInfo;
CrTable.ApplyLogOnInfo(tblLogOnInfo);
}
#region set null for empty string
if (branchID == "")
branchID = null;
if (department == "")
department = null;
if (assetClass == "")
assetClass = null;
if (periodFix == "")
periodFix = null;
#endregion
crystalReportViewer1.ReportSource = rptDoc;
//------ for passing parameter value ---------//
rptDoc.SetParameterValue("#Period", periodFix);
rptDoc.SetParameterValue("#BranchCD", branchID);
rptDoc.SetParameterValue("#AssetClass", assetClass);
rptDoc.SetParameterValue("#Department", department);
crystalReportViewer1.Refresh();
}
}
}
Please give references or suggestions how to solve this problem.
Thanks
I'm getting the error 'Log on failed' when trying to change my datasource at runtime. I've trawled SO and the SAP site and from that put together the code below, but I'm still getting the error. My access db is 2013 and isn't password protected and I'm using the default "Admin" user. The report has an OLE DB connection. My code loops through all tables, including subreports and changes the login, and I also change the database login. Any help much appreciated:
public void RunTestReport()
{
DataSet testDataSet = new DL.NonConformance().GetNonConformances(1, "NonConformance");
var rpt = new ReportDocument();
rpt.Load(#"C:\Reports\rptTest.rpt");
SetCrystalLogin(rpt);
rpt.SetDataSource(testDataSet);
crystalReportViewer1.ReportSource = rpt;
crystalReportViewer1.Refresh();
}
public void SetCrystalLogin(ReportDocument oRpt)
{
ConnectionInfo oConnectInfo = new ConnectionInfo();
string dbpath = string.Concat(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"\db\dbacc.db");
oConnectInfo.ServerName = dbpath;
oConnectInfo.DatabaseName = string.Empty;
oConnectInfo.UserID = "Admin";
oConnectInfo.Password = string.Empty;
// Set the logon credentials for all tables
SetCrystalTablesLogin(oConnectInfo, oRpt.Database.Tables);
// Check for subreports
foreach (CrystalDecisions.CrystalReports.Engine.Section oSection in oRpt.ReportDefinition.Sections)
{
foreach (CrystalDecisions.CrystalReports.Engine.ReportObject oRptObj in oSection.ReportObjects)
{
if (oRptObj.Kind == CrystalDecisions.Shared.ReportObjectKind.SubreportObject)
{
// This is a subreport so set the logon credentials for this report's tables
CrystalDecisions.CrystalReports.Engine.SubreportObject oSubRptObj = oRptObj as CrystalDecisions.CrystalReports.Engine.SubreportObject;
// Open the subreport
CrystalDecisions.CrystalReports.Engine.ReportDocument oSubRpt = oSubRptObj.OpenSubreport(oSubRptObj.SubreportName);
SetCrystalTablesLogin(oConnectInfo, oSubRpt.Database.Tables);
}
}
}
oRpt.Refresh();
oRpt.SetDatabaseLogon("Admin", string.Empty, dbpath, string.Empty, true);
oRpt.VerifyDatabase();
oRpt.Refresh();
}
private void SetCrystalTablesLogin(CrystalDecisions.Shared.ConnectionInfo oConnectInfo, Tables oTables)
{
foreach (CrystalDecisions.CrystalReports.Engine.Table oTable in oTables)
{
CrystalDecisions.Shared.TableLogOnInfo oLogonInfo = oTable.LogOnInfo;
oLogonInfo.ConnectionInfo = oConnectInfo;
oTable.ApplyLogOnInfo(oLogonInfo);
}
}
Turns out you can't configure a .accdb datasource at runtime, I'll need to create an ODBC connection.
I am new with crystal reports. I tried to to implement the crystal report in my win form c# application using report wizard visual studio 2012, so don't know what happen's in backhand for this. Everything works good on my computer but when i tried install this on another computer connection string changes and gives error.
I tried many links like Dynamic Connection string Change but as i am using report wizard for setup so don't know where to use this.
I also tried all options in report wizard for connection string but didn't find anything that change connection string at run time.
Is there any options by which i can attach connection String from app config at run time.
Try something like this:
strServer= ConfigurationManager.AppSettings["ServerName"].ToString();
strDatabase= ConfigurationManager.AppSettings["DataBaseName"].ToString();
strUserID= ConfigurationManager.AppSettings["UserId"].ToString();
strPwd= ConfigurationManager.AppSettings["Password"].ToString();
report.DataSourceConnections[0].SetConnection(strServer, strDatabase, strUserID, strPwd);
strServer= ConfigurationManager.AppSettings["ServerName"].ToString();
strDatabase= ConfigurationManager.AppSettings["DataBaseName"].ToString();
strUserID= ConfigurationManager.AppSettings["UserId"].ToString();
strPwd= ConfigurationManager.AppSettings["Password"].ToString();
//may be you need to set the integrated security to false, first.
report.DataSourceConnections[o].IntegratedSecurity = False;
report.DataSourceConnections[0].SetConnection(strServer, strDatabase, strUserID, strPwd);
Here's an example of changing all the main report tables as well as all subreports tables, to a newly specified TargetServer and TargetDatabase with Integrated Authentication:
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
// using CrystalDecisions.ReportAppServer.CommLayer; // not used directly, but this is needed in Project References.
//
// be sure to set "copy local" = true in the Project:
// see https://stackoverflow.com/questions/38025601/could-not-load-file-or-assembly-crystaldecisions-reportappserver-commlayer-ver
static ReportDocument crReportDocument;
static ConnectionInfo crConnectionInfo = new ConnectionInfo();
static public string TargetServer { get; set; }
static public string TargetDatabase { get; set; }
static void crAssignConnectionInfo()
{
crConnectionInfo.UserID = "";
crConnectionInfo.Password = "";
crConnectionInfo.DatabaseName = TargetDatabase;
crConnectionInfo.ServerName = TargetServer;
crConnectionInfo.IntegratedSecurity = true; // in case the report was saved with SQL authentication, switch to Integrated
}
static void SetSubreportLoginInfo(CrystalDecisions.CrystalReports.Engine.Sections objSections)
{
foreach (Section section in objSections)
{
foreach (ReportObject reportObject in section.ReportObjects)
{
SubreportObject crSubreportObject;
switch (reportObject.Kind)
{
case ReportObjectKind.SubreportObject:
crSubreportObject = (SubreportObject)reportObject;
ReportDocument subRepDoc = crSubreportObject.OpenSubreport(crSubreportObject.SubreportName);
if (subRepDoc.ReportDefinition.Sections.Count > 0) {
SetSubreportLoginInfo(subRepDoc.ReportDefinition.Sections);
}
Tables crTables = subRepDoc.Database.Tables;
foreach (Table table in crTables)
{
TableLogOnInfo tableLogOnInfo = new TableLogOnInfo();
tableLogOnInfo.ConnectionInfo.UserID = crConnectionInfo.UserID;
tableLogOnInfo.ConnectionInfo.Password = crConnectionInfo.Password;
tableLogOnInfo.ConnectionInfo.DatabaseName = crConnectionInfo.DatabaseName;
tableLogOnInfo.ConnectionInfo.ServerName = crConnectionInfo.ServerName;
tableLogOnInfo.ConnectionInfo.IntegratedSecurity = crConnectionInfo.IntegratedSecurity;
table.ApplyLogOnInfo(tableLogOnInfo);
}
break;
case ReportObjectKind.FieldObject:
case ReportObjectKind.TextObject:
case ReportObjectKind.LineObject:
case ReportObjectKind.BoxObject:
case ReportObjectKind.PictureObject:
case ReportObjectKind.ChartObject:
case ReportObjectKind.CrossTabObject:
case ReportObjectKind.BlobFieldObject:
case ReportObjectKind.MapObject:
case ReportObjectKind.OlapGridObject:
case ReportObjectKind.FieldHeadingObject:
case ReportObjectKind.FlashObject:
default:
// none of the other objects need to have login assigned
break;
}
}
}
}
static void SetCrystalDocumentLogon()
{
crAssignConnectionInfo();
TableLogOnInfo crTableLogonInfo = new TableLogOnInfo();
foreach (Table crTable in crReportDocument.Database.Tables)
{
try
{
crConnectionInfo.Type = crTable.LogOnInfo.ConnectionInfo.Type;
crTableLogonInfo.ConnectionInfo = crConnectionInfo;
crTableLogonInfo.ReportName = crTable.LogOnInfo.ReportName;
crTableLogonInfo.TableName = crTable.LogOnInfo.TableName;
crTable.ApplyLogOnInfo(crTableLogonInfo);
}
catch (Exception ex)
{
Console.WriteLine("Error during SetCrystalDocumentLogon " + ex.Message);
throw;
}
SetSubreportLoginInfo(crReportDocument.ReportDefinition.Sections);
}
}
I need to backup database (using SQL Server 2008 R2). Size of db is about 100 GB so I want backup content only of important tables (containing settings) and of course object of all tables, views, triggers etc.
For example:
db: Products
tables: Food, Clothes, Cars
There is too much cars in Cars, so I will only backup table definition (CREATE TABLE ...) and complete Food and Clothes (including its content).
Advise me the best solution, please. I will probably use SMO (if no better solution). Should I use Backup class? Or Scripter class? Or another (if there is any)? Which class can handle my requirements?
I want backup these files to *.sql files, one per table if possible.
I would appreciate code sample. Written in answer or somewhere (post url), but be sure that external article has solution exactly for this kind of problem.
You can use this part of code
ServerConnection connection = new ServerConnection("SERVER,1234", "User", "User1234");
Server server = new Server(connection);
Database database = server.Databases["DbToBackup"];
Using SMO. You will have to play with the options you need.
StringBuilder sb = new StringBuilder();
using (SqlConnection connection = new SqlConnection("connectionString")) {
ServerConnection serverConnection = new ServerConnection(connection);
Server server = new Server(serverConnection);
Database database = server.Databases["databaseName"];
Scripter scripter = new Scripter(server);
scripter.Options.ScriptDrops = false;
scripter.Options.WithDependencies = true;
scripter.Options.ScriptData = true;
Urn[] smoObjects = new Urn[1];
foreach (Table table in database.Tables) {
smoObjects[0] = table.Urn;
if (!table.IsSystemObject) {
foreach (string s in scripter.EnumScript(smoObjects)) {
System.Diagnostics.Debug.WriteLine(s);
sb.AppendLine(s);
}
}
}
}
// Write to *.sql file on disk
File.WriteAllText(#".\backup.sql");
Another easy way to do this is by backing the database to xml files. To do this use a DataTable and call WriteXml and WriteXmlSchema. (You need the schema later on so it can be imported/restored using the same method). This method means you are backing up per table.
private bool BackupTable(string connectionString, string tableName, string directory) {
using (SqlConnection connection = new SqlConnection(connectionString)) {
try {
connection.Open();
}
catch (System.Data.SqlClient.SqlException ex) {
// Handle
return false;
}
using (SqlDataAdapter adapter = new SqlDataAdapter(string.Format("SELECT * FROM {0}", tableName), connection)) {
using (DataTable table = new DataTable(tableName)) {
adapter.Fill(table);
try {
table.WriteXml(Path.Combine(directory, string.Format("{0}.xml", tableName)));
table.WriteXmlSchema(Path.Combine(directory, string.Format("{0}.xsd", tableName)));
}
catch (System.UnauthorizedAccessException ex) {
// Handle
return false;
}
}
}
}
return true;
}
You can later on then push these back into a database us by using ReadXmlSchema and ReadXml, using an adapter to fill and update the table to the database. I assume you are knowledgable in basic CRUD so I shouldn't need to cover that part.
If you want to use SMO, here is a Msdn article on using the Backup and Restore classes to backup and restore a database. The code sample us unformatted, and in VB.NET, but easily translatable.
http://msdn.microsoft.com/en-us/library/ms162133(v=SQL.100).aspx
Lastly, which may be easier, talk to the IT guys and see if they will let you remote in or give you access to do the backup yourself. If you are writing the software and this is a crucial step, speak up and let them know how important it is for you to do this, as this will reduce cost in you having to write a custom tool when great tools already exist. Especially since the database is 100GB, you can use the tools you know already work.
This arcitle was enough informative to solve my problem. Here is my working solution.
I decided script all objects to one file, it's better solution because of dependencies, I think. If there is one table per on file and there is also some dependencies (foreign keys for example) it would script more code than if everything is in one file.
I omitted some parts of code in this sample, like backuping backup files in case wrong database backup. If there is no such a system, all backups will script to one file and it will go messy
public class DatabaseBackup
{
private ServerConnection Connection;
private Server Server;
private Database Database;
private ScriptingOptions Options;
private string FileName;
private const string NoDataScript = "Cars";
public DatabaseBackup(string server, string login, string password, string database)
{
Connection = new ServerConnection(server, login, password);
Server = new Server(Connection);
Database = Server.Databases[database];
}
public void Backup(string fileName)
{
FileName = fileName;
SetupOptions();
foreach (Table table in Database.Tables)
{
if (!table.IsSystemObject)
{
if (NoDataScript.Contains(table.Name))
{
Options.ScriptData = false;
table.EnumScript(Options);
Options.ScriptData = true;
}
else
table.EnumScript(Options);
}
}
}
private void SetupOptions()
{
Options = new ScriptingOptions();
Options.ScriptSchema = true;
Options.ScriptData = true;
Options.ScriptDrops = false;
Options.WithDependencies = true;
Options.Indexes = true;
Options.FileName = FileName;
Options.EnforceScriptingOptions = true;
Options.IncludeHeaders = true;
Options.AppendToFile = true;
}
}
Server databaseServer = default(Server);//DataBase Server Name
databaseServer = new Server("ecrisqlstddev");
string strFileName = #"C:\Images\UltimateSurveyMod_" + DateTime.Today.ToString("yyyyMMdd") + ".sql"; //20120720
if (System.IO.File.Exists(strFileName))
System.IO.File.Delete(strFileName);
List<SqlSmoObject> list = new List<SqlSmoObject>();
Scripter scripter = new Scripter(databaseServer);
Database dbUltimateSurvey = databaseServer.Databases["UltimateSurvey"];//DataBase Name
// Table scripting Writing
DataTable dataTable1 = dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.Table);
foreach (DataRow drTable in dataTable1.Rows)
{
// string strTableSchema = (string)drTable["Schema"];
// if (strTableSchema == "dbo")
// continue;
Table dbTable = (Table)databaseServer.GetSmoObject(new Urn((string)drTable["Urn"]));
if (!dbTable.IsSystemObject)
if (dbTable.Name.Contains("SASTool_"))
list.Add(dbTable);
}
scripter.Server = databaseServer;
scripter.Options.IncludeHeaders = true;
scripter.Options.SchemaQualify = true;
scripter.Options.ToFileOnly = true;
scripter.Options.FileName = strFileName;
scripter.Options.DriAll = true;
scripter.Options.AppendToFile = true;
scripter.Script(list.ToArray()); // Table Script completed
// Stored procedures scripting writing
list = new List<SqlSmoObject>();
DataTable dataTable = dbUltimateSurvey.EnumObjects(DatabaseObjectTypes.StoredProcedure);
foreach (DataRow row in dataTable.Rows)
{
string sSchema = (string)row["Schema"];
if (sSchema == "sys" || sSchema == "INFORMATION_SCHEMA")
continue;
StoredProcedure sp = (StoredProcedure)databaseServer.GetSmoObject(
new Urn((string)row["Urn"]));
if (!sp.IsSystemObject)
if (sp.Name.Contains("custom_"))
list.Add(sp);
}
scripter.Server = databaseServer;
scripter.Options.IncludeHeaders = true;
scripter.Options.SchemaQualify = true;
scripter.Options.ToFileOnly = true;
scripter.Options.FileName = strFileName;
scripter.Options.DriAll = true;
scripter.Options.AppendToFile = true;
scripter.Script(list.ToArray()); // Stored procedures script completed
What you describe is not really a Backup but I understand what your goal is:
Scripter sample code
Using SMO to get create script for table defaults
http://blogs.msdn.com/b/mwories/archive/2005/05/07/basic-scripting.aspx
http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.scripter.aspx
http://weblogs.asp.net/shahar/archive/2010/03/03/generating-sql-backup-script-for-tables-amp-data-from-any-net-application-using-smo.aspx
http://en.csharp-online.net/SQL_Server_Management_Objects
http://www.mssqltips.com/sqlservertip/1833/generate-scripts-for-database-objects-with-smo-for-sql-server/
For "Backup" of Data you could load the table content via a Reader into a DataTable and store the result as XML...