IBM Cloud Functions to MySQL - mysql

I am trying to read some data from my MySql DB using a function (Node), the code bellow is what i had tryed so far.
/**
*
* main() será executado quando você chamar essa ação
*
* #param As ações do Cloud Functions aceitam um único parâmetro, que deve ser um objeto JSON.
*
* #return A saída dessa ação, que deve ser um objeto JSON.
*
*/
var sql = require('mysql');
var connection = sql.createConnection({
host: 'xxxxxxxxxxxxxxxxx',
user: 'ccccccccccccccc',
password: 'wwwwwwwwwwww',
database: 'dsssssssssssssss'
});
function main(params) {
try {
connection.connect();
var sql="SELECT * FROM db_a43aea_frenew.funcionarios where Owner = 208 AND CodigoVendedor = 20";
console.log("Olaaaaaaaa....");
connection.query(sql,function(err,result){
return{message:result};
//console.log(result);
})
//console.log(result);
//console.log(rows);
connection.end();
}
catch (e) {
return { message:"error ==> " + e};
//return{message:"FALSE"};
}
}
But it produced no results. And have no error also.
Can someone give some hint of where the problem is..
Thank you.

Related

Creating a Custom Data Adapter: Importing data adapter

Following the tutorial for creating a custom data adapter:
https://forge.autodesk.com/en/docs/dataviz/v1/developers_guide/advanced_topics/custom_data_adapter/
Getting error in chrome console:
Created file Hyperion.Data.BimapiDataAdapter in the folder forge-dataviz-iot-reference-app-main\node_modules\forge-dataviz-iot-data-modules\client\data based on the Hyperion.Data.Adapter file in the same folder. Then edited on line 371 and changed RestApiDataAdapter to BimapiDataAdapter.
Then trying to import this in BaseApp.jsx on line 34 in the folder forge-dataviz-iot-reference-app-main\node_modules\forge-dataviz-iot-react-components\client\components.
Your Hyperion.Data.BimapiDataAdapter.js is not placed aside forge-dataviz-iot-react-components/BaseApp.jsx, so the package-tool Webpack cannot it by ./Hyperion.Data.BimapiDataAdapter in BaseApp.jsx.
Here is my approach to exposing Hyperion.Data.BimapiDataAdapter.js.
Create Hyperion.Data.BimapiDataAdapter.js under forge-dataviz-iot-reference-app-main\node_modules\forge-dataviz-iot-data-modules\client\data. Here is how it looks like (just copied and pasted the contents of RestApiDataAdapter for the quick demo)
import { DataAdapter } from './Hyperion.Data';
/**
* Data adapter class dealing with sample data.
* #memberof Autodesk.DataVisualization.Data
* #alias Autodesk.DataVisualization.Data.BimapiDataAdapter
* #augments DataAdapter
*/
export class BimapiDataAdapter extends DataAdapter {
/**
* Constructs an instance of BimapiDataAdapter.
*/
constructor(provider = "synthetic", baseName = "") {
super("BimapiDataAdapter", baseName);
/* eslint-disable no-undef */
this._provider = provider;
}
/**
* Loads all DeviceModel objects from the sample REST API.
*
* #returns {Promise<DeviceModel[]>} A promise that resolves to a single
* dimensional array containing a list of loaded DeviceModel objects. If no
* DeviceModel is available, the promise resolves to an empty array.
* #memberof Autodesk.DataVisualization.Data
* #alias Autodesk.DataVisualization.Data.BimapiDataAdapter#loadDeviceModels
*/
async loadDeviceModels() {
const adapterId = this.id;
return fetch(this._getResourceUrl("api/device-models"))
.then((response) => response.json())
.then((rawDeviceModels) => {
/** #type {DeviceModel[]} */
const normalizedDeviceModels = [];
rawDeviceModels.forEach((rdm) => {
// Create a normalized device model representation.
const ndm = new DeviceModel(rdm.deviceModelId, adapterId);
ndm.name = rdm.deviceModelName;
ndm.description = rdm.deviceModelDesc;
// Generate device property representation.
rdm.deviceProperties.forEach((rdp) => {
const propId = rdp.propertyId;
const propName = rdp.propertyName;
const ndp = ndm.addProperty(propId, propName);
ndp.description = rdp.propertyDesc;
ndp.dataType = rdp.propertyType;
ndp.dataUnit = rdp.propertyUnit;
ndp.rangeMin = rdp.rangeMin ? rdp.rangeMin : undefined;
ndp.rangeMax = rdp.rangeMax ? rdp.rangeMax : undefined;
});
normalizedDeviceModels.push(ndm);
});
// Fetch actual devices for each of the device models.
return this.fetchDevicesForModels(normalizedDeviceModels);
});
}
/**
* Fetches actual device IDs and populate DeviceModel objects with them.
*
* #param {DeviceModel[]} deviceModels The DeviceModel objects for which
* actual device IDs are to be populated.
*
* #returns {Promise<DeviceModel[]>} A promise that resolves to the
* DeviceModel objects populated with actual device IDs.
* #memberof Autodesk.DataVisualization.Data
* #alias Autodesk.DataVisualization.Data.BimapiDataAdapter#fetchDevicesForModels
*/
async fetchDevicesForModels(deviceModels) {
const promises = deviceModels.map((deviceModel) => {
const model = deviceModel.id;
return fetch(this._getResourceUrl("api/devices", { model: model }))
.then((response) => response.json())
.then((jsonData) => jsonData.deviceInfo);
});
return Promise.all(promises).then((deviceInfosList) => {
// Assign devices to each device model.
deviceModels.forEach((deviceModel, index) => {
// Turn data provider specific device data format into
// the unified data format stored in Device object.
//
const deviceInfos = deviceInfosList[index];
deviceInfos.forEach((deviceInfo) => {
const device = deviceModel.addDevice(deviceInfo.id);
device.name = deviceInfo.name;
const p = deviceInfo.position;
device.position = new THREE.Vector3(
parseFloat(p.x),
parseFloat(p.y),
parseFloat(p.z)
);
device.lastActivityTime = deviceInfo.lastActivityTime;
device.deviceModel = deviceModel;
device.sensorTypes = deviceModel.propertyIds;
});
});
return deviceModels;
});
}
/**
* Fetches the property data based on the given device ID.
*
* #param {QueryParam} query Parameters of this query.
*
* #returns {Promise<DeviceData>} A promise that resolves to an aggregated
* property data for the queried device.
* #memberof Autodesk.DataVisualization.Data
* #alias Autodesk.DataVisualization.Data.BimapiDataAdapter#fetchDeviceData
*/
async fetchDeviceData(query) {
const pids = query.propertyIds;
const promises = pids.map((pid) => this._fetchPropertyData(query, pid));
return Promise.all(promises).then((deviceDataList) => {
const deviceData = new DeviceData(query.deviceId);
deviceDataList.forEach((devData) => deviceData.mergeFrom(devData));
return deviceData;
});
}
/**
* Fetches data for a single property based on the given device ID.
*
* #param {QueryParam} query Parameters of this query.
* #param {string} propertyId The ID of the property.
*
* #returns {Promise<DeviceData>} A promise that resolves to an aggregated
* property data for the queried device.
*/
async _fetchPropertyData(query, propertyId) {
const url = this._getResourceUrl("api/aggregates", {
device: query.deviceId,
property: propertyId,
startTime: query.dateTimeSpan.startSecond,
endTime: query.dateTimeSpan.endSecond,
resolution: query.dateTimeSpan.resolution,
});
return fetch(url)
.then((response) => response.json())
.then((rawAggregates) => {
// Convert 'rawAggregates' which is in the following format, into 'AggregatedValues'
//
// rawAggregates = {
// timestamps: number[],
// count: number[],
// min: number[],
// max: number[],
// avg: number[],
// sum: number[],
// stdDev: number[]
// }
//
const aggrValues = new AggregatedValues(query.dateTimeSpan);
aggrValues.tsValues = rawAggregates.timestamps;
aggrValues.countValues = rawAggregates.count;
aggrValues.maxValues = rawAggregates.max;
aggrValues.minValues = rawAggregates.min;
aggrValues.avgValues = rawAggregates.avg;
aggrValues.sumValues = rawAggregates.sum;
aggrValues.stdDevValues = rawAggregates.stdDev;
aggrValues.setDataRange("avgValues", getPaddedRange(aggrValues.avgValues));
const deviceData = new DeviceData(query.deviceId);
const propertyData = deviceData.getPropertyData(propertyId);
propertyData.setAggregatedValues(aggrValues);
return deviceData;
})
.catch((err) => {
console.error(err);
});
}
/**
* Gets the resource URL for a given endpoint with query parameters
*
* #param {string} endpoint The endpoint for the URL to generate
* #param {Object.<string, string>} parameters Key-value pairs of query parameters
*
* #returns {string} The string that represents the complete resource URL
* #private
*/
_getResourceUrl(endpoint, parameters) {
parameters = parameters || {};
parameters["provider"] = this._provider;
parameters["project"] = "unused";
const ps = Object.entries(parameters).map(([k, v]) => `${k}=${v}`);
return `${this._baseName}/${endpoint}?${ps.join("&")}`;
}
}
Expose the class BimapiDataAdapter from ``forge-dataviz-iot-reference-app-main\node_modules\forge-dataviz-iot-data-modules\client.js`
export * from "./client/data/Hyperion.Data";
export * from "./client/data/Hyperion.Data.BimapiDataAdapter"; //!<<< add this line
Import BimapiDataAdapter in forge-dataviz-iot-reference-app-main\node_modules\forge-dataviz-iot-react-components\client\components\BaseApp.jsx from where import { ... } from "forge-dataviz-iot-data-modules/client" is
import {
Session,
AzureDataAdapter,
RestApiDataAdapter,
DataView,
DateTimeSpan,
EventType,
DeviceProperty,
DeviceModel,
BimapiDataAdapter //!<<< here it is
} from "forge-dataviz-iot-data-modules/client";
Afterward, re-execute ENV=local npm run dev in your terminal console.
If you have further questions on how Webpack resolves packages, I would advise you to check these out:
https://webpack.js.org/concepts/module-resolution/
https://webpack.js.org/concepts/module-federation/

Html Data to JSON to String Using Swift 4 [duplicate]

This question already has answers here:
Convert HTML to Plain Text in Swift
(8 answers)
Closed 3 years ago.
I am trying to decode html data to simple string but I get all html syntax along with
I am using alamofire get method
Link for html data
http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es
Any help will be appreciated
I have tried all codes and extension on stack overflow but unable to get proper results
let urlString = "http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es"
Alamofire.request(urlString).response { response in
if let data = response.data{
let str = data.html2AttributedString
print(str)
}
}
I get String in along with html syntax
I want this text
Te damos la bienvenida a La Orotava, el pueblo con mayor desnivel de
España. Abarca desde las playas del Rincón, a nivel del mar, hasta
los 3718 metros del pico Teide, el punto más alto de España, cuya
última erupción fue en 1798. Se cree que el nombre Orotava deriva de
la palabra Arautápala, con el que denominaban a este territorio los
antiguos aborígenes guanches. Tras la conquista, fue declarada Villa
por el rey Felipe IV en 1648. Te invitamos a recorrerlo a través de
dos rutas diferentes: La Orotava Secreta o Ruta Azul y La Orotava
Legendaria o Ruta Verde.Cada ruta dura aproximadamente una hora y
media a paso normal y sus contenidos son diferentes. Si dispones de
tiempo, te recomendamos que hagas las dos rutas por separado para
disfrutar de rincones, leyendas y secretos que La Orotava te ofrece. A
lo largo del recorrido encontrarás, incrustadas en el suelo, placas
circulares de metal dorado. Cada placa indica el número de pista en el
color de la ruta a la que pertenece. Cuando te encuentres frente a
estas placas, pulsa el número de pista correspondiente. Si no
dispones del tiempo suficiente, te recomendamos que elijas sólo una
ruta. Pregunta al personal de la Oficina Municipal de Turismo, te
atenderán encantados y te ayudarán a elegir una de ellas en función de
tus intereses. También tienes a tu disposición folletos y otros
materiales en la oficina para ayudarte en esta decisión. Ten en
cuenta que La Orotava está llena de calles pendientes con subidas y
bajadas muy pronunciadas. Si eliges la ruta de La Orotava Legendaria,
o Ruta Verde, te encontrarás un recorrido con menos desnivel. Por
otro lado, la Ruta de La Orotava Secreta o Ruta Azul ofrece a los más
aventureros vistas panorámicas únicas desde las mayores alturas a las
que llega la visita. Te recomendamos realizar las rutas en horario de
oficina para que tengas la oportunidad de encontrar abiertos el mayor
número de espacios posible. Las iglesias suelen estar abiertas en
horario de culto. Recuerda que tienes a tu disposición un botón de
pausa y otro de repetición de los últimos 10 segundos en el
reproductor, para hacerte más cómodo el recorrido. Cualquiera de las
dos rutas está llena de sorpresas y rincones maravillosos. Adelante,
pulsa la ruta de tu elección y adentrémonos juntos en este paseo por
La Orotava.
Your answer is here
extension String{
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
API Call
let urlString = "http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es"
Alamofire.request(urlString, method: .get, parameters: nil).responseJSON { response in
do {
if let jsonDict = try JSONSerialization.jsonObject(with: (response.data as Data?)!, options: []) as? [String:AnyObject]{
if let body = jsonDict["body"] as? String{
print(body.htmlToString) // Your output is Here
}
}
} catch _ {
print("Exception!")
}
}
Output:
You need to create NSAttributedString from HTML string.
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
Whenever you want to use HTML text:
textView.attributedText = htmlString.htmlToAttributedString
Use the Below Extension for Data & String
extension Data {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print("error:", error)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
extension String {
var html2AttributedString: NSAttributedString? {
return Data(utf8).html2AttributedString
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
Implementation in your code should be Like this.
let urlString = "http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es"
Alamofire.request(urlString).response { response in
if let data = response.data{
let str:NSAttributedString = data.html2AttributedString //call the extension method here
print(str)
}
}

Angular clone object from function

I try clone my response json, but the id is the same..
I want to clone an item in my json to facilitate the addition of content.
The problem is following the same ID, then the answer is to update and no new item ..
the function:
$scope.cloneItem = function(id) {
$scope.itemtoclone = allDB.get({section: section, id: id}, function(){
$scope.itemnew = new allDB({section: section});
$scope.itemnew = angular.copy($scope.itemtoclone);
$scope.itemnew.$save(function(){
$mdToast.show($mdToast.simple({position: 'top right'}).content('Clone criado!'));
});
});
}
and the response:
GET http://localhost:5000/posts/25 304 Not Modified 7ms
POST http://localhost:5000/25 201 Created 2ms
json object to clone:
{
"id": 25,
"title": "Willian busca protagonismo igual ao de Neymar: \"Sempre joguei assim\"",
"subtitle": "Com 94% de aproveitamento nos passes na estreia da Copa América, jogador tem chamado a
responsabilidade e dividido a missão de criar os lances com o camisa 10",
"slug": "brasil-post-1",
"published": true,
"originalDate": "2015-06-16T03:00:00.000Z",
"excerpt": "Com 94% de aproveitamento nos passes na estreia da Copa América",
"$promise": {},
"$resolved": true,
"cats": [
2,
3,
4,
5,
7
]
}
Resolved, It was not quite what I wanted, but I help!
$scope.cloneItem = function(id) {
$scope.getclone = allDB.get({section: section, id: id}, function(response){
console.log(response);
$scope.itemnew = new allDB({section: section});
$scope.itemnew.title = response.title;
$scope.itemnew.subtitle = response.subtitle;
$scope.itemnew.excerpt = response.excerpt;
$scope.itemnew.$save(function(){
$mdToast.show($mdToast.simple({position: 'top right'}).content('Clone criado!'));
});
});
}

Exception with Crystal Reports on IIS 6

Hi i encountered a problem on my production environement with Crystal Reports 13. My OS is Windows Server 2003 with IIS 6.
I explain:
Since many month, my production environement worked with Crystal Reports 10 but 1 month ago i install Crystal Reports 13. I precise the 2 version Cohabite and i change in the web.config versions of assembly. Since, i got 2 problems, the first is resolved, i increase the printjoblimit to 150. The other problem who was not resolved is an exception :
Une erreur interne a été détectée. Veuillez nous excuser pour le désagrément.
L'appel à la fonction Suiv_Click a levé l'exception suivante :
CrystalDecisions.CrystalReports.Engine.LoadSaveReportException: Chemin d'accès au fichier de rapport non valide. à
CrystalDecisions.CrystalReports.Engine.EngineExceptionUtils.DoThrowException(String
message, EngineExceptionErrorID id) à CrystalDecisions.CrystalReports.Engine.ExceptionThrower.ThrowEngineException(String
messageID, EngineExceptionErrorID id) à
CrystalDecisions.CrystalReports.Engine.ReportDocument.Load(String filename,
OpenReportMethod openMethod, Int16 parentJob) à
CrystalDecisions.CrystalReports.Engine.ReportDocument.EnsureLoadReport() à
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val,
Type type) à CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSource(DataSet
dataSet) à WebOvins_DocumentCirculationv3.CreerEtat_DocCirculation(dsDocCirculation ds)
dans d:\Inetpub\wwwroot\Synel\WOC\WOC\DocumentCirculationv3.aspx.cs:ligne 1182 à
WebOvins_DocumentCirculationv3.Suiv_Click(Object sender, EventArgs e) dans
d:\Inetpub\wwwroot\Synel\WOC\WOC\DocumentCirculationv3.aspx.cs:ligne 1009
The exception occur beetween 12 or 16 o'clock when i print a report. Before no problem. I supposed is a problem of load. In the night something was flush?
Do you have an idea?
Sorry for my english.
Thanks
Here is my code.
private void CreerEtat_DocCirculation(dsDocCirculation ds)
{
//try
//{
// Variables utilisées pour la suppression dans le fichier aspx
objname = this.Session.SessionID;
objtype = "dir";
ReportDocument rd = new ReportDocument();
//if (Master.ElevageCours.TypeAdhesion != eTypeAdhesion.V1 && !Master.ElevageCours.SansInventaire)
if (false)
{
rd.Load(this.Request.PhysicalApplicationPath + "WOC\\Editions\\DocCirculation.rpt");
}
else
{
rd.Load(this.Request.PhysicalApplicationPath + "WOC\\Editions\\DocCirculationv3.rpt");
}
rd.SetDataSource(new dsDocCirculation());
// Remplissage des divers paramètres de l'édition
rd.DataDefinition.FormulaFields["AFFANI"].Text = "'0'"; // Suppression de la section liste des animaux
//if (Master.ElevageCours.TypeAdhesion != eTypeAdhesion.V1 && !Master.ElevageCours.SansInventaire)
if (false)
{
if (vuesDocumentCirculation.GetActiveView().Equals(vueChargement))
{
EditionDocCirculation.AffectationParametres(rd,
(DocCirculation)Session[sSession.DocumentCirculation],
Master.ElevageCours,
0,//txtNbOvinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbOvinsCharge.Text),
0,//txtNbCaprinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbCaprinsCharge.Text),
0,
BaseWOC,
Master.UtilisateurCours.EnDemo ? Coord_ARSOE : null,
true);
}
else
{
EditionDocCirculation.AffectationParametres(rd,
(DocCirculation)Session[sSession.DocumentCirculation],
Master.ElevageCours,
0,//txtNbOvinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbOvinsDecharge.Text),
0,//txtNbCaprinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbCaprinsDecharge.Text),
txtNbMortsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbMortsDecharge.Text),
BaseWOC,
Master.UtilisateurCours.EnDemo ? Coord_ARSOE : null,
false);
}
}
else
{
if (vuesDocumentCirculation.GetActiveView().Equals(vueChargement))
{
EditionDocCirculation.AffectationParametresV3(rd,
(DocCirculation)Session[sSession.DocumentCirculation],
Master.ElevageCours,
txtNbAgneauxOvinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbAgneauxOvinsCharge.Text),
txtNbReproducteursOvinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbReproducteursOvinsCharge.Text),
txtNbAgneauxCaprinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbAgneauxCaprinsCharge.Text),
txtNbReproducteursCaprinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbReproducteursCaprinsCharge.Text),
0,
BaseWOC,
Master.UtilisateurCours.EnDemo ? Coord_ARSOE : null,
true);
}
else
{
EditionDocCirculation.AffectationParametresV3(rd,
(DocCirculation)Session[sSession.DocumentCirculation],
Master.ElevageCours,
txtNbAgneauxOvinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbAgneauxOvinsDecharge.Text),
txtNbReproducteursOvinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbReproducteursOvinsDecharge.Text),
txtNbAgneauxCaprinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbAgneauxCaprinsDecharge.Text),
txtNbReproducteursCaprinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbReproducteursCaprinsDecharge.Text),
txtNbMortsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbMortsDecharge.Text),
BaseWOC,
Master.UtilisateurCours.EnDemo ? Coord_ARSOE : null,
false);
}
}
if (ds.dtListeBoucles.Count == 0)
rd.DataDefinition.FormulaFields["AFFBOUCLES"].Text = "'0'";
else
{
// Affichage de la liste des boucles
rd.DataDefinition.FormulaFields["AFFBOUCLES"].Text = "'1'";
rd.Subreports[0].SetDataSource(ds);
rd.Subreports[1].SetDataSource(ds);
}
// Affichage de l'aperçu
rd.Export(Editions.OptionsImpression(this.Request.PhysicalApplicationPath + "Editions\\" + objname + "\\DocCirculation.pdf"));
//}
//catch (Exception e)
//{
// String str = string.Empty;
// str = "L'appel à la fonction CreerEtat_DocCirculation a levé l'exception suivante : " + e.ToString();
// Exception ex = new Exception(str);
// Session["LastError"] = ex;
// ScriptManager.RegisterStartupScript(this, typeof(string), "ErrApplication", "window.open('/WOC/WOC/PopUp/ErreurInterne.aspx','Params','resizable=no,width=400,height=270');", true);
//}
}
Without seeing the code we cannot determine the reason for this exception. with this exception , a simple idea is that the location of the report too be created is not exist and unavailable or dont have permission

stack smashing error

This is my code:
#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *server = "nope";
char *user = "nope";
char *password = "nope";
char *database = "nope";
unsigned int port = 0;
int cprint(char *text){//Imprime como encabezado el numero de productos sin stock sumado al argumento
MYSQL *conn;
MYSQL_RES *res;
my_ulonglong num;
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, port, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/* send SQL query */
if (mysql_query(conn, "SELECT id FROM productos WHERE stock <= 0")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_store_result(conn);
num = mysql_num_rows(res);
printf("\n===============================\n\n");
if(num > 0){
printf("Productos sin stock: %llu\n",num);
}
else{
printf("No hay productos sin stock\n");
}
printf("\n===============================\n\n%s",text);
/*close connection */
mysql_free_result(res);
mysql_close(conn);
return 0;
}
char *remove_newline(char *s)
{
int len = strlen(s);
if (len > 0 && s[len-1] == '\n') // if there's a newline
s[len-1] = '\0'; // truncate the string
return s;
}
int newproduct(){
char *name = malloc(127*sizeof(char));//nombre del producto
char *desc = malloc(127*sizeof(char));//descripcion del producto
double price;//precio del producto
cprint("Agregar nuevo producto\n\n");
printf("Nombre del producto: ");
fgets(name, 127, stdin);
name = remove_newline(name);
printf("Descripcion: ");
fgets(desc, 127, stdin);
name = remove_newline(desc);
printf("Precio: ");
scanf("%e", &price);
MYSQL *conn;
conn = mysql_init(NULL);
printf("Mysql initiated\n");
if (!mysql_real_connect(conn, server,
user, password, database, port, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
printf("connection established\n");
char rname[256];//string donde guardar el nombre con caracteres de escape
char rdesc[256];
printf("Vars declared\n");
mysql_real_escape_string(conn,rname,name,256);//se agregan los caracteres de escape
printf("name escaped\n");
mysql_real_escape_string(conn,rdesc,desc,256);
printf("desc escaped\n");
/*
char *query;//donde guardar el query
snprintf(query,1000,"INSERT INTO productos (nombre,descripcion,stock,precio) VALUES( %s,%s, 0, %e)",rname,rdesc,price);//query a enviar
if (mysql_query(conn, query)) {//enviar el query
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}*/
mysql_close(conn);
printf("Mysql closed\n");
return 0;
}
int main(){
printf("Sales Assistant Alpha v0.0\n");//Nombre y version del programa
unsigned int choice;//numero de eleccion del menu
char *err = NULL;//Error
while(1){//loop infinito
cprint("Menu Principal\n\n");//imprime el encabezado
printf("1-Agregar nuevo producto\n");
printf("2-Editar producto existente\n");
printf("3-Productos sin stock\n");
printf("4-Agregar pedido\n");
printf("5-Salir de la aplicacion\n\n");
if(err != NULL){//evalua si hubo un error y lo imprime
printf("%s\n",err);
err = NULL;
}
printf("Numero de eleccion: ");
scanf("%i",&choice);//pide eleccion
if (scanf("%*[^\n]") != EOF){//read and discard all non-newlines
scanf("%*c"); //then read and discard the newline
}
switch(choice){//evalua la eleccion y ejecuta la funcion correspondiente
case 1:
newproduct();
printf("returned\n");
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
exit(0);//termina el programa
break;
default:
err = "Eleccion no valida";//error
break;
}
}
return 0;
}
And the console execution:
Sales Assistant Alpha v0.0
===============================
Productos sin stock: 3
===============================
Menu Principal
1-Agregar nuevo producto
2-Editar producto existente
3-Productos sin stock
4-Agregar pedido
5-Salir de la aplicacion
Numero de eleccion: 1
===============================
Productos sin stock: 3
===============================
Agregar nuevo producto
Nombre del producto: a
Descripcion: a
Precio: 1
Mysql initiated
connection established
Vars declared
name escaped
desc escaped
Mysql closed
*** stack smashing detected ***: ./sales_assistant terminated
Aborted (core dumped)
------------------
(program exited with code: 134)
Press return to continue
i have this stack smashing thing that is unknown to me. Besides that i want to know how much memory i can safely allocate without getting bus error.
IMPORTANT:when i disable the mysql_real_escape_string functions the code works normally, so the problem is there, but i dont know what the problem is.
thanks, matt.
edited
Added the complete code and translated to english. Also changed the question because i got a new error. Added debugging code.
When you ask for a number with scanf("%i", &choice); (the result of which should be checked!), you leave the newline behind. When you read a line with fgets() in newproduct(), it reads the newline left behind.
Ultimately, if you're doing line-based inputs, use fgets() or readline() (from POSIX 2008) to read the line and sscanf() to parse the line.
your malloc() is wrong for a (char*)
should be:
char *name = malloc(127*sizeof(char));//nombre del producto
char *desc = malloc(127*sizeof(char));
The problem was indeed mysql_real_escape_string(). the thing was that the length argument must be the *from lenght instead of the *to lenght like i was doing. im very happy that i worked that thing out, i was getting really frustrated.