Tedious node.js SQL connection; want to insert multiple values from an array - sql

I'm running a loop and trying to insert the multiple values from an array while running it.
Here is the code:
function GetJobsToCourseID(index, jobData){
if((jobData != undefined)||(jobData != null)){
var extrArray = [];
for(var i = 0 ; i< jobData.length; i++){
extrArray = jobData[i];
for (var j=0; j<extrArray.length; j++)
{
console.log(extrArray[j]);
requestID = new Request("SELECT IDKey from dbo.Jobz where SubJobFamily ='"+extrArray[j]+"'", function(err, rowCount){
if (err) {
console.log(err);
}
else { connection111.reset(function(err){});
}
});
}
}
}
requestID.on('row', function(columns) {
for (var i = 0; i <columns.length; i++)
{
console.log(columns[i].value, "Please work");
if (columns[i].value == null || columns[i].value == undefined) {
console.log('NULL');
} else {
}
}
connection111.execSql(requestID);
});
}
As you can see I'm trying to insert the j element of my tempArray(I dont think it should work anyways, because of how Tedious connections work)
What would be the approach then - extracting each array element and populating it withing the SQL table using Tedious?

Fixed it by adding a connection pool and an changing the second loops var j to let j ... 'tedious' is really tedious...
here is the code:
function GetJobsToCourseID(index, jobData){
if((jobData != undefined)&&(jobData != null)){
var extrArray = [];
var newArray = [];
for(var i = 0 ; i< jobData.length; i++){
extrArray = jobData[i];}
for (let j=0; j<extrArray.length; j++){
pool.acquire(function (err, connection1111) {
if (err)
console.error(err);
requestID = new Request("SELECT IDkey from dbo.Jobz where SubJobFamily ='"+extrArray[j]+"'", function(err, rowCount){
if (err) {
console.log(err);
}
else {connection1111.reset(function(err){});}});
requestID.on('row', function(columns) {
for (var i = 0; i <columns.length; i++){
if (columns[i].value == null || columns[i].value == undefined) {
console.log('NULL');
} else {
arty.push(columns[i].value);
console.log(arty);
}}
});
connection1111.execSql(requestID);
});}
pool.on('error', function (err) {
console.error(err);
});
}}

Related

QnA maker get answer from multiple kb

Currently i am getting response from single kb in QnA maker.
Current code.
QnAMaker _qnaservice = new QnAMaker(new QnAMakerEndpoint
{
EndpointKey = _qnaconfig.AuthKey,
Host = _qnaconfig.EndPoint,
KnowledgeBaseId = "{KBID}"
}, new QnAMakerOptions { Top = 3, StrictFilters = channelData.Filters?.ToArray() });
var response = await _qnaservice.GetAnswersAsync(stepContext.Context);
Is there any option to get results from multiple KBs?
The code you have there pulls the top three answers from just the one kb you have from KBID. You have to code to show three answers, and if you're scorethreshold isn't set, its going to return the answer that's something around 0.3 or higher. Then to display them in chat you're going to have to basically iterate through them. For example:
var options = new QnAMakerOptions { Top = 3, ScoreThreshold=0.0F };
var httpClient = _httpClientFactory.CreateClient();
var qnaMaker = new QnAMaker(new QnAMakerEndpoint
{
KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
EndpointKey = _configuration["QnAEndpointKey"],
Host = _configuration["QnAEndpointHostName"]
},
options,
httpClient);
_logger.LogInformation("Calling QnA Maker");
// The actual call to the QnA Maker service.
var response = await qnaMaker.GetAnswersAsync(turnContext);
if (response != null && response.Length > 0)
{
for (int i = 0; i < response.Length; i++)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response[i].Answer), cancellationToken);
}
}
For my KB, this shows:
Now, if you want to show top three answers from multiple KBs, you're going to have to construct multiple QnAMakers
var qnaMaker = new QnAMaker(new QnAMakerEndpoint
{
KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
EndpointKey = _configuration["QnAEndpointKey"],
Host = _configuration["QnAEndpointHostName"]
},
options,
httpClient);
var qnaMaker2 = new QnAMaker(new QnAMakerEndpoint
{
KnowledgeBaseId = _configuration["QnAKnowledgebaseId2"],
EndpointKey = _configuration["QnAEndpointKey"],
Host = _configuration["QnAEndpointHostName"]
},
options,
httpClient);
//LATER IN CODE:
var response = await qnaMaker.GetAnswersAsync(turnContext);
var response2 = await qnaMaker2.GetAnswersAsync(turnContext);
if ((response != null && response.Length > 0) && (response2 != null && response2.Length > 0))
{
await turnContext.SendActivityAsync(MessageFactory.Text("Answers from KB1:"), cancellationToken);
for (int i = 0; i < response.Length; i++)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response[i].Answer), cancellationToken);
}
await turnContext.SendActivityAsync(MessageFactory.Text("Answers from KB2:"), cancellationToken);
for (int i = 0; i < response2.Length; i++)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response2[i].Answer), cancellationToken);
}
}
else if (response != null && response.Length > 0)
{
await turnContext.SendActivityAsync(MessageFactory.Text("Answers from JUST KB1:"), cancellationToken);
for (int i = 0; i < response.Length; i++)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response[i].Answer), cancellationToken);
}
}
else if (response2 != null && response2.Length > 0)
{
await turnContext.SendActivityAsync(MessageFactory.Text("Answers from JUST KB2:"), cancellationToken);
for (int i = 0; i < response2.Length; i++)
{
await turnContext.SendActivityAsync(MessageFactory.Text(response2[i].Answer), cancellationToken);
}
}
else
{
await turnContext.SendActivityAsync(MessageFactory.Text("No QnA Maker answers were found."), cancellationToken);
}
Then just do the same length check, and SendActivities for each:

