Script Component - ODBC exception password incorrect - package validation - sql-server

I'm trying to insert some rows into Filemaker using Script Component. I followed this article Creating an ODBC Destination with the Script Component
When I edit the script here I set the connection string:
public override void AcquireConnections(object Transaction)
{
string connectionString;
//connectionString = this.Connections.FmConnection.ConnectionString;
odbcConn = new OdbcConnection("uid=someUID;Dsn=FM;pwd=somepassword");
odbcConn.Open();
}
I get the connection string from the this.Connections object and set it to the new OdbcConnection object. This does not work as I keep getting the exception. I tried setting the connection string manually as you can see above. I still get the exception.
In other parts of my package I use the connection manager to Filemaker and it works. Just not in this script component.
The exceptions I'm getting is:
Error at MyPackageName: [Filemaker] Password Incorrect
What is wrong?

Related

NpgsqlConnection : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host

I am getting error 'Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.' when connecting to PostgreSQL db from .net console application. As far as I did R&D and tried different things, I found that it may be because of = in password as other connection string works fine that doesn't have = in password. Is there any way to pass = in password tried sending %3D instead of = but it didn't work. Password is abc=xyz. Issue looks like with Password=abc=xyz, tried changing it to Password=abc%3Dxyz as well. pgcon.Open(); gives this error.
string pgconnectionstring="Server=someserver.azure.com;Username=dev#postgres;Database=dbname;Port=5432;Password=abc=xyz;SSLMode=Require";
using (NpgsqlConnection pgcon = new NpgsqlConnection(pgconnectionstring))
{
pgcon.Open();
}
NpgsqlConnection doesn't have property password to be set from outside, Is there any way to handle = or other special chars or set password differently?
Issue was not because of =, It was because of DB name. Seems like DB name should be case sensitive. The actual db name is Field-Service. And I was setting it like Field-service, s in small which led to the issue. Though exception message led to wrong direction as it gave error connection closed by remote which generally comes in case of wrong password instead should have given something like DB doesn't exists.

Using SQL Server Authentication to connect to SSRS from a WinForms Application

I'm busy testing SSRS to see if it's a viable alternative to our current reporting solution. I've set up SSRS on my local machine and have developed a working report using SQL Server Report Builder. Now what I'm trying to do is to call the report from within a WinForms application and display it in a ReportViewer control. The problem is that I've set up SQL Server to use SQL Server Authentication and I'm struggling to figure out how to connect to it programmatically.
The code I've pieced together so far looks like this:
Imports Microsoft.Reporting.WinForms
Public Class frmMain
Public v_report_name As String = "TestReport"
Public v_report_server As String = "http://elnah-ict-dt006:80"
Public v_report_path As String = "/reports_SSRS/"
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'create parameter array
Dim paramlist As New List(Of Microsoft.Reporting.WinForms.ReportParameter)
'create a specific parameter required by the report
Dim param1 As New Microsoft.Reporting.WinForms.ReportParameter("ClientID")
'add values to the parameter here we use a variable that holds the parameter value
param1.Values.Add("0279")
'add parameter to array
paramlist.Add(param1)
'Set the processing mode for the ReportViewer to Remote
ReportViewer1.ProcessingMode = ProcessingMode.Remote
'use the serverreport property of the report viewer to select a report from a remote SSRS server
ReportViewer1.ServerReport.ReportServerUrl = New System.Uri(v_report_server)
ReportViewer1.ServerReport.ReportPath = v_report_path & v_report_name
'select where the report should be generated with the report viewer control or on the report server using the SSRS service.
'Me.ReportViewer1.ProcessingMode = Microsoft.Reporting.WinForms.ProcessingMode.Remote
'add the parameterlist to the viewer
ReportViewer1.ServerReport.SetParameters(paramlist)
Me.ReportViewer1.RefreshReport()
End Sub
End Class
When it hits the SetParameters line towards the bottom, it gets the following error message:
Microsoft.Reporting.WinForms.Internal.Soap.ReportingServices2005.Execution.RSExecutionConnection.MissingEndpointException
HResult=0x80131500
Message=The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version.
Source=Microsoft.ReportViewer.WinForms
I've tried to find examples of how to set the username and password but from what I can tell, most examples are focused on using Windows Authentication. I've tried the following line but it doesn't work:
ReportViewer1.ServerReport.ReportServerCredentials = New ReportServerCredentials("SA", "mypassword")
I haven't worked in VB.NET for ages so please excuse any obvious errors.
Here's some code from a Web Forms project I was part of the team for recently:
private void SetCredentials()
{
var userName = ConfigurationManager.AppSettings["SSRSUserName"];
var passwordEncrypted = ConfigurationManager.AppSettings["SSRSUserPasswordEncrypted"];
var passwordPlainText = SI.Crypto3.Crypto.Decrypt(passwordEncrypted, PASSPHRASE);
var domain = ConfigurationManager.AppSettings["SSRSUserDomain"];
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(passwordPlainText) && !string.IsNullOrEmpty(domain))
{
this.EventsHubReportViewer.ServerReport.ReportServerCredentials = new ReportServerCredentials(userName, passwordPlainText, domain);
}
}
That's C# but hopefully you can see that the important part is that last line. I think that the equivalent in your case should be:
ReportViewer1.ServerReport.ReportServerCredentials = New ReportServerCredentials(userName, password, domain)
The domain value can be an empty String if your on the same domain as the server.
EDIT:
I looked more closely and the ReportServerCredentials class that code is using is one of our own. In your case, you can use the Microsoft.ReportViewer.WinForms.ReportServerCredentials class, which I don't think has a constructor like that. Looking at the documentation for the NetworkCredentials property of that type indicates that you need to do this:
Dim credentials As New NetworkCredential(userName, password, domain)
ReportViewer1.ServerReport.ReportServerCredentials.NetworkCredentials = credentials

