Fluent NHibernate ExportSchema without connection string - database

I want to generate a database script without having an actual database connection string declared.
To do this for now i use NHibernate ExportSchema bases on a NHibernate configuration generated with Fluent NHibernate this way (during my ISessionFactory creation method):
FluentConfiguration configuration = Fluently.Configure();
//Mapping conf ...
configuration.Database(fluentDatabaseProvider);
this.nhibernateConfiguration = configuration.BuildConfiguration();
returnSF = configuration.BuildSessionFactory();
//Later
new SchemaExport(this.nhibernateConfiguration)
.SetOutputFile(filePath)
.Execute(false, false, false);
fluentDatabaseProvider is a FluentNHibernate IPersistenceConfigurer which is needed to get proper sql dialect for database creation.
When factory is created with an existing database, everything works fine.
But what i want to do is to create an NHibernate Configuration object on a selected database engine without a real database behind the scene... And i don't manage to do this.
If anybody has some idea.

This is what I used. My mistake was calling BuildSessionFactory which tries to connect to the database:
var config = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008)
.Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<SessionManager>());
new SchemaExport(config.BuildConfiguration())
.SetOutputFile(filedestination)
.Create(false, false);

Try using:
.Create(false, false);
inplace of
.Execute(false, false, false);
Do not add the connectionstring property to the IPersistenceConfigurer (fluentDatabaseProvider).

Related

Entity Framework 6 - How to update customer's database with CodeFirst migration