I want to generate and send multiple responses to client side

I am using Angular for client side and Node and express server for server side and Mongo database..
In my project I want to give some conditions before data to be saved and generate multiple responses as per needed..
I try res.write but give error ..I post my code..In my code I want to send response instead of console.log
router.post('/addratio',(req,res)=>{
var requestbody = req.body.items;
res.setHeader("Content-Type", "text/plain");
// first, convert data into a Map with reduce
let counts = requestbody.reduce((prev, curr) => {
let count = prev.get(curr.Emp_id) || 0;
prev.set(curr.Emp_id, curr.ValueRatio + count);
return prev;
}, new Map());
// then, map your counts object back to an array
let reducedObjArr = [...counts].map(([Emp_id,ValueRatio]) => {
return {Emp_id, ValueRatio}
});
/**/
if(reducedObjArr.length > 0){
AddRatioPickPoint.find({},(err,found)=>{
for(var i=0;i<reducedObjArr.length;i++){
var Empid = reducedObjArr[i].Emp_id;
var Ratio = reducedObjArr[i].ValueRatio;
if(Ratio < 100){
if(found.find(x=>x.Emp_id == Empid)){
var oldRatio = found.find(y=>y.Emp_id == Empid).ValueRatio;
console.log(oldRatio);
if(oldRatio < 100){
var addtion = oldRatio + Ratio;
//console.log(addtion);
if(addtion < 100){
AddRatioPickPoint.updateMany({ "Emp_id":Empid },{$set: { "ValueRatio":addtion}},(err,change)=>{
if(change){
console.log("there is change");
}
})
}
if(addtion == 100){
AddRatioPickPoint.updateMany({ "Emp_id":Empid },{$set: { "ValueRatio":addtion}},(err,change)=>{
if(change){
console.log("there is change");
}
});
EmployeeSchema.updateMany({"_id":Empid},{$set: { "status":false}},(err,change)=>{
if(change){
console.log("there is Emp Status change");
}
});
}
}
}
if(!found.find(x=>x.Emp_id == Empid)){
AddRatioPickPoint.insertMany({Emp_id:Empid,ValueRatio:Ratio},(err,add)=>{
if(add){
console.log("New Addition of reqbody success");
}
});
}
}
if(Ratio == 100){
if(!found.find(t=>t.Emp_id == Empid)){
EmployeeSchema.updateMany({"_id":Empid},{$set: { "status":false}},(err,change)=>{
if(change){
console.log("there is Emp Status change");
}
});
AddRatioPickPoint.insertMany({Emp_id:Empid,ValueRatio:Ratio},(err,add)=>{
if(add){
console.log("New Addition of reqbody success");
}
});
}
if(found.find(t=>t.Emp_id == Empid)){
var oldRatio = found.find(t=>t.Emp_id == Empid).ValueRatio;
console.log(oldRatio);
console.log("not store");
}
}
}
for(var i=0;i<requestbody.length;i++){
var reqEmpID =requestbody[i].Emp_id;
var reqValueRatio = requestbody[i].ValueRatio;
var reqClient = requestbody[i].NameClient;
var reqEmp = requestbody[i].NameEmployee;
var Alldata = {Emp_id:reqEmpID,NameEmployee:reqEmp,NameClient:reqClient,ValueRatio:reqValueRatio};
if(requestbody[i].ValueRatio == 100){
RatioSchema.insertMany(Alldata,(err,add)=>{
if(add){console.log("Ratio data added");}
});
}
if(requestbody[i].ValueRatio < 100){
RatioSchema.insertMany(Alldata,(err,add)=>{
if(add){console.log("Ratio data added");}
})
}
}
})
}
});
You need to use res.send().
if(change){
res.send("there is change");
};
for more information: res.send

calling a function inside mongoose hook 'post save' returns same doc