JDBC DriverManager trying to use non specified Oracle driver

I am trying to connect to an Oracle Database using the java.sql.DriverManager in a JSF application. I am using a Tomcat v7 with ojdbc5.jar.
I have a very simple sample project that consists of nothing else than this piece of java code:
String url = "jdbc:oracle:thin:#DBSERV:DBPORT:DBSID";
String user = "account_admin";
String password = "my_assword";
Connection connection = null;
try {
Class.forName("oracle.jdbc.OracleDriver");
connection = DriverManager.getConnection(url, user, password);
connection.close();
} catch ..
...
Executed I get the following error:
java.lang.NoClassDefFoundError: Could not initialize class oracle.jdbc.driver.OracleDriver
Infact the class specified there "oracle.jdbc.driver.OracleDriver" is deprecated...and I can't change the Tomcat configuration. Therefore I specified "oracle.jdbc.OracleDriver" which loads just fine.
So the question is: Why does the DriverManager tries to load the "wrong" oracle driver, although I am loading another one?
I also tried as an alternative to Class.forName the following:
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
That does not change anything though. I also checked for the registered drivers in the following way:
Enumeration<Driver> driverList = DriverManager.getDrivers();
while(driverList.hasMoreElements()){
Driver driver = driverList.nextElement();
System.out.println(driver.getClass().toString());
}
The output:
class sun.jdbc.odbc.JdbcOdbcDriver
class oracle.jdbc.OracleDriver
So the desired driver seems to be registered, no trace of the deprecated "oracle.jdbc.driver.OracleDriver".
Thank you for any help
My problem just disappeared when I restarted the container. I can't explain why that is though.

NHibernate with custom sql-insert vs catching procedure raised exceptions and out params

