I want to create an extension for Azure Data Studio that accesses a database. The database (SQL Server) is already available in Azure Data Studio, as I am manually interacting with it.
Reading the Extensible API documentation it seems to be possible to access the databases available in Azure Data Studio. But how do I send SQL queries and receive their replies from within my extension code? What would be the SQL client for my extension code?
I found no docs about this, however, I found myself this piece of code that works.
I don't know if this is a correct approach.
var connection = await azdata.connection.getCurrentConnection();
if (connection) {
var uri = await azdata.connection.getUriForConnection(connection.connectionId);
var g = azdata.dataprotocol.getProvidersByType(
azdata.DataProviderType.QueryProvider
)[0] as QueryProvider;
var t = await g.runQueryAndReturn(
uri,
"SELECT TOP 1 * FROM sys.objects"
);
var jj = t.rows[0][0];
vscode.window.showInformationMessage(jj.displayValue);
}
Related
I'm in a project the we need to use BigQuery, PubSub, Logs explorer and Cloud Functions.
The project:
Every time certain event occurs (like an user accepting cookies), a system inserts a new query into BigQuery with a lot of columns (params) like: utm_source, utm_medium, consent_cookies, etc...
Once I have this new query in my table I need to read the columns and get the values to use in a cloud function.
In the cloud function I want to use those values to make api calls.
What I manage to do so far:
I created a log routing sink that filter the new entries and send the log to my PubSub topic.
Where I'm stuck:
I want to create a Cloud function that triggers every time a new log comes in and in that function I want to access the information that is contained in the log, such as utm_source, utm_medium, consent_cookies, etc... And use values to make api calls.
Anyone can help me? Many MANY thanks in advance!
I made a project to illustrate the flow:
Insert to table:
2.From this insertion create a sink in logging: (filtering)
Now every time I create a new query it goes to PUB/SUB i get the log of the query
What I want to do is to trigger a function on this topic and use the values I have in the query to do operations like call api etc...
So far I was able to write this code:
"use strict";
function main() {
// Import the Google Cloud client library
const { BigQuery } = require("#google-cloud/bigquery");
async function queryDb() {
const bigqueryClient = new BigQuery();
const sqlQuery = `SELECT * FROM \`mydatatable\``;
const options = {
query: sqlQuery,
location: "europe-west3",
};
// Run the query
const [rows] = await bigqueryClient.query(options);
rows.forEach((row) => {
const username = row.user_name;
});
}
queryDb();
}
main();
Now I'm again stuck, Idont know how to get the correct query from the sink I created and use the info to make my calls...
You have 2 solutions to call your Cloud Functions from a PubSub message
HTTP Functions: You can set up a HTTP call. Create your Cloud Function in trigger-http, and create a push subscription on your PubSub topic to call the Cloud Functions. Don't forget to add security (make your function private and enable security on PubSub) because your function is publicly accessible
Background functions: You can bind directly your Cloud Functions to PubSub topic. A subscription is automatically created and linked to the Cloud Functions. The security is built-in.
And, because you have 2 types of functions, you have 2 different function signatures. I provide you both, the processing is the (quite) same.
function extractQuery(pubSubMessage){
// Decide base64 the PubSub message
let logData = Buffer.from(pubSubMessage, 'base64').toString();
// Convert it in JSON
let logMessage= JSON.parse(logData)
// Extract the query from the log entry
let query = logMessage.protoPayload.serviceData.jobInsertRequest.resource.jobConfiguration.query.query
console.log(query)
return query
}
// For HTTP functions
exports.bigqueryQueryInLog = (req, res) => {
console.log(req.body)
const query = extractQuery(req.body.message.data)
res.status(200).send(query);
}
// For Background functions
exports.bigqueryQueryInLogTopic = (message, context) => {
extractQuery(message.data)
};
The query logged is the insert into... that you have in your log entry. Then, you have to parse your SQL request to extract the part that you want.
I am currently working on Bot framework technology, in my current project I want to store the bot conversation data into azure SQL database.
I have developed one ReviewBot, In this I have to write the code for to give review/rating of any hotel by user.
Bot communicate with user is working fine but I want to store the user conversation data with my bot into azure SQL database using C# language.
Please tell me how to implement the above concept.
Regards,
Pradeep
I wrote a tutorial showing this: Implementing A SQL Server Database With The Microsoft Bot Framework
The key piece of code is:
// *************************
// Log to Database
// *************************
// Instantiate the BotData dbContext
Models.BotDataEntities DB = new Models.BotDataEntities();
// Create a new UserLog object
Models.UserLog NewUserLog = new Models.UserLog();
// Set the properties on the UserLog object
NewUserLog.Channel = activity.ChannelId;
NewUserLog.UserID = activity.From.Id;
NewUserLog.UserName = activity.From.Name;
NewUserLog.created = DateTime.UtcNow;
NewUserLog.Message = activity.Text;
// Add the UserLog object to UserLogs
DB.UserLogs.Add(NewUserLog);
// Save the changes to the database
DB.SaveChanges();
We are using Spreadsheet API in our .Net Application to change content dynamically in the spreadsheet, and we are using that content to update values in the Google Ads with AdWords Script.
But from 1st June 2015 we are facing issues in our .Net Application, because of the update in the Spreadsheet API.
Our earlier work :- We were making window based application and scheduling it hourly. In the background it was retrieving and adding value in the spreadsheet. In the previous application, we used to authenticate our Gmail id and password only once in our code.
Below is the exact problem we are facing :-
As per the new API we need to authenticate our app each and every time it runs and also every time we need to put unique access code, which will badly affect our automation.
I would appreciate your immediate attention to this matter, and looking forward to your revert.
After lot of R&D I got the solution.
Links:
https://developers.google.com/apps-script/guides/jdbc
//it will insert value into table entries
function main() {
// Replace the variables in this block with real values.
var address = 'Your Server IP:1433';
var user = 'Server username';
var userPwd = Server Password';
var db = 'lms';
var dburl = 'jdbc:sqlserver://Your Server IP:1433;DataBaseName=lms';
// Write one row of data to a table.
var conn = Jdbc.getConnection(dburl, user, userPwd);
Logger.log(conn);
var stmt = conn.prepareStatement('INSERT INTO entries '
+ '(guestName, content) values (?, ?)');
stmt.setString(1, 'First Guest');
stmt.setString(2, 'Hello, world');
stmt.execute();
// Write 500 rows of data to a table in a single batch.
}
i need help for my application "Google App Script".
I am the owner of a Spreadsheet that I use as a DB in my application; this spreadsheet must remain private.
My application is executed as Gadget in Google Site, in this application a user runs the script as himself (not under the owner's identity).
I need that all users who access the application can get some data from the DB Spreadsheet.
How can users get this data, if the Spreadsheet is only accessible to me?
Can I use oAuth?
Sorry for the bad English
Following Zig answer and to illustrate, here is an example of such a contentService webapp, one can call it with this url either in a browser or in urlFetch
The app is deployed as follows : execute as me and anyone can access even anonymous
https://script.google.com/macros/s/AKfycbxfk5YR-JIlhv7HG9R7F-cPxmL0NZRzrdGF4VFGxGivBkYeZY4/exec?&user=chris&row=4&sheet=Sheet1
and here is the demo script
function doGet(e) {
if(e.parameter.user!='serge' && e.parameter.user!='chris' ){return ContentService.createTextOutput("logging error, you are not allowed to see this").setMimeType(ContentService.MimeType.TEXT)};
var sheet = e.parameter.sheet;
var row = Number(e.parameter.row);
Logger.log(sheet+' '+row);
var ss = SpreadsheetApp.openById("0AnqSFd3iikE3dENnemR2LVFMTFM5bDczNGhfSG11LVE");// this sheet is private but anyone can call this app
var sh = ss.getSheetByName(sheet);
var range = sh.getRange(row,1,1,sh.getLastColumn());
var val = Utilities.jsonStringify(range.getValues());
var result = ContentService.createTextOutput(val).setMimeType(ContentService.MimeType.JSON);
return result;
}
No you cant use oauth from the gadget as the user doesnt have read permission.
However you can publish a second script to extract needed data that runs as you with anonymous public access and call that one with urlfetch from the 1st. Slower thou.
Can Flash be used together with SQL? I have a Flash form and I need to connect it to SQL. If there is any example on the net about this topic. I can't find it.
You don't use ActionScript directly with an SQL database. Instead you make http requests from ActionScript to a server, specifying the correct parameters. A typical opensource setup, is a PHP script communicating with a MySQL DB, but you can use Java with Oracle, Ruby with CouchDB, .NET with SQL or any other possible configuration. The important point is that you must be able to call a server script and pass variables... typically a Restful setup.
Once your PHP script has been properly configured, you can use http POST or http GET to send values from ActionScript.
PHP:
<?php
$updateValue = $_POST["updateValue"];
$dbResult = updateDB( $updateValue ); //This should return the db response
echo( $dbResult );
?>
To call this script from ActionScript, you need to create a variables object.
var variables:URLVariables = new URLVariables();
variables.updateValue = "someResult";
The variable name .updateValue, must match the php variable exactly.
now create a URLRequest Object, specifying the location of your script. For this example the method must be set to POST. You add the variable above to the data setter of the request.
var request:URLRequest = new URLRequest( "yourScript.php" );
request.method = URLRequestMethod.POST;
request.data = variables;
Now create a URLLoader and add an event listener. Do not pass the request created above to the constructor, but to the load method.
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onComplete );
loader.load( request );
The handler would look something like this.
private function onComplete( e:Event ) : void
{
trace( URLLoader( e.target ).data.toString() );
}
This example shows how to update and receive a response from a server / db combo. However, you can also query a DB through the script and parse the result. So in the PHP example above, you can output JSON, XML or even a piped string, and this can be consumed by ActionScript.
XML is a popular choice, as ActionScript's e4x support treats XML like a native object.
To treat the response above like an XML response, use the following in the onComplete handler.
private function onComplete( e:Event ) : void
{
var result:XML = XML( URLLoader( e.target ).data );
}
This will throw an error if your xml is poorly formed, so ensure the server script always prints out valid XML, even if there is a DB error.
The problem with this is giving someone a flash file that directly accesses SQL server is very insecure. Even if it's possible, which I have seen SOCKET classes out there to do so for MySQL (though never used it), allowing users to remotely connect to your DB is insecure as the user can sniff the login information.
In my opinion, the best way to do this is to create a Client/Server script. You can easily do this with PHP or ASP.net by using SendAndLoad to send the data you need to pass to SQL via POST fields. You can then send back the values in PHP with:
echo 'success='.+urlencode(data);
With this, flash can access the data via the success field.
I don't personally code flash but I work with a company who develops KIOSK applications for dozens of tradeshow companies, and my job is to store the data, return it to them. This is the method we use. You can make it even cleaner by using actual web services such as SOAP, but this method gets the job done if its just you using it.
You should look into Zend Amf or even the Zend Framework for server side communication with Flash. As far as I know Zend Amf is the fastest way to communicate with PHP ( therefore your database ) also you can pass & return complex Objects from the client to the server and vice versa.
Consider this , for instance. You have a bunch of data in your database , you implement functions in ZF whereas this data is formatted and set as a group of Value Objects. From Flash , you query ZF , Zf queries the database , retrieve & formats your data, return your Value Objects as a JSON string ( for instance ). In Flash, you retrieve you JSON string , decode it and assign your Value Objects to whatever relevant classes you have.
There are plenty of tutorials out there regarding Flash communication with the Zend Framework.
Here's an example:
http://gotoandlearn.com/play.php?id=90