Checking if database connection established / exists Ci4 - codeigniter-4

I'm trying to check id database connection exist or not then redirect to a page where a user can be able to create a database through form inputs.
Here's what I tried to do but not succeed.
public function index()
{
// $database = \Config\Database::connect();
$database = \CodeIgniter\Database\Config::getConnections();
if ($database)
{
//db connection initialized
return view('dashboard');
}
else
{
//db connection not initialized
return redirect('db_setup');
}
}

Using the code from Virender Kumar but extending it with your request for dbname verification, use something like this:
$database = \Config\Database::connect();
if ($database)
{
// check if db exists:
if($database->query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME='yourDbName'")) {
//db connection initialized
return view('dashboard');
} else {
return false; // db not exist
}
} else {
//db connection not initialized
return redirect()->to('db_setup');
}
Explanation: I added a CodeIgniter 4 raw query $db->query() that selects the general information schema from the database. If the database does not exists you'll get an error.

You have syntax error in redirect function and I am not sure about getconnections function what you have implemented there but connect () will work. See updated code
$database = \Config\Database::connect();
if ($database)
{
//db connection initialized
return view('dashboard');
}
else
{
//db connection not initialized
return redirect()->to('db_setup');
}

Related

Adding client tags to presto jdbc connection

I am using jdbc to connect to presto server.
From the documentation, I am able to connect to the server and run queries.
https://prestodb.io/docs/current/installation/jdbc.html
I am facing issues while sending ClientTags (X-Presto-Client-Tags) in the connection/statement.
Here's the function to build a connection and run a query.
public void test() {
java.util.Properties info = new java.util.Properties();
if (PRESTO_USER != null) {
info.put("user", PRESTO_USER);
}
if (PRESTO_PASSWORD != null) {
info.put("password", PRESTO_PASSWORD);
}
info.put("ClientTags", "my,tag");
try (Connection connection = DriverManager.getConnection(PRESTO_URL, info);
Statement statement = connection.createStatement()) {
testBody(connection, statement);
} catch (Exception ex) {
ex.printStackTrace();
fail("Exception occured");
}
}
However, it fails with
java.sql.SQLException: Unrecognized connection property 'ClientTags'
at com.facebook.presto.jdbc.PrestoDriverUri.validateConnectionProperties(PrestoDriverUri.java:316)
For pyhive, I was able to override the session and pass client tags
https://github.com/dropbox/PyHive/issues/283. Can this be done for jdbc driver too?
It's currently not possible to set ClientTags on the connection URL.
Please create a feature request # https://github.com/trinodb/trino/issues/
Currently, the only way is to use Connection method:
Connection connection = DriverManager.getConnection("....");
connection.unwrap(PrestoConnection.class)
.setClientInfo("ClientTags", "one,two,three");

Accessing sqlite databases on remote machine with static adress (Electron / Nodejs / fs)

I am trying to access an sqlite file on a local area network machine located in "sqlite" folder, on windows file explorer I access it using the IP address "192.168.5.15/sqlite/db.sqlite", however when the electron aplication tries to access it, the path is converted to the local machine path "c:/application ....../192.168 ....".
please how can I just point the file directly using the static IP adress without converting it to local machine path?
here is the code:
// login_app.js
var route = require('../../libs/router.js'); //my lib
var dbPath = "192.168.5.15/sqlite/db.sqlite" // here is the path i want to keep it static
function login() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
if(email == "" || password == ""){
alert("Please Enter Your email & Password ...");
return;
} else{
var sql = require('sql.js'); //Import sqLite
var fs = require("fs"); //Import Files driver
var SHA256 = require("crypto-js/sha256"); //Crypting Library
try {
var filebuffer = fs.readFileSync(dbPath); //here is the problem it converts the file to local machine path c:/..../192....
if (filebuffer != null) {
var db = new SQL.Database(filebuffer);
} else {
var db = new SQL.Database();
console.log("No Database");
}
// Prepare an sql statement
var stmt = db.prepare("SELECT * FROM users WHERE email=:emailid");
// Bind values to the parameters and fetch the results of the query
var result = stmt.getAsObject({':emailid' : email});
if(result.password == null) alert('Account not existing, please contact Your Administrator ...');
else{
if(SHA256(password) == result.password) {
route.data.relocate('dashboard');
}
else alert('Wrong Login credentials, please try again ...');
}
} catch (e) {
console.log(e);
}
}
}
as suggested by GregHNZ var dbPath = "//192.168.5.15/sqlite/db.sqlite" worked, so just used double slash.
Thanks GregHNZ

DocumentDB / CosmosDB - Entity with the specified id does not exist in the system