I have mapped classes with custom sql (insert, delete, update) through procedure calls. But, I noticed that when my insert procedure fails raising exception, the GenericAdoException from NHibernate doesn't have my message raised from the procedure.
But, all raised exceptions from procedures for delete and update is catched well, only the insert procedure hasn't its exception message catched.
Is that a limitation or a bug of NHibernate 3.2.4 when we use "native" generator for ids combined with custom sql ?
I'm searching also ways to get some out parameters from that procedures like a timestamp to each event (insert, delete and update), the timestamp is generated inside procedures.
EDIT: OUT PARAMs - I found the "generated" option over properties mapping options which we can ask to NHibernate to get params from procedures. This means that these properties have genarated values. So I tried to use generated="always" and works for insert, update and delete operations. Example: <property name="MyProp" generated="always"/>
I found that sql server driver doesn't put the messages raised by stored procedures into the SqlException when you run these stored procedures with ExecuteReader(). On the other hand NHibernate executes the custom sql-insert with ExecuteReader() (I debbuged its source code) and I guess it's right and necessary to get the key when it's mapped with native (or identity), my case.
Well, and now what to do ? I found also (hard to found) that the SqlConnection has a event called "InfoMessage" in which you can receive (catch) all messages sent from your stored procedures (raiserror). Now this is possible to "catch" these messages, but how to make them cross NHibernate core and be received by our application when we insert something session.save() ?
Altough we have access to session and so to the connection (SqlConnection) the messages was already lost, because them are only received by the delegate assigned to the event SqlConnection.InfoMessage before of its occurrence.
To solve this, I tried two approaches:
In the first I projected a way to register the delegate inside DriverConnectionProvider.GetConnection() and this delegate would store the messages on the thread context associating it with the connection, so these messages could be getted later.
In the second and the one choosed, I implemented IDbConnection and IDbCommand wrapping inside them the SqlConnection and SqlCommand (but I think the NHibernate has a bug because in some places it references DbConnection instead IDbConnection - like in ManagedProviderConnectionHelper, so I had to extend from DbConnection and DbCommand instead).
Inside my CustomSqlConnection I register the delegate and store the messages for later use.
This is working ! Work as standalone driver (ADO) either as a NHibernate driver.
The idea is:
public class CustomSqlConnection : DbConnection, IDbConnection {
private SqlConnection con;
private StringBuilder str = new StringBuilder(0);
public CustomSqlConnection() {
con = new SqlConnection();
con.InfoMessage += OnInfoMessage;
}
private void OnInfoMessage(object sender, SqlInfoMessageEventArgs e) {
if (str.Length > 0) {
str.Append("\n");
}
str.Append(e.Message);
}
public string FetchMessage() {
string msg = Message;
str.Clear();
return msg;
}
...
...
}
EDIT: The hard step is to implement all operations from DdConnection and Dbcommand, repassing the call to the sql instance (look the field con above), so:
...
public override void Open() {
con.Open();
}
...

"Cannot drop database because it is currently in use". How to fix?