In my schema I'm having a post save hook like
DateInfoSchema.post('save', function (doc) {
var newDoc = helper. getListTimeRate(doc);
console.log(newDoc);
});
Then I'm having a helper module in that I'm having a function to calculate date range
lets consider 'doc' startdate and enddate so I want to calculate date range from start date to enddate
module.exports = {
getListTimeRate: function (data, yearEndDate) {
var toDate = new Date(),
weekName = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
Date.prototype.addDays = function(days) {
var dateAdd = new Date(this.valueOf());
dateAdd.setDate(dateAdd.getDate() + days);
return dateAdd;
};
function getDates(startDate, stopDate) {
var dateArray = [];
var currentDate = startDate;
if (currentDate == undefined){
while (currentDate <= stopDate) {
dateArray.push(currentDate);
currentDate = currentDate.addDays(1);
}
return dateArray;
}else {
var newCurrentDate = new Date(currentDate.toISOString().substr(0,10));
var newStopDate = new Date(stopDate.toISOString().substr(0,10));
while (newCurrentDate <= newStopDate) {
dateArray.push(newCurrentDate);
newCurrentDate = newCurrentDate.addDays(1);
}
return dateArray;
}
}
function calcRange(entry) {
// function get time
var dateList = [],
newList = [];
if (toDate < entry.endDate) {
// calc from endDate
newList = getDates(entry.startDate, entry.endDate);
//status often
selectDateFromOften();
} else {
if (yearEndDate) {
newList = getDates(entry.startDate, entry.endDate);
} else {
newList = getDates(entry.startDate, toDate);
}
// calc from toDate
//status often
selectDateFromOften();
}
function getDateTimeAnother() {
if (entry.hour) {
var setHour = entry.hour.getHours(),
setMin = entry.hour.getMinutes(),
setSecond = entry.hour.getSeconds();
}
dateList.forEach(function(entryDate){
entryDate.setHours(setHour);
entryDate.setMinutes(setMin);
entryDate.setSeconds(setSecond);
});
entry.rangeDate = dateList;
var compareUsedDate = [];
_.forEach(entry.frequencyId, function(value) {
compareUsedDate.push(value.dateRated);
});
entry.rangeDate = _.differenceBy(entry.rangeDate, compareUsedDate,Math.floor);
entry.rangeDate = entry.rangeDate.filter(function( element ) {
return element !== undefined;
});
console.log(dateList);
if (yearEndDate) {
return dateList;
}
}
function selectDateFromOften() {
switch(entry.oftenStatus) {
// Daily
case "0":
for (var i = 0; i< newList.length; i++) {
dateList.push(newList[i]);
}
getDateTimeAnother();
break;
//Weekly
case "1":
for (var i = 0; i< newList.length; i++) {
if (i == 0 || i % 7 == 0) {
dateList.push(newList[i]);
}
}
getDateTimeAnother();
break;
//Bi-Weekly
case "2":
for (var i = 0; i< newList.length; i++) {
if (i == 0 || i % 14 == 0) {
dateList.push(newList[i]);
}
}
getDateTimeAnother();
break;
//Monthly
case "3":
// for (var i = newList.length-1; i >= 0; i--) {
for (var i = 0; i< newList.length; i++) {
if (i == 0 || i % 28 == 0) {
dateList.push(newList[i]);
}
}
getDateTimeAnother();
break;
//Custom Date
case "4":
dateList = newList;
getDateCustom();
break;
default:
}
}
}
if (data.length) {
_.forEach(data, function(entry) {
if(entry.startDate != undefined){
calcRange(entry);
}
});
} else {
if(data.startDate != undefined){
calcRange(data);
}
}
return data;
}
};
But inside the hook 'newDoc' doesn't have 'rangeDate' field in it. Can anyone help me solve this issue? Thank you.

how to execute a function after end another in react native?

