MS Sync Framework and SQL Server Compact - c#

I develop a Windows C# application which can work in Online and Offline mode.
When in Online mode it connects to a SQL Server. In Offline mode it connects to a local DB.
I use the Microsoft Sync Framework 2.1 to sync the 2 databases on demand.
Until now I used a LocalDB instance of SQL Server as the local database. But it is a pain to setup the system automatically during the installation process of my application. So I tought to use SQL Server Compact 3.5 or 4.0 which is very easy to distribute (comes in a single file).
But I cannot get it to even compile the provisioning code of the Compact DB:
DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("MyScope");
SqlCeConnection clientConn = new SqlCeConnection(OfflineConnectionString);
var clientProvision = new SqlCeSyncScopeProvisioning(clientConn, scopeDesc);
clientProvision.Apply();
which I used before (without the Ce classes) but SqlCeSyncScopeProvisioning cannot be resolved.
Something is terribly wrong here.
How can I sync my CompactDB to distribute this as my local database?

First ensure, you have successfully installed the sdk?
After this, make sure you have added the following references:
Microsoft.Synchronization.Data.dll,
Microsoft.Synchronization.Data.Server.dll
Microsoft.Synchronization.Data.SqlServer.dll
Microsoft.Synchronization.Data.SqlServerCe.dll
Also in my case it worked with adding
System.Data.SqlServerCe - 4.0
EDIT
Against your comment, this is only working if you use SQL Server CE 4.
I've tried it now with SQL Server CE 3.5 and indeed I could reproduce your issue.
Switching to SQL Server CE 4.0 fixed it.
ExampleTable 4.0
TestCode
var scopeDesc = new DbSyncScopeDescription("MyScope");
var tbl = new DbSyncTableDescription("TestTable");
var pkColumn = new DbSyncColumnDescription("Id", "int");
pkColumn.IsPrimaryKey = true;
tbl.Columns.Add(pkColumn);
tbl.Columns.Add(new DbSyncColumnDescription("Name", "nvarchar(254)"));
scopeDesc.Tables.Add(tbl);
var clientConn = new SqlCeConnection(#"Data Source=test.sdf;Persist Security Info=False;");
var clientProvision = new SqlCeSyncScopeProvisioning(clientConn, scopeDesc);
clientProvision.Apply();
Result
Everything compiles nicely. After following the above steps, you should be able to easily migrate your code to SQL Server CE

Related

Programmatically script or migrate SQL Compact database for importing into SQL Server

I have used ErikEJ's SQLite/SQL server Compact Toolbox which allows migration from a compact database to SQL Server, but I am trying to implement this process into my ASP.NET application.
The user will have an already completed SQL Server Compact database.
The process will be
1) User selects the database
2) Existing SQL Server database will be deleted
3) Compact database will be scripted/migrated into SQL Server
The part I am unsure of is how I should script or migrate the SQL Compact database. Deleting and creating a new database on the server itself seems easy enough. I have been digging around in the System.Data.SqlServerCe class for a while and am unsure what the best approach would be.
Using my scripting API, you can do something like this:
using (IRepository ceRepository = new DB4Repository(#"Data Source=C:\Data\SQLCE\Test\nw40.sdf"))
{
string fileName = Path.GetTempFileName();
var generator = new Generator4(ceRepository, fileName);
generator.ScriptDatabaseToFile(Scope.SchemaData);
using (IRepository serverRepository = new ServerDBRepository4("Data Source=.;Trusted_Connection=true;Initial Catalog=Test"))
{
serverRepository.ExecuteSqlFile(fileName);
}
}
See my blog post here: http://erikej.blogspot.dk/2013/03/sql-server-compact-code-snippet-of-week_8.html
A more complete implementation (from my Toolbox)
https://github.com/ErikEJ/SqlCeToolbox/blob/master/src/GUI/SqlCe35Toolbox/Commands/SqlServerDatabaseMenuCommandsHandler.cs#L370

System cannot find file while connecting database in nhibernate

I am using fluent nhibernate since long. Its working fine until I updated my database. Prior I was using SQL Server 2012, and updated it to 2016. When try to connect database in application, it throws an error:
The system cannot find the file specified.
when it tried to connect. My connecting function is as below
Fluently.Configure().Database(MsSqlConfiguration.MsSql2005.ShowSql().ConnectionString(x=> x.FromConnectionStringWithKey("imConnectionString2"))).Mappings(m=> m.FluentMappings.AddFromAssemblyOf<MapUsers>()).BuildSessionFactory();
This was working fine before database update. I change MsSql2005 it to MsSql2012, but same result.
Do I have to do anything in Fluent Nhibernate side or configuration?
Any assistance please
There is a major change in the client connectivity for SQL Server 2016.
This change is due to sql client is becoming support windows and other O.S like Linux.
install Microsoft ODBC Driver 13 for SQL Server - Windows
https://www.microsoft.com/en-us/download/details.aspx?id=50420
review: Installing SQL Server Native Client
SQL Server Native Client (SNAC) is not supported beyond SQL Server 2012. Avoid using SNAC in new development work, and plan to modify applications that currently use it. The Microsoft ODBC Driver for SQL Server provides native connectivity from Windows to Microsoft SQL Server
Before configuring Nhibernate, be sure that you can connect with SQL server 2016 by using sqlcmd tool (for server 2016- download it)
Update:
When you install the driver named msodbcsql.msi, it's really the same driver of sql 2012 client.
I installed the driver in windows 7 (32 bit), using the library FluentNHibernate v 2.0.3 and connecting to SQL server 2016 and running successfully the following code:
class FluentNHibernateTest
{
private static ISessionFactory CreateSessionFactory()
{
//also MsSqlConfiguration.MsSql2005 is working
return Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2012.ShowSql()
.ConnectionString(x => x.FromConnectionStringWithKey("test16")))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Program>())
.BuildSessionFactory();
}
public static string GetSqlVersion()
{
string sql = "select ##version version";
var sessionFactory = CreateSessionFactory();
using (var session = sessionFactory.OpenSession())
{
var query = session.CreateSQLQuery(sql);
var result = query.UniqueResult();
Console.WriteLine(result);
return result.ToString();
}
}
}
Output result:
FluentNHibernateTest.GetSqlVersion();
Microsoft SQL Server 2016 (RTM-CU1) (KB3164674) - 13.0.2149.0 (X64)
Jul 11 2016 22:05:22
.......