Having this simple code I get "Cannot drop database "test_db" because it is currently in use" (CleanUp method) as I run it.
[TestFixture]
public class ClientRepositoryTest
{
private const string CONNECTION_STRING = "Data Source=.;Initial Catalog=test_db;Trusted_Connection=True";
private DataContext _dataCntx;
[SetUp]
public void Init()
{
Database.SetInitializer(new DropCreateDatabaseAlways<DataContext>());
_dataCntx = new DataContext(CONNECTION_STRING);
_dataCntx.Database.Initialize(true);
}
[TearDown]
public void CleanUp()
{
_dataCntx.Dispose();
Database.Delete(CONNECTION_STRING);
}
}
DataContext has one property like this
public DbSet<Client> Clients { get; set; }
How can force my code to remove database?
Thanks
The problem is that your application probably still holds some connection to the database (or another application holds connection as well). Database cannot be deleted where there is any other opened connection. The first problem can be probably solved by turning connection pooling off (add Pooling=false to your connection string) or clear the pool before you delete the database (by calling SqlConnection.ClearAllPools()).
Both problems can be solved by forcing database to delete but for that you need custom database initializer where you switch the database to single user mode and after that delete it. Here is some example how to achieve that.
I was going crazy with this! I have an open database connection inside SQL Server Management Studio (SSMS) and a table query open to see the result of some unit tests. When re-running the tests inside Visual Studio I want it to drop the database always EVEN IF the connection is open in SSMS.
Here's the definitive way to get rid of Cannot drop database because it is currently in use:
Entity Framework Database Initialization
The trick is to override InitializeDatabase method inside the custom Initializer.
Copied relevant part here for the sake of good DUPLICATION... :)
If the database already exist, you may stumble into the case of having
an error. The exception “Cannot drop database because it is currently
in use” can raise. This problem occurs when an active connection
remains connected to the database that it is in the process of being
deleted. A trick is to override the InitializeDatabase method and to
alter the database. This tell the database to close all connection and
if a transaction is open to rollback this one.
public class CustomInitializer<T> : DropCreateDatabaseAlways<YourContext>
{
public override void InitializeDatabase(YourContext context)
{
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction
, string.Format("ALTER DATABASE [{0}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE", context.Database.Connection.Database));
base.InitializeDatabase(context);
}
protected override void Seed(YourContext context)
{
// Seed code goes here...
base.Seed(context);
}
}
This is a really aggressive database (re)initializer for EF code-first with migrations; use it at your peril but it seems to run pretty repeatably for me. It will;
Forcibly disconnect any other clients from the DB
Delete the DB.
Rebuild the DB with migrations and runs the Seed method
Take ages! (watch the timeout limit for your test framework; a default 60 second timeout might not be enough)
Here's the class;
public class DropCreateAndMigrateDatabaseInitializer<TContext, TMigrationsConfiguration>: IDatabaseInitializer<TContext>
where TContext: DbContext
where TMigrationsConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration<TContext>, new()
{
public void InitializeDatabase(TContext context)
{
if (context.Database.Exists())
{
// set the database to SINGLE_USER so it can be dropped
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "ALTER DATABASE [" + context.Database.Connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
// drop the database
context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "USE master DROP DATABASE [" + context.Database.Connection.Database + "]");
}
var migrator = new MigrateDatabaseToLatestVersion<TContext, TMigrationsConfiguration>();
migrator.InitializeDatabase(context);
}
}
Use it like this;
public static void ResetDb()
{
// rebuild the database
Console.WriteLine("Rebuilding the test database");
var initializer = new DropCreateAndMigrateDatabaseInitializer<MyContext, MyEfProject.Migrations.Configuration>();
Database.SetInitializer<MyContext>initializer);
using (var ctx = new MyContext())
{
ctx.Database.Initialize(force: true);
}
}
I also use Ladislav Mrnka's 'Pooling=false' trick, but I'm not sure if it's required or just a belt-and-braces measure. It'll certainly contribute to slowing down the test more.
None of those solutions worked for me. I ended up writing an extension method that works:
private static void KillConnectionsToTheDatabase(this Database database)
{
var databaseName = database.Connection.Database;
const string sqlFormat = #"
USE master;
DECLARE #databaseName VARCHAR(50);
SET #databaseName = '{0}';
declare #kill varchar(8000) = '';
select #kill=#kill+'kill '+convert(varchar(5),spid)+';'
from master..sysprocesses
where dbid=db_id(#databaseName);
exec (#kill);";
var sql = string.Format(sqlFormat, databaseName);
using (var command = database.Connection.CreateCommand())
{
command.CommandText = sql;
command.CommandType = CommandType.Text;
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
}
}
I try adding Pooling=false like Ladislav Mrnka said but always got the error.
I'm using Sql Server Management Studio and even if I close all the connection, I get the error.
If I close Sql Server Management Studio then the Database is deleted :)
Hope this can helps
I got the same error. In my case, I just closed the connection to the database and then re-connected once the in my case the new model was added and a new controller was scaffolded. That is however a very simple solution and not recommended for all scenarios if you want to keep your data.
I got the same problem back then. Turns out the solution is to close the connection in Server Explorer tab in Visual Studio. So maybe you could check whether the connection is still open in the Server Explorer.
Its simple because u're still using the same db somewhere, or a connection is still open.
So just execute "USE master" first (if exist, but usually is) and then drop the other db. This always should work!
Grz John

Resources