I found code here: Update linked tables in MS Access Database with C# programatically That will re-link a table, but how do you actually Link the table and change the name from what it is titled in SQL Server?
I have gotten some pretty rough code started, but am getting hung-up on the parameters...
Microsoft.Office.Interop.Access.Application docacc = new Microsoft.Office.Interop.Access.Application();
docacc.DoCmd.TransferDatabase(AcDataTransferType.acLink
EDIT -- Access 2003 - and I want to link the table from SQL server into access
EDIT # 2
I found this site: http://bytes.com/topic/visual-basic-net/answers/379904-create-linked-table
And have adapted code there, but I get an error of 'unable to establish connection' on my server?
I found a solution....
string path = "path to Access database";
DAO.Database dd;
DAO.DBEngine db = new DAO.DBEngine();
DAO.TableDef tdf - new DAO.TableDef();
dd.db.OpenDatabase(path);
tdf = dd.CreateTableDef();
tdf.Name = "Whatever you want the linked table to be named";
tdf.Connect = "ODBC;Driver=SQL Server;Server=<Server Name>;Database=<DB NAME>;Trusted_Connection=YES";
tdf.SourceTableName = "Whatever the SQL Server Table Name is";
dd.TableDefs.Append(tdf);
Related
I have a WinForms database driven application that I want to make it work in online/offline mode using Dotmim sync framework that I find an article by their author here.
The documentation for the library is here
this is my code to sync the two SQL Server databases one is localdb and the other one is now on the SQL Server Management Studio for the testing purpose:
string connect = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=bright_square_db;Integrated Security=SSPI;AttachDBFilename=D:\Folder\project_file\bright_square_db.mdf";
string constring = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlSyncProvider serverProvider = new SqlSyncProvider(constring);
SqlSyncProvider clientProvider = new SqlSyncProvider(connect);
SyncAgent agent = new SyncAgent(clientProvider, serverProvider, new string[] { "I have listed all the tables here" });
var progress = new SynchronousProgress<ProgressArgs>(s => MessageBox.Show($"{s.Context.SyncStage}:\t{s.Message}"));
var syncContext = await agent.SynchronizeAsync(progress);
MessageBox.Show(syncContext.ToString());
But, when I try to run the code. I am getting this error
The columns that indicated in the error are for a table that created by the sync process named "scope_info" inside the SQL Server database.
I have solved the problem by swapping the client and server connection string link in the third and fourth line of the above code. I don't know what exactly cause the problem, but lastly this changed makes the code work for me.
I have a program where on a click event SQL will open and connect to a server instance and database however. I am wanting to make to program a bit more dynamic and allow user input but I am struggling to get this to work as wanted.
The old code is as follows and this works:
Process.Start("ssms.exe", "-S .\\SQLEXPRESS -d master -E ");
I tried the following but this just opens SQL but states will not use the details enterd to connect to a database.
Process.Start("ssms.exe", DataBaseNameInput.Text);
Edit
The error SQl shows is The following files where specified on the command line: These files could not be found and will not be loaded.
For this you would need to use SqlConnectionStringBuilder(), this allows you to build a string whitch can then be passed.
var Connection = new SqlConnectionStringBuilder();
Connection.DataSource = ServerNameTextBox.Text;
Connection.InitialCatalog = DatabaseTextbox.Text;
Connection.UserID = UserNameTextBox.Text;
Connection.Password = PasswordTextBox.Text;
var connString = Connection.ConnectionString;
This was done by the following information
Ssms Utility
A Microsoft Office Access database contains Tables, Queries, Forms and Reports.
Is it possible to build and save a query in the Access database from C#?
For example, I know I can use OLEDB to connect to an Access database and use SQL commands using its tables and already defined queries, but how would I build a new query and then save it in the database?
If you want to add Querydefinitons to an existing access database you can do so with the Access Interop asssembly.
Create a new c# project and add a reference to:
Microsoft Office 12.0 Access database engine Object Library
(or a version that matches your Office/Access version)
This code creates a Query in the Access Database for every table in the database to query the count of rows:
var dbe = new DBEngine();
var db = dbe.OpenDatabase(#"c:\path\to\your\youraccessdatabase.accdb");
// loop over tables
foreach (TableDef t in db.TableDefs)
{
// create a querydef
var qd = new QueryDef();
qd.Name = String.Format("Count for {0}", t.Name);
qd.SQL = String.Format("SELECT count(*) FROM {0}", t.Name);
//append the querydef (it will be parsed!)
// might throw if sql is incorrect
db.QueryDefs.Append(qd);
}
db.Close();
I am inserting a SQL Database Backup and Recovery section into my program. I have been using MSDN Examples (tryed another and it wouldnt work).
MSDN Page - http://msdn.microsoft.com/en-us/library/ms162133.aspx
I have got the Backup file working, and have tested the file in Management Studio.
But I am having trouble with the Recovery of the file.
The code seems to be working, but the database in SQL Server is stuck in "Restoring..."
if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Server sqlServer = new Server();
Restore sqlRestore = new Restore();
sqlRestore.NoRecovery = true;
sqlRestore.Action = RestoreActionType.Database;
BackupDeviceItem deviceItem = new BackupDeviceItem(openFile.FileName, DeviceType.File);
sqlRestore.Devices.Add(deviceItem);
sqlRestore.Database = "firstRecoverTest";
sqlRestore.SqlRestore(sqlServer);
//Add the recovered database into the Entity Table
SqlCommand intoEntity = new SqlCommand("IF NOT EXISTS(SELECT entityName FROM Entitys WHERE entityName = 'firstRecoveryTest') INSERT INTO Entitys VALUES ('firstRecoveryTest');", sqlConnection);
sqlConnection.Open();
intoEntity.ExecuteNonQuery();
Database db = default(Database);
db = sqlServer.Databases["firstRecoverTest"];
db.RecoveryModel = (RecoveryModel)1;
db.AutoClose = true;
//db.Alter();
}
In the example there is a db.Alter(); function, but that throws an error that says "Alter failed for Database 'firstRecoverTest'".
Please let me know your thoughts
Thanks in advance
UPDATE
After inserting the "ReplaceDatabase = true;" there was no change in the end result.
Also stepping though the code line by line, shows that it is making it through.
The "db.Alter();" is just that placed at the end of the code (shown as comment). It is used in the creation of the backup and works without error.
InnerError shows this information when using db.Alter();
"ALTER DATABASE is not permitted while a database is in the Restoring state"
The interesting part is the SQL Log files. I am getting 3 Logs:
"Starting up database 'firstRecoverTest'."
"The database 'firstRecoverTest' is marked RESTORING and is in a state that does not allow recovery to be run."
"Database was restored: Database: firstRecoverTest, creation date(time): 2011/09/20(15:44:48), first LSN: 37:159:37, last LSN: 37:175:1, number of dump devices: 1, device information: (FILE=1, TYPE=DISK: {'C:\Users\Administrator\Desktop\installer_backup'}). Informational message. No user action required."
However, when I do a normal recover using SQL Management Studio there is 2 more log entrys saying
"Starting up database '[databaseName]'."
"Restore is complete on database '[databaseName]'. The database is now available"
I don't have enough reputation to post a small image of how it is in SQL Management Studio unfortunatly.
You should try either dropping the database or using sqlRestore.ReplaceDatabase = true;.
http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.restore.replacedatabase.aspx
If it looks like nothing is happening you can start the process in a seperate thread and wire up the events for notification of progress changes by using these.
sqlRestore.Complete += new ServerMessageEventHandler(completionEvent);
sqlRestore.PercentCompleteNotification = 10; // Call progress event every x percent change.
sqlRestore.PercentComplete += new PercentCompleteEventHandler(progressEvent);
If that doesn't work can you please post the Alter code that wasn't working. Also check SQL server logs and permissions.
UPDATED
Ok that update makes more sense. The reason is because you are setting sqlRestore.NoRecovery = true;. This has the effect that after the restore is done the DB is kept in a recovery state so you can restore an additional differential backup in addition to the full you just restored.
While it is in this state you will not be able to do anything more to the database. I would suggest that unless you require it you leave the default which is NoRecovery = false.
See http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.backuprestorebase.norecovery.aspx
Hope that helps.
I'm using Mindscape.Lightspeed and getting the following error:
Error: Invalid object name 'KeyTable'.
LightSpeedContext<LightSpeedModel1UnitOfWork> context = new LightSpeedContext<LightSpeedModel1UnitOfWork>("Development");
using (var uow = context.CreateUnitOfWork())
{
SiteUser user = new SiteUser();
user.UserName = "ABC";
user.RoleId = 1;
uow.Add(user);
}
I posted this commment on the official forum where you also posted this question :-)
This error message is being generated because you're using the KeyTable identity method. The Identity Method is how LightSpeed will generate identifiers for your entities and, by default, uses the KeyTable pattern. This requires a table called "KeyTable" (there is a script for this in the LightSpeed installation directory under the providers folder).
If you don't want to use the KeyTable identity method please configure an appropriate method on your LightSpeedContext configuration in the .config file. There is information about the various methods in the help file, in the getting started screencast and in some of the samples.
You can read the help file page online here:
http://www.mindscape.co.nz/Help/LightSpeed/Help%20Topics/LightSpeed/IdentityGeneration.html
I hope that helps,
John-Daniel
To save you a step or two, here's the SQL from the Lightspeed install folder to create the KeyTable in SQL Server 2008
(C:\Program Files (x86)\Mindscape\LightSpeed\Providers\SQLServer2008)
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'U' AND name = 'KeyTable')
BEGIN
DROP TABLE KeyTable
END;
CREATE TABLE KeyTable
(
NextId INT NOT NULL
)
INSERT INTO KeyTable VALUES (1);