i tried to connect documentdb from my asp.net website but i am getting this error.
Entity with the specified id does not exist in the system
DocumentClientException: Entity with the specified id does not exist in the system
code as follows in aspx code behind
protected async void Page_Load(object sender, EventArgs e)
{
Response.Write("Page Load<br/>");
await GetData();
}
public async Task GetData()
{
try
{
Response.Write("<br/> Get Data function Start<br/><br/>");
using (var client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]))
{
//await client.OpenAsync();
RequestOptions reqOpt = new RequestOptions { PartitionKey = new PartitionKey(209) };
var parameters = new dynamic[] { 1 };
StoredProcedureResponse<object> result = await client.ExecuteStoredProcedureAsync<object>(
UriFactory.CreateStoredProcedureUri(ConfigurationManager.AppSettings["database"], ConfigurationManager.AppSettings["pcsd"], "GetMemberbyId"), reqOpt, parameters);
Response.Write(result.Response.ToString());
}
Response.Write("<br/><br/> Get Data function End");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
stored procedure as follows
function GetMemberbyId(memId) {
var collection = getContext().getCollection();
//return getContext().getResponse().setBody('no docs found');
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root m where m.memberId='+memId,
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found',
// else take 1st element from feed
if (!feed || !feed.length) getContext().getResponse().setBody('no docs found');
else getContext().getResponse().setBody(feed);
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
in my localhost it's working fine but website published to azure web apps and running i am getting above error
I just spent a couple of hours troubleshooting this, only to find that I had firewalled my instance to a point where I could not connect locally. Keep in mind that the Azure portal document query will obviously still work even when you have no direct access via the API / C# client.
Try setting the firewall to allow All Networks temporarily to check access.
I would check in the portal that the "GetMemberbyId" is the name of the stored procedure for the collection you are trying to run it on. Could be the stored procedure is on a different collection or that the stored procedure is named something else.
If that all checks out.. I have had more luck with the __.filter() way of querying documents on the server. See:
http://azure.github.io/azure-documentdb-js-server/

Change connection used on runtime

I hope you can help me (us). I'm working on a API project which have two databases :
Production DB : api.myapp.fr
Testing DB : test.api.myapp.fr
Theses two databases are writable by the user.
When a user call our API, he can set the authorization header whichever he needs. For example :
Authorization: s_0
Will perform operations on api.myapp.fr and
Authorization: s_t_0
Will perform operations on test.api.myapp.fr .
My question is : How can I do that with sails ?
Actually, I have a policie which check if the user is using a production key or a testing key, and I override the default models with the one for testings purposes, like this :
if (!is_production) {
req.session.isProd = false;
req.session.logs.environment = "test";
User = UserTest;
Payment = PaymentTest;
PayzenStatus = PayzenStatusTest;
Transaction = TransactionTest;
Card = CardTest;
Doc = DocTest;
}
But you can see the problem if a user makes a test request and then a production request, the models are still the tests ones...
I use my models in services and policies, therefor I can't do
req.models = {};
// If not in production, use the test models
if (!is_production) {
req.session.isProd = false;
req.session.logs.environment = "test";
req.models.User = UserTest;
req.models.Payment = PaymentTest;
req.models.PayzenStatus = PayzenStatusTest;
req.models.Transaction = TransactionTest;
req.models.Card = CardTest;
req.models.Doc = DocTest;
}
// Otherwise use the production models
else {
req.models.User = User;
req.models.Payment = Payment;
req.models.PayzenStatus = PayzenStatus;
req.models.Transaction = Transaction;
req.models.Card = Card;
req.models.Doc = Doc;
}
If you have any idea on how ton achieve this (whatever the way, we can still perform deep changes in our code), I would be really happy to ear it.
Thanks
Two different ways of doing this.
First you could set an environment variable on your production host and check that environment variable to see if you are running in prod. If you are running in prod then use the URI to the production database.
Secodonly, which is probably the better way of doing this creating a config.js file that allows you to read environment variables. What I do for all my apps is set environment variables for connection info to databases and API keys. When running locally/testing I have some defaults in my app but when they environment variables are set they are read and used. So set the environment variable in production to point to your production databases.
The config.js file Im posting below contains references to VCAP, which assumes you are running on Cloud Foundry.
config.js
var VCAP_SERVICES = process.env["VCAP_SERVICES"],
vcapServices;
if (VCAP_SERVICES) {
vcapServices = JSON.parse(VCAP_SERVICES);
}
function getEnv(propName, defaultValue) {
if (process.env[propName]) {
return process.env[propName];
} else {
return defaultValue;
}
}
module.exports = function() {
return {
getEnv : getEnv,
couchDbURL: function() {
// Default to a local couch installation for development
if (VCAP_SERVICES) {
return vcapServices["cloudantNoSQLDB"][0].credentials.url;
}
else {
return "http://localhost:5984";
}
},
couchDbName: function() {
return getEnv("COUCHDB_NAME", "mydb");
}
};
};
app.js
var config = require("./config")();
console.log(config.couchDbURL());

connect to local AD domain controller

I've set up a development server with AD and I'm trying to figure out how to connect to it via .NET. I'm working on the same machine that AD is installed on. I've gotten the DC name from AD, and the name of the machine, but the connection just does not work. I'm using the same credentials I used to connect to the server.
Any suggestions?
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://[dc.computername.com]", "administrator", "[adminpwd]");
Can you connect to the RootDSE container?
DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE", "administrator", "[adminpwd]");
If that works, you can then read out some of the properties stored in that root container
if (rootDSE != null)
{
Console.WriteLine("RootDSE Properties:\n\n");
foreach (string propName in rootDSE.Properties.PropertyNames)
{
Console.WriteLine("{0:-20d}: {1}", propName, rootDSE.Properties[propName][0]);
}
}
This will show you some information about what LDAP paths are present in your installation.
Try something like this, using the System.DirectoryServices.Protocols namespace :
//Define your connection
LdapConnection ldapConnection = new LdapConnection("123.456.789.10:389");
try
{
//Authenticate the username and password
using (ldapConnection)
{
//Pass in the network creds, and the domain.
var networkCredential = new NetworkCredential(Username, Password, Domain);
//Since we're using unsecured port 389, set to false. If using port 636 over SSL, set this to true.
ldapConnection.SessionOptions.SecureSocketLayer = false;
ldapConnection.SessionOptions.VerifyServerCertificate += delegate { return true; };
//To force NTLM\Kerberos use AuthType.Negotiate, for non-TLS and unsecured, use AuthType.Basic
ldapConnection.AuthType = AuthType.Basic;
ldapConnection.Bind(networkCredential);
}
catch (LdapException ldapException)
{
//Authentication failed, exception will dictate why
}
}

Resources