How to download csv file from Google app engine? - google-app-engine

I can't download file from google app engine. This is working in Compute engine.
$sql="SELECT * FROM $table ";
$query = $db->runQuery($sql);
if($query->num_rows > 0) {
$delimiter = ",";
$filename = $table . date('Y-m-d') . ".csv";
// create a file pointer
$f = fopen('php://memory', 'w');
// set column headers
$fields = array('id', 'srno', 'empid', 'empname');
fputcsv($f, $fields, $delimiter);
// output each row of the data, format line as csv and write to file pointer
while($row = $query->fetch_assoc()) {
// $status = ($row['status'] == '1') ? 'Active' : 'Inactive';
$lineData = array(
$row['id'], $row['srno'], $row['empid'], $row['empname'], ]
);
fputcsv($f, $lineData, $delimiter);
}
// move back to beginning of file
fseek($f, 0);
// set headers to download file rather than display it
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
//output all remaining data on a file pointer
fpassthru($f);
}
exit;

What are the logs, error message? How did you deploy this app? Can you show the app.yaml? Is the App in the same project as the Cloud SQL instance? Standard or Flexible environment? PHP 5 or 7?
Most common issues while connecting App Engine to Cloud SQL:
App Engine service account must have the Cloud SQL Admin role
Project in which the Cloud SQL instance resides must have both the Cloud SQL and the SQL Admin API activated
The connection between the app and the MySQL instance is done via proxy, that you configure in your php code and yaml file.
Here is an example of connection to a MySQL instance from PHP72, you can also use this code for local testing. For this you will need to install and run the Cloud SQL Proxy Client.
app.yaml
runtime: php72
handlers:
- url: .*
script: auto
env_variables:
MYSQL_USER: [MYSQL_USER]
MYSQL_PASSWORD: [MYSQL_PASSWORD]
MYSQL_DSN: 'mysql:dbname=[MYSQL_DB_NAME];unix_socket=/cloudsql/[MYSQL_INSTANCE_CONNECTION_NAME]'
beta_settings:
cloud_sql_instances: [MYSQL_INSTANCE_CONNECTION_NAME]
index.php
<?php
$user = getenv('MYSQL_USER');
$password = getenv('MYSQL_PASSWORD');
$dsn = getenv("MYSQL_DSN") ?: "mysql:host=127.0.0.1;port=3306;dbname=[MYSQL_DB_NAME]";
$db = new PDO($dsn, $user, $password);
try {
$db = new PDO($dsn, $user, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$statement = $db->prepare("SELECT * from [MYSQL_TABLE_NAME]");
$statement->execute();
$all = $statement->fetchAll();
foreach ($all as $data) {
echo $data["id"];
}
?>

Related

Microsoft Teams integration into Moodle LMS

everybody! I have an error during integration of Microsoft Teams into Moodle. So one of the steps of integration is running Moodle-AzureAD-Script.ps1 script on a local machine. And when I try running the script I got an error: "./Moodle-AzureAD-Script.ps1: line 1: syntax error near unexpected token newline' '/Moodle-AzureAD-Script.ps1: line 1: <#
";
It doesn't depend on OS, so can somebody tell me, what should I do? Thanks!
The Moodle-AzureAD-Script.ps1 script is in the download from https://moodle.org/plugins/pluginversions.php?plugin=local_o365
<#
File Name : Moodle-AzureAD-Script.ps1
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
#>
# Allow for the script to be run
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser
# Install necessary modules
Install-Module AzureAD -AllowClobber -Scope CurrentUser
Install-Module AzureRM -AllowClobber -Scope CurrentUser
#Overarching requirement - log into Azure first!
Connect-AzureAD
<#
.DESCRIPTION
This function will be able to create an array of type RequiredResourceAccess which will be then passed to the New-AzureADApplication cmdlet
#>
function Get-Resources
{
[Microsoft.Open.AzureAD.Model.RequiredResourceAccess[]] $outputArray = #();
$localPath = Get-Location
$jsonPath = -Join($localPath,'\Json\permissions.json');
$jsonObj = (New-Object System.Net.WebClient).DownloadString($jsonPath) | ConvertFrom-Json;
# Output the number of objects to push into the array outputArray
Write-Host 'From the json path:'$jsonPath', we can find' $jsonObj.requiredResourceAccess.length'attributes to populate';
for ($i = 0; $i -lt $jsonObj.requiredResourceAccess.length; $i++) {
# Step A - Create a new object fo the type RequiredResourceAccess
$reqResourceAccess = New-Object -TypeName Microsoft.Open.AzureAD.Model.RequiredResourceAccess;
# Step B - Straightforward setting the ResourceAppId accordingly
$reqResourceAccess.ResourceAppId = $jsonObj.requiredResourceAccess[$i].resourceAppId;
# Step C - Having to set the ResourceAccess carefully
if ($jsonObj.requiredResourceAccess[$i].resourceAccess.length -gt 1)
{
$reqResourceAccess.ResourceAccess = $jsonObj.requiredResourceAccess[$i].resourceAccess;
}
else
{
$reqResourceAccess.ResourceAccess = $jsonObj.requiredResourceAccess[$i].resourceAccess[0];
}
# Step D - Add the element to the array
$outputArray += $reqResourceAccess;
}
$outputArray;
}
# Step 1 - Getting the necessary information
$displayName = Read-Host -Prompt "Enter the AAD app name (ex: Moodle plugin)"
$moodleDomain = Read-Host -Prompt "Enter the URL of your Moodle server (ex: https://www.moodleserver.com)"
if ($moodleDomain -notmatch '.+?\/$')
{
$moodleDomain += '/'
}
# Step 2 - Construct the reply URLs
$ssoEndUrl = $moodleDomain + 'local/o365/sso_end.php'
$ssoUrl = $moodleDomain + 'local/o365/sso.php'
$ssoLogoutUrl = $moodleDomain + 'local/o365/sso_logout.php'
$botFrameworkUrl = 'https://token.botframework.com/.auth/web/redirect'
$authUrl = $moodleDomain + 'auth/oidc/'
$replyUrls = ($ssoEndUrl, $ssoUrl, $botFrameworkUrl, $authUrl)
# Step 3 - Compile the Required Resource Access object
[Microsoft.Open.AzureAD.Model.RequiredResourceAccess[]] $requiredResourceAccess = Get-Resources
# Step 4 - Making sure to officially register the application
$appVars = New-AzureADApplication -DisplayName $displayName -ReplyUrls $replyUrls -RequiredResourceAccess $requiredResourceAccess -LogoutUrl $ssoLogoutUrl
# Step 5 - Taking the object id generated in Step 2, create a new Password
$pwdVars = New-AzureADApplicationPasswordCredential -ObjectId $appVars.ObjectId
# Step 5a - Updating the logo for the Azure AD app
$location = Get-Location
$imgLocation = -Join($location, '\Assets\moodle-logo.jpg')
Set-AzureADApplicationLogo -ObjectId $appVars.ObjectId -FilePath $imgLocation
# Step 6 - Write out the newly generated app Id and azure app password
Write-Host 'Your AD Application ID: '$appVars.AppId
Write-Host 'Your AD Application Secret: '$pwdVars.Value
In fact, the script exactly depends on OS.
Please pay attention to the README.md file under \o365\scripts path.
It states that:
Requirements
This script requires a Windows 7+ device. MacOS/Linux devices are NOT supported.
This script is only compatible with Windows Powershell 5, which is pre-installed on each Windows 7+ device. Powershell 6+ is NOT
supported.
Make sure the OS and Powershell version are OK and then you will be able to follow the guide in this README.md file to finish the integration.

How to capture DacSevices.Deploy output?

So I've managed to deploy our DACPAC schema via Octopus. I'm using a Deploy.ps1 script interacting with .Net objects just like the article describes.
I'd like to make the deployment process more transparent by including the "standard output" you get from sqlcmd in our Octopus logs. I'm looking for the the generated schema modification messages as well as any custom migration migration messages our developers have put into the pre/post scripts.
The only workaround I can think of is to first generate the script with the DACPAC services and then run it with sqlcmd.exe. Any ideas?
Found the solution, posting in case someone else runs across this. You simply need to subscribe to the your DacService's Message event.
C# sample:
var services = new Microsoft.SqlServer.Dac.DacServices("data source=machinename;Database=ComicBookGuy;Trusted_connection=true");
var package = Microsoft.SqlServer.Dac.DacPackage.Load(#"C:\Database.dacpac");
var options = new Microsoft.SqlServer.Dac.DacDeployOptions();
options.DropObjectsNotInSource = true;
options.SqlCommandVariableValues.Add("LoginName", "SomeFakeLogin");
options.SqlCommandVariableValues.Add("LoginPassword", "foobar!");
services.Message += (object sender, Microsoft.SqlServer.Dac.DacMessageEventArgs eventArgs) => Console.WriteLine(eventArgs.Message.Message);
services.Deploy(package, "ComicBookGuy", true, options);
Powershell sample (executed by the Octopus Tentacle):
# This script is run by Octopus on the tentacle
$localDirectory = (Get-Location).Path
$tagetServer = $OctopusParameters["SQL.TargetServer"]
$databaseName = "ComicBookGuy"
Add-Type -path "$localDirectory\lib\Microsoft.SqlServer.Dac.dll"
$dacServices = New-Object Microsoft.SqlServer.Dac.DacServices ("data source=" + $tagetServer + ";Database=" + $databaseName + "; Trusted_connection=true")
$dacpacFile = "$localDirectory\Content\Unity.Quotes.Database.dacpac"
$dacPackage = [Microsoft.SqlServer.Dac.DacPackage]::Load($dacpacFile)
$options = New-Object Microsoft.SqlServer.Dac.DacDeployOptions
$options.SqlCommandVariableValues.Add("LoginName", $OctopusParameters["SQL.LoginName"])
$options.SqlCommandVariableValues.Add("LoginPassword", $OctopusParameters["SQL.LoginPassword"])
$options.DropObjectsNotInSource = $true
Register-ObjectEvent -InputObject $dacServices -EventName "Message" -Action { Write-Host $EventArgs.Message.Message } | out-null
$dacServices.Deploy($dacPackage, $databaseName, $true, $options)
In the powershell version I couldn't get the handy "Add_EventName" style of event notification working so I had to use the clunky cmdlet. Meh.
Use sqlpackage instead of sqlcmd to deploy dacpac.
Get Latest version here : https://msdn.microsoft.com/en-us/mt186501
$sqlpackage = "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\120\sqlpackage.exe"
It will automatically output errors on the console. We use TFS build definition and call powershell and it is able to display errors that happened during a deploy.
Usage:
& $sqlpackage /Action:Publish /tsn:$dbServer /tdn:$database /sf:$mydacpac/pr:$dbProfile /variables:myVariable=1
This variation captures output but also allows you to capture and react to deploy failures by catching the exception
function Load-DacPacAssembly()
{
$assemblyName = "Microsoft.SqlServer.Dac.dll"
$packageFolder = <some custom code to find our package folder>
$dacPacAssembly = "$packageFolder\lib\net46\$assemblyName"
Write-Host "Loading assembly $assemblyName"
Add-Type -Path "$dacPacAssembly"
}
function Publish-Dacpac($dacpac, $publishProfile){
Load-DacPacAssembly
Write-Host "Loading profile $publishProfile..."
$dacProfile = [Microsoft.SqlServer.Dac.DacProfile]::Load($publishProfile)
$dacService = New-Object Microsoft.SqlServer.dac.dacservices ($dacProfile.TargetConnectionString)
Write-Host "Loading dacpac $dacpac"
$dacPackage = [Microsoft.SqlServer.Dac.DacPackage]::Load($dacpac)
$event = Register-ObjectEvent -InputObject $dacService -EventName "Message" -Action {
$message = $EventArgs.Message
$colour = "DarkGray"
if ($message -contains "Error SQL")
{
$colour = "Red"
}
Write-Host $message -ForegroundColor $colour
}
Write-Host "Publishing...."
try {
$dacService.deploy($dacPackage, $dacProfile.TargetDatabaseName, $true, $dacProfile.DeployOptions)
}
catch [Microsoft.SqlServer.Dac.DacServicesException]
{
$message = $_.Exception.Message
Write-Host "SQL Publish failed - $message" -ForegroundColor Red # Customise here for your build system to detect the error
exit;
}
finally
{
Unregister-Event -SourceIdentifier $event.Name
}
}

Solarium 3.2.0 create ping for SOLR5.0

Installed SOLR 5.0 and started the SOLR instance with bin/solr start -e cloud... normal stuff. The web UI is functioning and can see the two nodes.
Created an index file trying to ping the server per Solarium documentation:
require_once ('init.php');
$str="Running Solarium client version: ".Solarium\Client::VERSION;
$client = new Solarium\Client($config);
// create a ping query
$ping = $client->createPing();
var_dump($ping);
// execute the ping query
try {
$result = $client->ping($ping);
$str=$str.'Ping query successful';
var_dump($result->getData());
} catch (Solarium\Exception $e) {
echo 'Ping query failed';
}
return $str;
the $str can show using Solarium client version 3.2.0.
But while doing $client->ping(), there is an exception:
Problem accessing /solr/admin/ping. Reason:
Not Found
Any hints???
config.php pasted here:
<?php
$config = array(
'endpoint' => array(
'localhost' => array(
'host' => '10.0.0.8',
'port' => 8983,
'path' => '/solr/',
)
)
);
It is a remote connection.
I had the same issue. Put collection name in config.php like this:
'path' => '/solr/collection_name/',

How to properly connect cloudant + sag

I'm working in getting a connection to cloudant done.
The following is using sag library for php:
<?php
header('Content-Type: text/html; charset=utf-8');
require_once('../../src/Sag.php');
//this credentials are from API key
$uName="";
$pName="";
$sag = new Sag('user.cloudant.com');
$sag->login($uName, $pName);
$sag->setDatabase('test');
try {
$result = $sag->get('/test/_design/wordsP/_view/errores');
echo ($result);
}
catch(Exception $e) {
error_log("Something's wrong");
var_dump($e);
}
?>
However I'm not getting expected result (). The view does work, if used just in the url bar.
The response is:
object(SagException)#3(6){
[
"message:protected"
]=>string(50)"Sag Error: cURL error #7: couldn't connect to host"[
"string:private"
]=>string(0)""[
"code:protected"
]=>int(0)[
"file:protected"
]=>string(73)"/home2/.../public_html/clant/src/httpAdapters/SagCURLHTTPAdapter.php"[
"line:protected"
]=>int(134)[
"trace:private"
]=>array(3){ .............
Is there something I'm not using corretly in the php script? (removed current password + username as well as account, but they're there).
Curl error 7 means you are unable to connect to the host or proxy:
CURLE_COULDNT_CONNECT (7)
Failed to connect() to host or proxy.
Source: http://curl.haxx.se/libcurl/c/libcurl-errors.html
When you connect to the URL from your browser if your browser is using a proxy, you will also need to configure sag to use that proxy.
Also, when you say that you replaced the account in your code example, did you mean that you replaced user in $sag = new Sag('user.cloudant.com'); with your actual username? If not, you will need to use your actual username.

CakePHP 2.2 AclExtras aco_sync in browser (sh permission denied)

I'm working on a remote server and I can't use the console because ssh is not enabled. So I need to run aco_sync directly from the browser (or any other way that doesn't involve the shell).
I managed to sync acos on my local dev server with the following code in controller/action:
$command = ROOT . DS . APP_DIR . DS . 'Console' . DS . 'cake';
$params = ' -app ' . ROOT . DS . APP_DIR;
$params .= ' AclExtras.AclExtras';
$params .= ' aco_sync';
$result = shell_exec($command . $params);
But on the production server (with cPanel) I just get no response for about 5 minutes and then I get an internal server error (500). I simply hangs. Actually, this happened on two different VPS servers with cPanel. In the first one, I had ssh and was able to run the command from the console. But when running the quoted code from the browser, I hung just as the other server.
I found no logged errors either on php log files nor cake's log files.
The action is prefixed with "admin_" and ACL doesn't allow execution if not logged in.
'./cake' script file has execute permissions (took me a while to figure this was necessary).
I tried on Chrome and IE8.
Debug level was set to 1.
After trying to run the script, the page broke and I wasn't able to browse until I opened an incognito window or restarted the browser.
I think the server's memory gets completely consumed when I run this script. I've had to restart httpd to get the site up and running again on the server that I could control.
I've seen some implementations using $dispatcher->dispatch() and tried a bunch of them but with no luck.
Any ideas?
App::uses('ShellDispatcher', 'Console');
$command = '-app '.APP.' AclExtras.AclExtras aco_sync';
$args = explode(' ', $command);
$dispatcher = new ShellDispatcher($args, false);
if($dispatcher->dispatch()) {
echo 'OK';
} else {
echo 'Error';
}
Try this, the $dispatcher->dispatch(); seems to show something only in case of an error.
run this and check your database.
App::uses('ShellDispatcher', 'Console');
$command = '-app '.APP.' AclExtras.AclExtras aco_sync';
$args = explode(' ', $command);
$dispatcher = new ShellDispatcher($args, false);
try {
$dispatcher->dispatch();
} catch (Exception $e) {
pr($e);
}

Resources