My team develops an application which deploys MSSQL database at customer's system. We encountered a problem with using migrations to update the customer's database structure .
We can't use automated migrations because more than one instance of the app can run on the same database so if one of instances gets updated and therefore changes the model and therefore the structure of database the others change it back so neither of them can work on the database.
We can't use nonautomated migrations because we have no access to customer's database to run the update-database command.
The question is what's the best approach to keep the database and the model always up to date on the level of code ?
You have to use the migrate to latest version strategy. This apporach allows you to automatically update the database when the model is changed:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, MyMagicDatabaseConfiguration>()`);
public class MyMagicDatabaseConfiguration : DbMigrationsConfiguration<MyDbContext>
{
public MyMagicDatabaseConfiguration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
}
// !!Force the initialization. this will execute the update!!
MyDb.Context.Database.Initialize(true);
This works fine if you are using MS SQL Server
The problem you are using MySql you have to do everything by your self!:
var migrator = new DbMigrator(new DbMigrationsConfiguration ());
migrator.Update();
// In the migrtaions directory:
public partial class MyMigration : DbMigration
{
public override void Up()
{
AddColumn("dbo.MyTable", "AnyName", c => c.Boolean(nullable: false));
}
public override void Down()
{
DropColumn("dbo.MyTable", "AnyName");
}
}
This is not an easy work and I do not recommeded you to do it. Just use SQL Server apporach this will safe your time.
one note more: Magic migration sometimes does not working(Complex changes with keys), if the changes can not be handled automatically.
You can also use migration to a target version:
var configuration = new DbMigrationsConfiguration();
var migrator = new DbMigrator(configuration);
migrator.Update("HereMigrationId");
var scriptor = new MigratorScriptingDecorator(migrator);
var migrationScript = scriptor.ScriptUpdate(sourceMigration: null, targetMigration: "HereMigrationId");
In your case you need migration to target version.
with the decrator you can modifiy the migration script during the migration.

Grails 2.4.4 Multiple datasources, separate drivers, IntegrationSpec

I am attempting to use multiple datasources in a Grails 2.4.4 project. According to the docs, this should be possible:
http://www.grails.org/doc/2.4.4/guide/conf.html#multipleDatasources
My primary dataSource (the one I want to use for all domain classes) is using H2 at the moment, as configured by the default DataSource.groovy configuration. My second, read-only datasource is SQL Server, and I tried to declare it as follows at the top level of my DataSource.groovy config (shared by all environments):
ds {
pooled = true
dialect = "org.hibernate.dialect.SQLServer2008Dialect"
driverClassName = "net.sourceforge.jtds.jdbc.Driver"
url = "jdbc:jtds:sqlserver://myserver:1433/mydb;domain=mydomain;useNTLMv2=true;user=myuser"
dbCreate = "none"
}
(Don't let the URL throw you off - I'm just having to use Windows Auth with JTDS. I've tested this via third-party clients as well.)
I inject this into my service class and use it, and everything appears to hook up well:
def dataSource_ds
def serviceMethod(){
Sql ds = new Sql(dataSource_ds)
String query = "SELECT ... "
def results = ds.rows(query)
println "Results are ${results.size()}"
return "Some value"
}
But when I try to access this from an IntegrationSpec-backed Integration Test, I noticed that I was getting "schema not found" errors for valid schemas referred to by my query string, such as "dbo". And the stack trace of any errors from this setup looks like this:
org.h2.jdbc.JdbcSQLException: Schema "DBO" not found; SQL statement:
...
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.get(DbException.java:169)
at org.h2.message.DbException.get(DbException.java:146)
at org.h2.command.Parser.readTableOrView(Parser.java:4774)
at org.h2.command.Parser.readTableFilter(Parser.java:1083)
at org.h2.command.Parser.parseSelectSimpleFromPart(Parser.java:1689)
at org.h2.command.Parser.parseSelectSimple(Parser.java:1796)
at org.h2.command.Parser.parseSelectSub(Parser.java:1683)
at org.h2.command.Parser.parseSelectUnion(Parser.java:1526)
at org.h2.command.Parser.parseSelect(Parser.java:1514)
at org.h2.command.Parser.parsePrepared(Parser.java:404)
at org.h2.command.Parser.parse(Parser.java:278)
at org.h2.command.Parser.parse(Parser.java:250)
at org.h2.command.Parser.prepareCommand(Parser.java:217)
at org.h2.engine.Session.prepareLocal(Session.java:414)
at org.h2.engine.Session.prepareCommand(Session.java:363)
...
Now why would THIS datasource be trying to use the H2 driver?
In case it's relevant, my Integration test looks like this:
void "serviceMethod" () {
when: "service method is called"
String response = myService.serviceMethod()
then: "we should get the appropriate text back"
response.equals("Some value")
}
If, in the Service class, I hard-code the connection using a constructor of the Groovy Sql object, the integration test works fine, and any stack traces go through the JTDS driver.But when I try to use the injected datasource, things are strange.
Any idea what I'm doing wrong here?
Just to close the loop on this and hopefully save someone pain on this oversight in the future:
Grails uses an in-memory database when running tests. Make sure to read up on the other differences between integration tests and production here:
http://www.grails.org/doc/latest/guide/testing.html#integrationTesting
This feature makes the use of external (read-only) datasources during any tests pretty interesting, but some of that is to be expected (a test which depends on an external datasource is not a very good test in the long run). I hope to refactor my app and its testing approach at some point (e.g., to use a simple DAO and mock that during the test), because I don't really care about asserting the contents of the external datasource from my app's tests.

How would I configure Effort Testing Tool to mock Entity Framework's DbContext withOut the actual SQL Server Database up and running?

Our team's application development involves using Effort Testing Tool to mock our Entity Framework's DbContext. However, it seems that Effort Testing Tool needs to be see the actual SQL Server Database that the application uses in order to mock our Entity Framework's DbContext which seems to going against proper Unit Testing principles.
The reason being that in order to unit test our application code by mocking anything related to Database connectivity ( for example Entity Framework's DbContext), we should Never need a Database to be up and running.
How would I configure Effort Testing Tool to mock Entity Framework's DbContext withOut the actual SQL Server Database up and running?
*
Update:
#gert-arnold We are using Entity Framework Model First approach to implement the back-end model and database.
The following excerpt is from the test code:
connection = Effort.EntityConnectionFactory.CreateTransient("name=NorthwindModel");
jsAudtMppngPrvdr = new BlahBlahAuditMappingProvider();
fctry = new BlahBlahDataContext(jsAudtMppngPrvdr, connection, false);
qryCtxt = new BlahBlahDataContext(connection, false);
audtCtxt = new BlahBlahAuditContext(connection, false);
mockedReptryCtxt = new BlahBlahDataContext(connection, false);
_repository = fctry.CreateRepository<Account>(mockedReptryCtxt, null);
_repositoryAccountRoleMaps = fctry.CreateRepository<AccountRoleMap>(null, _repository);
The "name=NorthwindModel" pertains to our edmx file which contains information about our Database tables
and their corresponding relationships.
If I remove the "name=NorthwindModel" by making the connection like the following line of code, I get an error stating that it expects an argument:
connection = Effort.EntityConnectionFactory.CreateTransient(); // throws error
Could you please explain how the aforementioned code should be rewritten?
You only need that connection string because Effort needs to know where the EDMX file is.
The EDMX file contains all information required for creating an inmemory store with an identical schema you have in your database. You have to specify a connection string only because I thought it would be convenient if the user didn't have to mess with EDMX paths.
If you check the implementation of the CreateTransient method you will see that it merely uses the connection string to get the metadata part of it.
public static EntityConnection CreateTransient(string entityConnectionString, IDataLoader dataLoader)
{
var metadata = GetEffortCompatibleMetadataWorkspace(ref entityConnectionString);
var connection = DbConnectionFactory.CreateTransient(dataLoader);
return CreateEntityConnection(metadata, connection);
}
private static MetadataWorkspace GetEffortCompatibleMetadataWorkspace(ref string entityConnectionString)
{
entityConnectionString = GetFullEntityConnectionString(entityConnectionString);
var connectionStringBuilder = new EntityConnectionStringBuilder(entityConnectionString);
return MetadataWorkspaceStore.GetMetadataWorkspace(
connectionStringBuilder.Metadata,
metadata => MetadataWorkspaceHelper.Rewrite(
metadata,
EffortProviderConfiguration.ProviderInvariantName,
EffortProviderManifestTokens.Version1));
}

Insert data into external MSSQL database through Yii Framework

I'm using Yii Framework to create my project. I need to export some data from MySQL (my project) to an external Microsoft SQL server which is on the same network.
Basically, the user needs to click on a button (which will do the export-insert) in my view and the results should be displayed - Success (if the query has been successful) or Failure (if something went wrong).
The results part is quite easy as I'll be using 'setFlash' to display the appropriate message but I want to know how to insert data into an external database through Yii.
Do you have any idea how this can be done?
Well, I agree with #SuVeRa on the first part of defining two db instances in the config.php but i don't think the sql Commands part is necessary (Plus i hate writing sql :D )
Instead you can do:
class SomeModel extends CActiveRecord
{
...
// Override the getDbConnection() function to use the ms sql db connection
public function getDbConnection()
{
return Yii::app()->ms_sql_db_connection; // The name of the connection in config.php
}
public function transfer()
{
// Here you can do all the transferring logic using normal Yii Active Record functions
}
}
Check out the docs on getDbConnection().

SQL Reporting Services DataConnection Update

Is it possible to change the connection string of a published sql reporting services report? I can see the binary field called DataSource in the ReportServer database, but since it's stored as binary I don't think it's easily updatable.
Do I need to republish the report with the correct data source? I'm hoping not since I do not want to have to install VS2003.
EDIT: The client is running SQL Server 2000 Reporting Services with all of the service packs installed.
SQL Reporting Services 2000 has a [web service](http://msdn.microsoft.com/en-us/library/aa274396(SQL.80).aspx) that you can use to change the data source. Given that, the following, allows for changing of a data source to a shared data source. This was [adapted from MSDN](http://msdn.microsoft.com/en-us/library/aa225896(SQL.80).aspx).
// Create our reporting services class
ReportingService theRS = new ReportingService();
theRS.Credentials = System.Net.CredentialCache.DefaultCredentials;
// We need to setup a data source reference to an existing shared data source
DataSourceReference theDSRef = new DataSourceReference();
theDSRef.Reference = "/Path/To/ExistingSharedDataSource";
DataSource[] theDSArray = new DataSource[1];
DataSource theDS = new DataSource();
theDS.Item = (DataSourceReference)theDSRef;
theDS.Name = "NameOfSharedDataSource";
theDSArray[0] = theDS;
try
{
// Attempt to change the data source of the report
theRS.SetReportDataSources("/Path/To/ReportName", theDSArray);
Console.Out.WriteLine("We have changed the data source");
}
catch (System.Web.Services.Protocols.SoapException e)
{
Console.Out.WriteLine(e.Message);
Console.Out.WriteLine(e.Detail.InnerXml.ToString());
}
In this example, the ReportingService class is taken from the Proxy class that I generated to talk to the web service, which is described [here](http://msdn.microsoft.com/en-us/library/aa256607(SQL.80).aspx).
I hope this helps some. Let me know if you're looking for something different.

Resources