MongoDB server State is disconnected

I am using MongoDb server installed on VM Ubuntu 14 on Azure, and I use this
tutroial, with last version. I add the port of mongo 27017 too.
And I connect to it directly and add Database with some collections.
I use the mongoDb .Net Driver on VS2015 in C# with version 2.0.1 (using link)
and try to connect to the Mongo Server, but the state of the server is disconnected
var client = new MongoClient("mongodb://name.cloudapp.net:27017");
var state = client.Cluster.Description.State;
MessageBox.Show(state.ToString());
I used it before the same steps and nothing happen, just I don't know where is the problem
Try this please. I think this may work. Just have to add one line to enumerate all databases.
var client = new MongoClient("mongodb://name.cloudapp.net:27017");
var databases = client.ListDatabases();
var state = client.Cluster.Description.State;
MessageBox.Show(state.ToString());
This answer explains better.

How do I used a database I created in MS SQL Server 2008 R2 with a VS C# Project?

I created a new database using SQL Server 2008 R2 by using the Management Studio. The connection says (local) and I am using Windows Authentication (though I installed with mixed mode).
My questions are:
How do I connect to the DB via my C# application -
The only time I ever have done this before I just used VS Menu > Tools > Connect to DB and the drop down saw my database and connected, then right clicked on it and grabbed the connection string for use in connecting. However I'm thinking because its (local) I don't have that option.
As per Q#1 I am assuming the database file is being stored somewhere locally - I am wondering how to find that location and how I can include it with my application
Edit** Per comment: VSMenu-> View-> Server Explorer and then use add connection to connect to your local SQL Server instance and then use the database you created from the databases dropdown, and from advance settings copy the connection string created by the connection dialog
This is what I am looking for but I am missing the step during "add connection" where do I find my SQL Server I created locally? As mentioned before I have no idea where it is stored or how to find it
MSDN has an example in the SQLConnection documentation
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(queryString, connection))
{
command.Connection.Open();
command.ExecuteNonQuery();
}
You can then optionally use a SqlDataAdapter.
You need to use ADO.NET, which is comprised of a connection object (SqlConnection), command object (SqlCommand), parameters objects (SqlParameter) and data sets (DataSet) or data readers (SqlDataReader).
Read A Beginner's Tutorial for Understanding ADO.NET.

replacing data access strategy from SQL Server to Access MDB file in C#

I created a small accounting application a while back. It uses SQL Server 2008 as backend data store. Now I realize that SQL Server is too much for such a
small program PLUS it is not very much portable. I mean I want to have this application on my USB stick for easy access anywhere, and SQL Server will not be
available everywhere. So now I want to replace the data store from SQL Server to something portable i.e. MS Access MDB file.
1- Is it a good option or should I use SQL Server express edition?
2- I don't have experience using SQL Express edition. If I use it, would it be needed on any machine where I intend to run my application?
2- What changes should I make in the code to make it compatioble with MDF files (or SQL Express)?
As I said it is quite simple program, it uses connected model to fetch and insert data currently. For example
void bindGrid()
{
try
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
DataSet set = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM Categories ORDER BY name", con);
da.SelectCommand = selectCommand;
da.Fill(set);
this.grdCategories.DataSource = set.Tables[0];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Rather than using Access, I would use LocalDB. It should require very few if any changes to your code other than the connection string.
http://blogs.msdn.com/b/sqlexpress/archive/2011/07/12/introducing-localdb-a-better-sql-express.aspx
LocalDB is created specifically for developers. It is very easy to install and requires no management, yet it offers the same T-SQL language, programming surface and client-side providers as the regular SQL Server Express. In effect the developers that target SQL Server no longer have to install and manage a full instance of SQL Server Express on their laptops and other development machines. Moreover, if the simplicity (and limitations) of LocalDB fit the needs of the target application environment, developers can continue using it in production, as LocalDB makes a pretty good embedded database too.
I would recommend SQL CE for small projects.
LocalDB vs SQL Server Compact
There are significant differences between LocalDB and SQL Server Compact:
Execution mode: SQL Server Compact is an in-proc DLL, while LocalDB runs as a separate process.
Disk usage: all SQL Server Compact binaries amount to some 4MBs, while LocalDB installation takes 140MBs.
Features: SQL Server Compact offers core RDBMS functionality like querying, while LocalDB provides a much richer set of features, including Stored Procedures, Geometry and Geography data types, etc.

Categories