ColdFusion 10 Client Variables not persistent when declaring this.clientStorage as a DSN - coldfusion-10

Upgrading a CF 5.x site to ColdFusion 10 u13...
These are code snippets not full files.
Application.cfc:
<cfset this.clientManagement = true>
<cfset this.clientStorage = "myCSDSN">
main.cfm
<cfset client.test = "testing 1 2 3">
<cfdump var="#client#" label="client">
clienttest.cfm
<cfdump var="#client#" label="client">
Start by loading main.cfm. You'll see this:
Now load clienttest.cfm in a new tab, same browser. You'll see this:
Notice that client.test is missing in clienttest.cfm. Yet the session management cookies are identical in both dumps.
Now change this line in Application.cfc:
<cfset this.clientStorage = "cookie">
Re-run main.cfm and then clienttest.cfm. Now client.test will appear in both dumps. Hitcount will also start to increment for each reload as well.
The data source myCSDSN exists and has the CDATA and CGLOBAL tables in them. The myCSDSN datasource has been set up in CF Administrator as a Client Variables storage mechanism (it isn't the default though). No new records are getting added to these tables.
Any ideas why this doesn't work with the datasource?
Any downsides to using the "cookie" storage option?

I deleted the CDATA and CGLOBAL tables and recreated them through the ColdFusion Administrator.
It started working with a DSN after that.
There was a database structure difference from ColdFusion 5 to ColdFusion 10.
[cfid] char(20) becomes [cfid] char(64) in both tables.

Related

What does the "dmlreadexception" error mean on Moodle live logs when I try to pull from an external db log? And any suggestions to fix?

I am trying to use the external database log plugin in Moodle to copy over the standard log table into an external database for easier access to do some analytics work.
I activated the external db log and added all correct settings on the settings page. I clicked "test connection" and it connected successfully and returned the table column headers successfully. But if I click around and make some logs, they are visible in the standard log store but my external db table is still empty.
So I tried connecting to my external db locally in TablePlus using identical credentials as I put in the external db log store settings, and I could connect and write successfully.
Next I went into the live logs and picked standard logs, and they showed up just fine. Then I clicked on external db logs (nothing inside except for 2 manually entered rows of data), and got this error:
URL: https://ohsu.mrooms3.net/
Debug info: ERROR: syntax error at or near "{" LINE 1: SELECT COUNT('x') FROM {OpenLMSLog} WHERE courseid = $1 AND ... ^ SELECT COUNT('x') FROM {OpenLMSLog} WHERE courseid = $1 AND timecreated > $2 AND anonymous = $3 [array ( 0 => '1', 1 => 1604556625, 2 => 0, )] Error code: dmlreadexception
Stack trace:
* line 486 of /lib/dml/moodle_database.php: dml_read_exception thrown
* line 329 of /lib/dml/pgsql_native_moodle_database.php: call to moodle_database->query_end()
* line 920 of /lib/dml/pgsql_native_moodle_database.php: call to pgsql_native_moodle_database->query_end()
* line 1624 of /lib/dml/moodle_database.php: call to pgsql_native_moodle_database->get_records_sql()
* line 1697 of /lib/dml/moodle_database.php: call to moodle_database->get_record_sql()
* line 1912 of /lib/dml/moodle_database.php: call to moodle_database->get_field_sql()
* line 1895 of /lib/dml/moodle_database.php: call to moodle_database->count_records_sql()
* line 262 of /admin/tool/log/store/database/classes/log/store.php: call to moodle_database->count_records_select()
* line 329 of /report/loglive/classes/table_log.php: call to logstore_database\log\store->get_events_select_count()
* line 48 of /report/loglive/classes/table_log_ajax.php: call to report_loglive_table_log->query_db()
* line 59 of /report/loglive/classes/renderer_ajax.php: call to report_loglive_table_log_ajax->out()
* line 462 of /lib/outputrenderers.php: call to report_loglive_renderer_ajax->render_report_loglive()
* line 53 of /report/loglive/loglive_ajax.php: call to plugin_renderer_base->render()
This is the only error message I get even after turning on debugging in the developer settings. My goal is to successfully configure an external db to track logs, but due to a lack of error messages when testing the connection it is hard to debug.
Environment configuration: Open LMS 3.8 MP2 (Build: 20201008)
The external db is a postgres db so we set it on the postgres driver.
It looks like the SQL used by the external db log store plugin is not compatible with Postgres, despite using the Postgres driver in the external db log store plugin settings, as shown by the '{' error in the SQL shown in the question. See here for documentation.
To fix this, we used MariaDB instead of Postgres, and we ended up getting the external db log store working.
Another note, you have to match your columns and data types exactly to the schema in the Moodle db, and then you have to set the ID column of your db table to auto-increment. If you don't know what the schema looks like, there is an Admin SQL interface under "Reports" that lets you run SQL. On the side, there a button to view the schema for any table in the db.

Failure to find table when using multiple schemas in PostgreSQL

WPF PostgreSQL 11.1
Npgsql.PostgresException: '42P01: relation "testme" does not exist'
When attempting to use a PostgreSQL database with multiple schemas, I have defined the following connection strings in the App.config. Note that the only difference is in the SearchPath:
<system.data>
<DbProviderFactories>
<add name="Npgsql Data Provider" invariant="Npgsql" support="FF" description=".Net Framework Data Provider for Postgresql Server" type="Npgsql.NpgsqlFactory, Npgsql, Version=4.0.4.0, Culture=neutral" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<clear />
<add name="localconnection" providerName="Npgsql" connectionString="Server=127.0.0.1;Port=5432;Database=chaos;User Id=postgres;Password=****;Searchpath=nova" />
<add name="phoenixconnection" providerName="Npgsql" connectionString="Server=127.0.0.1;Port=5432;Database=chaos;User Id=postgres;Password=****;SearchPath=phoenix;" />
</connectionStrings>
The Npgsql data provider was installed using NuGet: Runtime Version:
v4.0.30319 Version: 4.0.4.0
In PostgreSQL, in the Phoenix schema:
CREATE TABLE phoenix.testme
(
name text COLLATE pg_catalog."default" NOT NULL
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default;
ALTER TABLE phoenix.testme
OWNER to postgres;
Using PgAdmin, displaying the testme table works without problem:
select * from phoenix.testme;
I have configured the WCF service using the above connection strings. Using PetaPoco, I write the following script:
public string SayHello()
{
string msg;
using (var db = new chaosDB("phoenixconnection"))
{
var m = db.ExecuteScalar<string>("select version()");
msg = string.Format("Hello from {0}", m);
m = db.ExecuteScalar<string>("select current_schema");
msg = string.Format("{0} Current Schema is {1}", msg, m);
var ss = db.ExecuteScalar<string>("show search_path");
var s = db.Fetch<string>("select * from testme"); <---THIS FAILS!
msg = string.Format("{0} I Am {1}", msg, m);
}
return msg;
}
All works correctly until the "select * from testme" is executed, when I receive the above error. Note: ss from "show search_path" returns correctly with "phoenix"
WHAT AM I DOING WRONG? How do I get this to work??
Any help is most appreciated?
After much head scratching the answer became self-evident. First I had reset the search_path in the database. This did not help. Then I rebuilt the POCO's with PetaPoco and quickly discovered that not only was the new table, "testme", not created, but nor were any POCO's. So, checking, the Database.tt file in PetaPoco showed it to have the wrong ConnectionStringName. Changing the ConnectionStringName to "phoenixconnection" allowed building the POCO's, but again failed to find the "testme" table.
Then the mistake became readily apparent, as stated above, both the "phoenixconnection" and the "localconnection" were pointed to the same port. From previous development, I had PostgreSQL v10.1 running on the same port as the newer PostgreSQL v11.1. Apparently, the first PostgreSQL v10.1 was receiving the connection (and not the newer PostgreSQL v11.1).
Going to services (services.msc) and shutting down v10.1 and running Database.TT now gave the error:
System.InvalidOperationException: Sequence contains more than one matching element
Apparently v10.1 (which I was using for development) only had ONE schema, but v11.1 has multiple schemas. I take the error message to mean that PetaPoco was seeing multiple tables with the same table name--i.e.,it was not distinguishing between schemas.
So, the problem is now solved.
Fix the ports! The older single-schema PostgreSQL v10.1 is kept on port: 5432.
The newer multiple-schema PostgreSQL is kept on port 5433. The v10.1 will be used for the POCO's.
Fix the connection strings in App.config of the WCF so that at run time, the WCF will use the newer v11.1. Once generated, LEAVE THE POCO'S alone and reference them in the WCF file.
Apparently, PetaPoco, can only work with one schema in generating its POCO's, but at runtime will read the connection strings from the App.Config of the WCF to execute its queries, etc. (So in the App.config where Database.TT resides, point PetaPoco to the "development" Database having only a single schema, but in the WCF environment, point the connection string to the new database with multiple schemas. The SearchPath of the connection string IS respected when running through Npgsql).
It would be nice if PetaPoco could generate POCO's specific to a schema in a multi-schema environment, but at the moment, I guess it can't :(
Addendum Note: It turns out that a given instance of PostgreSQL can have multiple DATABASES. So if the connection string for Npgsql is specific to a development database --i.e., a database with only one schema--then during development, PetaPoco works great to create the POCO's. These POCO's can then be directly used in a WCF Service project and uploaded to IIS website. The App.config files of the web site can then be directed to use the run-time database (again in the connection string) to the deployed database. All works well! :)

Define a database entry in DB2 db2dsdriver.cfg file that can access multiple databases

I currently use the CLI method of registering a node and then a database for that node (with CATALOG NODE / CATALOG DATABASE) to configure my DB2 CLI client to access our database server.
With a single registration of a database I can effectively register the default database but then when I connect in my application using SQLDriverConnect and use the "DATABASE=" option I can connect to other databases available on my server.
I would like to switch to the much easier to manage db2dsdriver.cfg configuration file, however I have been unable to configure it to allow a single to access multiple databases.
Some code to help clarify. My DB2 server instance has two databases defined like:
CREATE DATABASE DB_1 ON /opt/data/DB_1 USING CODESET UTF-8 TERRITORY US COLLATE USING SYSTEM
CREATE DATABASE DB_2 ON /opt/data/DB_2 USING CODESET UTF-8 TERRITORY US COLLATE USING SYSTEM
I register this server with my client CLI using these commands:
CATALOG TCPIP NODE DB_NODE remote example.server.com server 50000
CATALOG DB DB_1 as DB_1 at node DB_NODE
With that setup I can perform the following from my CLI application:
rc = SQLDriverConnect(hdbc, NULL, "DSN=DB_1;UID=dbtest1;PWD=zebco5;DATABASE=DB_1",
SQL_NTS, outStr, 128, &outSize, SQL_DRIVER_NOPROMPT);
or if I want to use the DB_2 database:
rc = SQLDriverConnect(hdbc, NULL, "DSN=DB_1;UID=dbtest1;PWD=zebco5;DATABASE=DB_2",
SQL_NTS, outStr, 128, &outSize, SQL_DRIVER_NOPROMPT);
Note I did not need to change the DSN, merely the "DATABASE" connection option.
Recently I found the db2dsdriver.cfg configuration file which I would rather use. To that end I created this and uncataloged my node and db from the cli:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<configuration>
<dsncollection>
<dsn alias="DB_1" name="DB_1" host="server.example.com" port="50000"/>
</dsncollection>
<databases>
<database name="DB_1" host="server.example.com" port="50000"/>
<database name="DB_2" host="server.example.com" port="50000"/>
</databases>
</configuration>
I can connect with this:
rc = SQLDriverConnect(hdbc, NULL, "DSN=DB_1;UID=dbtest1;PWD=zebco5;DATABASE=DB_1",
SQL_NTS, outStr, 128, &outSize, SQL_DRIVER_NOPROMPT);
just fine, but now using this to connect to DB_2:
rc = SQLDriverConnect(hdbc, NULL, "DSN=DB_1;UID=dbtest1;PWD=zebco5;DATABASE=DB_2",
SQL_NTS, outStr, 128, &outSize, SQL_DRIVER_NOPROMPT);
results in this error:
SQL0843N The server name does not specify an existing connection. SQLSTATE=08003
Which I understand, but seems like a regression in functionality from the old node/db registration mechanism.
I'm attempting to determine if the functionality I was using is supported with the configuration file and I am doing something wrong or if it just doesn't work that way?
Thank you for your help.

DB2 exception: Cannot create PoolableConnectionFactory SQLCODE=-142,

I keep having the following error in MobileFirst Platform 6.3:
Runtime: org.apache.commons.dbcp.SQLNestedException: Cannot create
PoolableConnectionFactory (DB2 SQL Error: SQLCODE=-142,
SQLSTATE=42612, SQLERRMC=null, DRIVER=4.19.26)
This is my adapter code:
var test2 = WL.Server.createSQLStatement("SELECT * FROM WSDIWC.WBPTRR1");
function getCEID(cnum) {
return WL.Server.invokeSQLStatement({
preparedStatement : test2,
parameters : []
});
}
And adapter XML:
<connectivity>
<connectionPolicy xsi:type="sql:SQLConnectionPolicy">
<!-- Example for using a JNDI data source, replace with actual data source
name -->
<!-- <dataSourceJNDIName>${training-jndi-name}</dataSourceJNDIName> -->
<!-- Example for using MySQL connector, do not forget to put the MySQL
connector library in the project's lib folder -->
<dataSourceDefinition>
<driverClass>com.ibm.db2.jcc.DB2Driver</driverClass>
<url>jdbc:db2://***</url>
<user>**</user>
<password>**</password>
</dataSourceDefinition>
</connectionPolicy>
</connectivity>
I have remove the url, user and password.
Hope you help me out on clarification about the current problem.
I already know that the sql is not accepted since it's just a simple query.
I have also research about z/OS DB2 that it has issue with same error code sqlcode=-142. http://answers.splunk.com/answers/117024/splunk-db-connect-db2.html
While you say that this is a "simple query", the exception error code mentions the following:
-142
THE SQL STATEMENT IS NOT SUPPORTED
Explanation
An SQL statement was detected that is not supported by the database.
The statement might be valid for other IBM® relational database
products or it might be valid in another context. For example,
statements such as VALUES and SIGNAL or RESIGNAL SQLSTATE can be used
only in certain contexts, such as in a trigger body or in an SQL
Procedure.
System action
The statement cannot be processed.
Programmer response
Change the syntax of the SQL statement or remove the statement from
the program.
You should review the DB2 SQL guidelines for how to achieve what you want to achieve, and also explain that in the question if you'd like further assistance. For example, are you sure "WSDIWC.WBPTRR1" is actually available?
I encountered this same problem with JDBC connections to mainframe DB2 in MobileFirst 6.3. Connections to DB2 LUW worked fine. It appears that default pool validationQuery is valid for DB2 LUW but not DB2 z/OS.
You can work around the bug by doing the data source configuration in the Liberty profile server.xml. From the Eclipse Servers view, expand MobileFirst Development Server and edit the Server Configuration. Add the driver and data source there; for example:
<library id="db2jcc">
<fileset dir="whereever" includes="db2jcc4.jar db2jcc_license_cisuz.jar"/>
</library>
<dataSource id="db2" jndiName="jdbc/db2">
<jdbcDriver libraryRef="db2jcc"/>
<properties.db2.jcc databaseName="mydb" portNumber="5021"
serverName="myserver" user="myuser" password="mypw" />
</dataSource>
Then reference it in your adapter XML under connectionPolicy:
<dataSourceJNDIName>jdbc/db2</dataSourceJNDIName>
A benefit of configuring data sources in server.xml (vs the adapter XML) is you have access to all data source, JDBC, and JCC properties. So if the connection pool gives you other problems, you can customize it or switch to another data source type, such as type="javax.sql.DataSource".

How to detach a LocalDB (SQL Server Express) file in code

When using LocalDB .mdf files in deployment you will often want to move, delete or backup the database file.
It is paramount to detach this file first as simply deleting it will cause errors because LocalDB still keeps a registration of it.
So how is a LocalDB .mdf file detached in code?
I had to string together the answer from several places, so I wil post it here:
Mind, manually detaching the .mdf file from Visual Studio is possible after manually deleting it before detachment by going through SQL Server Object Explorer.
''' <summary>
''' Detach a database from LocalDB. This MUST be done prior to deleting it. It must also be done after a inadvertent (or ill advised) manual delete.
''' </summary>
''' <param name="dbName">The NAME of the database, not its filename.</param>
''' <remarks></remarks>
Private Sub DetachDatabase(dbName As String)
Try
'Close the connection to the database.
myViewModel.CloseDatabase()
'Connect to the MASTER database in order to excute the detach command on it.
Dim connectionString = String.Format("Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True")
Using connection As New SqlConnection(connectionString)
connection.Open()
Dim cmd = connection.CreateCommand
'--Before the database file can be detached from code the workaround below has to be applied.
'http://web.archive.org/web/20130429051616/http://gunnalag.wordpress.com/2012/02/27/fix-cannot-detach-the-database-dbname-because-it-is-currently-in-use-microsoft-sql-server-error-3703
cmd.CommandText = String.Format("ALTER DATABASE [{0}] SET OFFLINE WITH ROLLBACK IMMEDIATE", dbName)
cmd.ExecuteNonQuery()
'--
'--Now detach
cmd.CommandText = String.Format("exec sp_detach_db '{0}'", dbName)
cmd.ExecuteNonQuery()
'--
End Using
Catch ex As Exception
'Do something meaningful here.
End Try
End Sub
I had the same issue and was thinking of how to deal with it.
There are 3 approaches.
Detach at the end of (or during) working with database
I didn't find the way to close connection in LinqToSQL, but actually it is not needed. Simply execute the following code:
var db = #"c:\blablabla\database1.mdf";
using (var master = new DataContext(#"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True"))
{
master.ExecuteCommand(#"ALTER DATABASE [{0}] SET OFFLINE WITH ROLLBACK IMMEDIATE", db);
master.ExecuteCommand(#"exec sp_detach_db '{0}'", db);
}
and make sure nothing will try to query db after (or you get it attached again).
Detach on start
Before you made any connection to db, detaching is as simple as:
var db = #"c:\blablabla\database1.mdf";
using (var master = new DataContext(#"Data Source=(LocalDB)\v11.0;Initial Catalog=master;Integrated Security=True"))
master.ExecuteCommand(#"exec sp_detach_db '{0}'", db);
This suit very well to my needs, because I do not care about delay to start application (because in this case I will have to attach to db always), but it will fix any kind of
System.Data.SqlClient.SqlException (0x80131904): Database 'c:\blablabla\database1.mdf' already exists. Choose a different database name.
which occurs, if database file is delete and you try to create it programmatically
// DataContext
if (!DatabaseExists())
CreateDatabase();
Another way
You can also run command line tool sqllocaldb like this:
var start = new ProcessStartInfo("sqllocaldb", "stop v11.0");
start.WindowStyle = ProcessWindowStyle.Hidden;
using (var stop = Process.Start(start))
stop.WaitForExit();
start.Arguments = "delete v11.0";
using (var delete = Process.Start(start))
delete.WaitForExit();
It will stop the server, detaching all databases. If you have other application using LocalDB, then they will experience attaching delay next time when they try to do query.
Here is my solution for EntityFramework Core 1.0
As you see the database name can be used with its full file path.
var dbf = fileDlg.FileName;
var options = new DbContextOptionsBuilder();
options.UseSqlServer($#"Server=(localdb)\mssqllocaldb;Initial Catalog=master;MultipleActiveResultSets=False;Integrated Security=True");
using (var master = new DbContext(options.Options))
{
master.Database.ExecuteSqlCommand($"ALTER DATABASE [{dbf}] SET OFFLINE WITH ROLLBACK IMMEDIATE");
master.Database.ExecuteSqlCommand($"exec sp_detach_db '{dbf}'");
}