RavenDB v3 persist Database Creation - persistence

My program does the following:
Creates a new EmbeddedDocument store
docStore = new DocumentStore
{
DefaultDatabase = "Default",
Url = url
};
docStore.Conventions.DefaultQueryingConsistency = ConsistencyOptions.QueryYourWrites;
docStore.Initialize();
Creates a new database within that document store
using (var session = docStore.OpenSession())
{
docStore.DatabaseCommands.GlobalAdmin.CreateDatabase(
new DatabaseDocument
{
Id = name,
Settings = settings
});
session.SaveChanges();
}
Starts up a smuggler process that imports data from a ravendump file into the newly created database.
When I navigate to localhost:port while step 2 and 3 are occuring, I see the database get created and the documents get put into the database.
Now, once that process spins down, and I attempt to reconnect to the embedded database, everything is gone--It's like the database creation and import never took place. What am I missing? Do I need to call Save on something?

Related

Meteor get Files via GridFS of a Remote Collection

I am connecting to some remote collections via the following pattern:
let remoteDB = new MongoInternals.RemoteCollectionDriver("mongodb://localhost:7071/meteor");
export const RemoteCollection = new Mongo.Collection("remoteCollection", {_driver:remoteDB});
Which is working fine for normal collections.
However, there is a FilesCollection (via ostrio:files) that also exists in this remote DB.
The FileCollection constructor does not let me pass the _driver options, so I am asking if someone has managed to load the remote files via gridfs, before opening a ticket on the project.
Looking at the source of Meteor-Files, the Mongo.Collection is added in lines 126-130 of server.js and lines 73-77 of client.js without any options being passed in.
What you can do is pass your own RemoteCollection into the FilesCollection constructor and the collection will use your collection and it's remote.
let remoteDB = new MongoInternals.RemoteCollectionDriver("mongodb://localhost:7071/meteor");
export const RemoteCollection = new Mongo.Collection("remoteCollection", {_driver:remoteDB});
export const RemoteFilesCollection = new FilesCollection({
collectionName: "remoteCollection",
collection: RemoteCollection
});
You'll also need to add all the extra code for GridFS integration to Meteor-Files: https://github.com/VeliovGroup/Meteor-Files/wiki/GridFS-Integration

EntityFrameworkCore: How to initialize a Database and seed it the first time user uses an application

