I am Very new with MongoDB,I m using windows7 32bit,downloaded mongo exe files from http://www.mongodb.org/display/DOCS/Quickstart+Windows
And downloaded mongodb.dll also
Mongo mongo = new Mongo();
mongo.Connect();
gives me the error
Failed to connect to server localhost:27017
Is i m missing something,plz let me know
You should use
var connectionString = "mongodb://localhost/?safe=true";
var server = MongoServer.Create(connectionString);
var database = server.GetDatabase("test");
Related
In a C# application, I know using ADO.NET we can execute a backup command like this:
BACKUP DATABASE MyDb TO DISK='C:\\MyDb.bak'
and take a database backup and store it at some given location.
I want to take backup of database in-memory i.e. return the backup script content (schema and data) which I can later save as .sql file at some location.
Is this possible?
I achieved it using SQL Server Management Objects (SMO). Thanks to all the friends who helped in comments.
First, install Microsoft.SqlServer.SqlManagementObjects from nuget package manager.
The working code:
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
var script = new StringBuilder();
Server server = new Server(new ServerConnection(new SqlConnection(connectionString)));
Database database = server.Databases[databaseName];
ScriptingOptions options = new ScriptingOptions
{
ScriptData = true,
ScriptSchema = true,
ScriptDrops = false,
Indexes = true,
IncludeHeaders = true
};
foreach (Table table in database.Tables)
{
foreach (var statement in table.EnumScript(options))
{
script.Append(statement);
script.Append(Environment.NewLine);
}
}
File.WriteAllText(backupPath + databaseName + ".sql", script.ToString());
I'm using Xunit for writing test cases and using ABP framework which is built on top of Asp.Net Core 2.0. I want to connect to my local DB instead of memory DB so that I can verify the records while running test cases.
public static void Register(IIocManager iocManager)
{
RegisterIdentity(iocManager);
var builder = new DbContextOptionsBuilder<MyCompanyDbContext>();
var inMemorySqlite = new SqliteConnection("Data Source=:memory:");
builder.UseSqlite(inMemorySqlite);
inMemorySqlite.Open();
iocManager.IocContainer.Register(
Component
.For<DbContextOptions<MyCompanyDbContext>>()
.Instance(builder.Options)
.LifestyleSingleton()
);
new MyCompanyDbContext(builder.Options).Database.EnsureCreated();
}
So to connect with my local DB I have made the below change, But its giving error. I'm using the same connection string in the application at other places and it works fine.
var inMemorySqlite = new SqliteConnection("Server=.\\SQLEXPRESS; Database=MyLocalDb; Trusted_Connection=True;");
You are trying to use a Non SQLite connection string with a SqliteConnection object.
If the intention is connect to an actual db then the connection string should refer to an actual db file
var optionsBuilder = new DbContextOptionsBuilder<MyCompanyDbContext>();
var connectionString = "Data Source=MyRealLocalDb.db"; //use actual path
optionsBuilder.UseSqlite(connectionString);
//...
Reference Configuring a DbContext
I want to authenticate to MongoDB with C# not through passing the Connection String/Credentials on the MongoClient() instance. It's like we do it on MongoDB Shell, We call monog -> db.auth(<username>,<password>) it means Connect to database first and authenticate after that.
Write C# Code
This is my code:
var mongoClient = new MongoClient();
var testDB = mongoClient.GetDatabase("test");
string username = txtUserName.Text;
string password = txtPassword.Password;
// Check password
var cmd = new BsonDocument("authenticate", new BsonDocument
{
{"username",username },
{"password",password }
});
var queryResult = testDB.RunCommand<BsonDocument>(cmd);
My Code connect to MongoDB and call the authenticate Database Command (described Here. It's not the db.auth() Shell method)to login with it
Run MongoDB with --auth option.
Run my Code.
After step 3, I encountered this problem. My code say
Additional information: Command authenticate failed: field missing/wrong type in received authenticate command.
I have read MongoDB documents (Also the link I added above) I can't find What I was missing.
I think you can use a JsonCommand to call eval function to execute db.auth function like this - not tested -:
var command = new JsonCommand<BsonDocument>(#"{ eval: ""db.auth(\""username\"", \""password\"");"" }");
var result = db.RunCommand(command);
I am trying to programmatically create a new database using SMO in C#. For this project, I do not want the .mdf/.ldf files placed in the default folder
"C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQL2008R2\MSSQL\DATA". I have not found anything on the web that tells how to modify the setting for the file location.
I get a failed operation exception when I run the following code:
Server srv = new Server(serverName.Text);
var db = new Database(srv, dbName.Text);
db.Create();
DataFile df = new DataFile(db.FileGroups["PRIMARY"],
dbName.Text, pathText.Text + dbName.Text + "_data.mdf");
df.Create();
LogFile lf = new LogFile(db, "Log01", pathText.Text + dbName.Text + "_log.ldf");
lf.Create();
The exception occurs at the df.Create(); line.
Any ideas?
I think this one answers the question for you.
Use SMO to Change SQL Server Database Default Locations
TTRider's Answer was:
You need to add information about Data and Log files explicitly:
TTRider's answer in the linked question points in the right direction, but is incomplete. Using some additional info from this post I was able to get it working (tested with SMO 2016 libraries).
private void CreateDatabase(string connectionString, string databaseName, string dataFilePath)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
ServerConnection serverConnection = new ServerConnection(sqlConnection);
Server sqlServer = new Server(serverConnection);
Database smoDatabase = new Database(sqlServer, databaseName);
string dataFileName = string.Format("{0}_Data", databaseName);
string dataFileFullPath = Path.ChangeExtension(Path.Combine(dataFilePath, dataFileName), ".mdf");
string logFileName = string.Format("{0}_Log", databaseName);
string logFileFullPath = Path.ChangeExtension(Path.Combine(dataFilePath, logFileName), ".ldf");
FileGroup fileGroup = new FileGroup(smoDatabase, "PRIMARY");
smoDatabase.FileGroups.Add(fileGroup);
DataFile dataFile = new DataFile(fileGroup, dataFileName, dataFileFullPath);
dataFile.IsPrimaryFile = true;
fileGroup.Files.Add(dataFile);
LogFile logFile = new LogFile(smoDatabase, logFileName, logFileFullPath);
smoDatabase.LogFiles.Add(logFile);
smoDatabase.Create();
serverConnection.Disconnect();
}
}
Is there is any way by which we can rename a column in MS Access dynamically from C#?
I know its simple in SQL Server but which is the best approach to do the same in Access programmatically?
For an Access 2003 database file, you can use good old Jet DAO if your application is running as 32-bit:
// test data
string tableName = "Members";
string oldFieldName = "Photo";
string newFieldName = "Photograph";
// COM Reference required in C# project:
// Microsoft DAO 3.6 Object Library
//
var dbe = new DAO.DBEngine();
DAO.Database db = dbe.OpenDatabase(#"C:\Users\Public\mdbTest.mdb");
DAO.Field fld = db.TableDefs[tableName].Fields[oldFieldName];
fld.Name = newFieldName;
db.Close();
To operate on an .accdb file, or to perform the operation from a C# application that is running as 64-bit, the newer Access Database Engine (a.k.a "ACE") needs to be installed. Then the code would be:
// test data
string tableName = "Members";
string oldFieldName = "Photo";
string newFieldName = "Photograph";
// COM Reference required in C# project:
// Microsoft Office 14.0 Access Database Engine Object Library
//
var dbe = new Microsoft.Office.Interop.Access.Dao.DBEngine();
Microsoft.Office.Interop.Access.Dao.Database db = dbe.OpenDatabase(#"C:\Users\Public\accdbTest.accdb");
Microsoft.Office.Interop.Access.Dao.Field fld = db.TableDefs[tableName].Fields[oldFieldName];
fld.Name = newFieldName;
db.Close();