I have a query that I have a function which response to a server, so it takes a while and when it tries to execute the other function, an error occurs. Since the function responds an array from which comes from the server and when the other function requests that, even It does not have. Have to solve this. example :
responseServer(tarea) {
return fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({ refresh: false })
global.refresh = false
let data = [];
let Milestone = [];
Object.values(responseJson.summary).forEach(item => {
data = data.concat(item);
});
const result = ["Milestone"]
.reduce((total, category) => ({
...total,
[category]: data.filter(line => line.includes(category))
}), {})
Object.values(result.Milestone).forEach(item => {
Milestone = Milestone.concat(item)
});
this.setState({
Milestone: Milestone
})
})
}
and another function
sacarPorcentaje(item) {
this.responseServer(item)
let summaryCopy = this.state.Milestone.map(data => {return data.split(",")})
console.log(summaryCopy)
var Okeys = 0;
var total = 0;
for (var i = 0; i < summaryCopy.length; i++){
for(var j = 0; j < summaryCopy[i].length; j++){
if(summaryCopy[i][j] === "OK") {
Okeys = Okeys + 1
}
}
total = total + 1
}
console.log(Okeys)
console.log(total)
}
You should update sacarPorcentaje() to async function. then await the function call, will resolve your issue
async sacarPorcentaje (item) {
await this.responseServer(item)
let summaryCopy = this.state.Milestone.map(data => {return data.split(",")})
console.log(summaryCopy)
var Okeys = 0;
var total = 0;
for (var i = 0; i < summaryCopy.length; i++){
for(var j = 0; j < summaryCopy[i].length; j++){
if(summaryCopy[i][j] === "OK") {
Okeys = Okeys + 1
}
}
total = total + 1
}
console.log(Okeys)
console.log(total)
}
There is also one more solution for this issue. please search how to use Promise in JS
I think you need to use then when you call responseServer function in sacarPorcentaje function.
sacarPorcentaje(item) {
this.responseServer(item).then(() => {
let summaryCopy = this.state.Milestone.map(data => {return data.split(",")})
console.log(summaryCopy)
var Okeys = 0;
var total = 0;
for (var i = 0; i < summaryCopy.length; i++){
for(var j = 0; j < summaryCopy[i].length; j++){
if(summaryCopy[i][j] === "OK") {
Okeys = Okeys + 1
}
}
total = total + 1
}
console.log(Okeys)
console.log(total)
}
}

How to fetch dynamic table list in MVC and angularJS

I'm getting a list in my angular.js file (EditDeleteItem.js) which I'm making based on the selected table name.
The function to send my list is as below:-
$scope.SaveTblRecord = function (list) {
//alert(JSON.stringify($scope.employeeList));
$scope.FetchTableName();
//var Data = $.param({ TblData: $scope.MyTblDataList });
var itemList = [];
angular.forEach(list, function (value, key) {
if (list[key].selected) {
itemList.push(list[key].selected);
}
});
$scope.ItemsList = [];
$scope.ItemsList = itemList;
$http({
method: "Post",
url: "/Admin/SaveTblData",
data: $scope.ItemsList,
}).success(function (data) {
$scope.GetTblData($scope.TempName);
}).error(function (err) {
alert(err.Message);
})
};//SaveTblRecord
Now in my Controller I want to fetch that list based on the selected table name but I can't do it :-
public JsonResult SaveTblData(List<LocationTbl> NewTblList) //Need To Have TableName here instead of LocationTbl so that selected table name list is fetched.
{
string MyTableName = Convert.ToString(TempData["TableName"]);
try
{
if (NewTblList == null)
{
return new JsonResult { Data = "Empty Selection", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
else {
using (EBContext db = new EBContext())
{
bool results = false;
Type tableType = typeof(CourseDesc);
switch (MyTableName)
{
//case "CourseTbl":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var CtObj = NewTblList[i];
// CourseTbl ct = db.Courses.AsNoTracking().FirstOrDefault(x => x.ID == CtObj.ID);
// results = UtilityMethods<CourseTbl, int>.EditEntity(db, CtObj);
// }
// break;
//case "CourseDescTbl":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var CdtObj = NewTblList[i];
// CourseDesc cd = db.CourseDesc.AsNoTracking().FirstOrDefault(x => x.ID == CdtObj.ID);
// results = UtilityMethods<CourseDesc, int>.EditEntity(db, CdtObj);
// }
// break;
//case "CourseSubDesc":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var CsdObj = NewTblList[i];
// CourseSubDesc csd = db.CourseSubDesc.AsNoTracking().FirstOrDefault(x => x.ID == CsdObj.ID);
// results = UtilityMethods<CourseSubDesc, int>.EditEntity(db, CsdObj);
// }
// break;
//case "InternTbl":
// for (int i = 0; i < NewTblList.Count; i++)
// {
// var ItObj = NewTblList[i];
// InternShip It = db.Interns.AsNoTracking().FirstOrDefault(x => x.ID == ItObj.ID);
// results = UtilityMethods<InternShip, int>.EditEntity(db, ItObj);
// }
// break;
case "LocationTbl":
for (int i = 0; i < NewTblList.Count; i++)
{
var LtObj = NewTblList[i];
LocationTbl lt = db.Loc.AsNoTracking().FirstOrDefault(x => x.ID == LtObj.ID);
results = UtilityMethods<LocationTbl, int>.EditEntity(db, LtObj);
}
break;
}
var resultList = new List<object>();
foreach (var item in db.Set(tableType))
{
resultList.Add(item);
}
return new JsonResult { Data = resultList, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
}
catch (Exception ex)
{
return new JsonResult { Data = ex.Message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
I've been searching the internet for a while and found some related links like Link1
and Link2
But I can't find solution to my problem. Please HELP!!