I have build a project using Microsoft Visual Studio 2015 and EntityFrameworkCore.
I have seed manually a couple of dummy data and I was developing my solution. Now, I want to deploy the in the server, but I get the problem that by starting the application the first time, it crash since it does not find a data base and data.
I have googled and I find the solution for Visual Studio 2013 and previous using the CreateDatabaseIfNotExists class that need the package: System.Data.Entity
(http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx), however, such classes and packages do not exist in EntityFrameworkCore.
How does I create and populate a database with at least one row if user is using my application by the first time in EntityFrameworkCore?
or which is the equivalent to System.Data.Entity in Entity Framework Core?
Rowan Miller says that ApplyMigrations is enough to create database (if not exist) and apply all (nesessary) migrations.
Create method like this:
public void CreateDbAndSampleData(IServiceProvider applicationServices)
{
using (var serviceScope = applicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
using (var db = serviceProvider.GetService<ApplicationDbContext>())
{
// This will [try to] create database
// and apply all necessary migrations
db.Database.AsRelational().ApplyMigrations();
// then you can check for existing data and modify something
var admin = db.Users.Where(x => x.Name == "Superadmin").FirstOrDefault();
if (admin == null)
{
db.Users.Add(new User {...});
db.SaveChanges();
}
}
}
}
And call it from your Startup.cs, at end of Configure method:
CreateDbAndSampleData(app.ApplicationServices);
This code will run on every app startup, so you need to be accurate and do not overwrite any non-critical data changes (like changing Users's comment etc)
You can use MusicStore app as a sample: Startup.cs and SampleData.cs

How to handle changes to db in meteor/mongo?

I'm a couple hours new to Meteor and Mongo, coming from a Rails background and trying to understand how migrations work - or don't maybe?
I have a server/bootstrap.js file that I use to seed some data:
// if the database is empty on server start, create some sample data.
Meteor.startup(function () {
if (Users.find().count() === 0) {
var userData = [
{ name: 'Cool guy' },
{ name: 'Other dude' }
];
for (var i = 0; userData.length; i++) {
var userId = Users.insert({
name: userData[i].name
});
}
}
});
It seems like every time I want to change the database, say to add a new field, I have to run meteor reset to get it to pick up the changes.
But what happens if I create records or other data through the UI that I want to keep? In Rails, working with MySQL or PostgreSQL, I'd create a migration to create new fields without blowing away the entire database.
How does this work with Meteor and Mongo? Also thinking of the case of rolling out new changes from development to production. Thanks!
-- Update: 2013/09/24 --
Apparently, the schema-less nature of Mongo reduces or eliminates the need for migrations. In my case, modifying userData to add new fields won't work after it runs initially because of the Users count check - which is why I kept running meteor reset. I'll need to rethink my approach here and study up.
That said, there are projects out there that use migrations, like Telescope: https://github.com/SachaG/Telescope/blob/master/server/migrations.js
I also found the tutorial at http://try.mongodb.org/ useful.
First of all, your code is perfectly valid. And you know that.
mrt reset gives you a 'fresh' - empty database (as mentionned already).
If you want to reset a particular collection, you can do it so :
MyCollection.remove({});
But you have to understand the nature of NoSQL : there are no constraints on the data. It could be called NoREL (as in not a relational database, source : Wikipedia ).
MongoDB is also schema-less.
This means that you can use any field you want in your data. This is up to you (the programmer) to enforce specific constraints if you want some. In other words, there is no logic on the mongo side. It should accept any data you throw at it, just like Hubert OG demonstrated. Your code snippet could be :
// if the database is empty on server start, create some sample data.
Meteor.startup(function () {
if (Users.find().count() === 0) {
var userData = [
{ name: 'Cool guy' },
{ name: 'Other dude' },
{ nickname: 'Yet another dude' } // this line shows that mongo takes what you throw him
];
for (var i = 0; userData.length; i++) {
var userId = Users.insert({
name: userData[i].name
});
}
}
});
Source : http://www.mongodb.com/nosql
There is no need for migration there. You only have to add the logic in your application code.
Note : To import/export a database, you can have a look there : mongo import/export doc, and maybe at the db.copyDatabase(origin, destination, hostname) function.
There are no migrations in Mongo — there is no scheme! If you want to add a new field that was not there before, just do it and it will work. You can even have completely different documents in the same collection!
Items.insert({name: "keyboard", type: "input", interface: "usb"});
Items.insert({cherries: true, count: 5, unit: "buckets", taste: "awesome"});
This will just work. One of main reasons to use NoSQL (and advantages of Meteor over Rails) is that you don't have migrations to worry about.
Using mrt reset to change db model is a terrible idea. What it actually does is complete reset of db — it removes all of your data! While it's sometimes usefull in development, I bet it's not what you want in this case.

Manage Transactions on Business Layer

I want to use TransactionScope class in my business layer to manage database operation in data access layer.
Here is my sample code. When i execute it, it tries to enable the dtc. I want to do the operation without enable dtc.
I already checked https://entlib.codeplex.com/discussions/32592 article. It didn't work for me. I read many articles on this subject but none of them really touch enterprise library or i didn't see.
by the way, i am able to use TransactionScope using dotnet sql client and it works pretty well.
what would be the inside of SampleInsert() method?
Thanks,
Business Layer method:
public void SampleInsert()
{
using (TransactionScope scope = new TransactionScope())
{
Sample1DAL dal1 = new Sample1DAL(null);
Sample2DAL dal2 = new Sample2DAL(null);
Sample3DAL dal3 = new Sample3DAL(null);
dal1.SampleInsert();
dal2.SampleInsert();
dal3.SampleInsert();
scope.Complete();
}
}
Data Access Layer method:
//sampleInsert method structurally same for each 3 dal
public void SampleInsert()
{
Database database = DatabaseFactory.CreateDatabase(Utility.DATABASE_INFO); ;
using (DbConnection conn = database.CreateConnection())
{
conn.Open();
DbCommand cmd = database.GetStoredProcCommand("P_TEST_INS", "some value3");
database.ExecuteNonQuery(cmd);
}
}
Hi yes this will enable dtc because you are creating 3 DB connections within one TransactionScope . When more than one DB connection is created within same TransactionScope the local transaction escalate to Distributed Transaction and hence dtc will be enabled to manage Distributed Trnsactions.You will have to do it in a way that only one DB connection is created for entire TransactionScope. I hope this will give you an idea.
After research and waching query analyzer, I changed the SampleInsert() body as follows and it worked. The problem was as ethicallogics mentioned opening new connection each time i access the database.
public void SampleInsert()
{
Database database = DatabaseFactory.CreateDatabase(Utility.DATABASE_INFO);
using (DbCommand cmd = database.GetStoredProcCommand("P_TEST_INS", "some value1"))
{
database.ExecuteNonQuery(cmd);
}
}

iPhone - Connection String and DB File

I am developing a iPhone app using Monotouch. I need to access a Sqlite DB. In my soultion, I have a contracts, data access, business access and UI project. I have two questions:
Where should I keep my DB file? Originally, I put it in the data access project. When I compile my business access project it copies the DB file to the output, but when I compile my UI project it does not (UI has a reference to business access which has a ref to data access). I moved it to the UI project, but it feels wrong to keep it there.
Where should I keep the connection string to the DB? Is there a concept of config files?
Here is what we do:
We ship a copy of the DB in the application. It is included as Content, Always Copy in the project.
On the user's machine, it is stored in the special directory Environment.SpecialFolder.Personal.
When the app is started, we check to see if the database exists on the user's system and, if not, copy it there.
The connection string is just "Data Source=" + sDatabasePath.
Here is a sample of the code that we use for this (I hacked in the connection stuff since we use a homebuilt class for managing the DB, but you should get the idea):
const string DATABASE_FILE_NAME = "MyDB.db3";
bool fSuccess = false;
DbConnection conn = new DbConnection ();
string sApplicationDir = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.Personal), "MyApplicationSubDir");
if (!Directory.Exists (sApplicationDir)) {
Directory.CreateDirectory (sApplicationDir);
}
// Generate the directory to the database file
string sDatabaseDir = Path.Combine (sApplicationDir, "Database");
m_sDatabaseDir = sDatabaseDir;
if (!Directory.Exists (sDatabaseDir)) {
Directory.CreateDirectory (sDatabaseDir);
}
// Generate the path to the database file
string sDatabasePath = Path.Combine (sDatabaseDir, DATABASE_FILE_NAME);
m_sDatabaseFile = sDatabasePath;
// If the file does not not exist
if (!File.Exists (sDatabasePath)) {
// Copy the base implementation
File.Copy (Path.Combine (Path.Combine (Environment.CurrentDirectory, "Database"), DATABASE_FILE_NAME), sDatabasePath);
}
// Initialize the DB
conn.ConnectionString = "Data Source=" + sDatabasePath;
out of interest, have you looked at sqlite-net ? http://code.google.com/p/sqlite-net/
Makes your DB handling a lot easier.