node-red-node-firebird returns a buffer instead of a string - buffer

I'm doing KPI's in node-red, and I'm using node-red-node-firebird to connect my database and get the results from it. For that I made a query to select the columns I need, one of those is:
NAME Varchar(40), with an example value: "Pizzas"
(example: Select NAME from mytable)
When I receive the query response on node-red, I store it inside the msg.payload. The problem is the result that I get it isn't the string "Pizzas" but a buffer "NAME":{"type":"Buffer","data":[80,105,122,122,97,115]}}.
How can I get the string and not the buffer?
I already tried a lot of things, among them:
On the query I have tried cast(NAME AS varchar(40)) AS NAME; [NAME] without success. Put msg.payload.data.toString('utf-8') in function node but nothing happens, the function:
var objectData = msg.objectData; //this is the query response
//------------Columns----------------------------
var fields = [];
var i = 0;
if(objectData.length > 0) {
var data = objectData[0];
for(var key in data) {
fields[i] = key;
i++;
}
//TRY nº1
objectData.foreach(function(obj){
if (Buffer.isBuffer(obj) === true) {
obj = obj.toString('utf-8');
}
})
}
//-----------------------------------------
msg.method = "POST";
msg.url = //My api request//;
msg.headers = {};
msg.headers["Content-Type"] = "application/json";
msg.headers.Authorization = //auth//;
msg.payload = {
'groupID': 'Group123',
'companyID': 1221,
'table': 'DemoTable',
'fields': fields,
'data': objectData, //problem
'delete': true,
};
//TRY nº2
msg.payload = msg.payload.data.toString('utf-8');
return msg;

I solved my problem changing the select to:
SELECT cast(name as varchar(100) character set win1252) NOME FROM mytable
Thanks for the help :)

Related

Insert time stamp and user name (or email) on google sheets

I looking for script, that will create audit log in another sheet. In this log it should be:
1)Time stamp
2)User who edited cell
3)The value of the edited cell
I tryed many of tutorial, but I am really new in this and little lost.
This script will log all activities in the sheet "Logging"
function onEdit(e) {
var email = Session.getEffectiveUser().getEmail();
var timeZone = Session.getScriptTimeZone();
var key = Session.getTemporaryActiveUserKey();
var sName = e.source.getActiveSheet().getSheetName();
if(sName !== "Logging") {
var value;
var mA1 = e.range.getA1Notation().split(":")[0];
if(typeof(e.value) == 'string') {
var aCell = e.source.getRange(mA1);
value = aCell.getValue();
var form = "'" + aCell.getFormula();
} else {
value = e.value;
}
var data = [sName, mA1, timeZone, email, key, value, form];
e.source.getSheetByName("Logging").appendRow(data);
}
}

How can I get originalvalues from EF savechanges for complex primary key

i've implemented audit log for all my db objects but i'm running into an issue because of a special case.
i have code similar to the following.
private IEnumerable<CDMA_CHANGE_LOG> GetAuditRecords(DbEntityEntry ent, string userId, string primaryKeyId, bool updateFlag, object originalEntity)
{
List<CDMA_CHANGE_LOG> result = new List<CDMA_CHANGE_LOG>();
string changeId = Guid.NewGuid().ToString();
TableAttribute tableAttr = ent.Entity.GetType().GetCustomAttributes(typeof(TableAttribute), false).SingleOrDefault() as TableAttribute;
// Get table name (if it has a Table attribute, use that, otherwise get the pluralized name)
string entityName = tableAttr != null ? tableAttr.Name : ObjectContext.GetObjectType(ent.Entity.GetType()).Name;
var changeTime = DateTime.UtcNow;
if (ent.State == EntityState.Modified)
{
foreach (var prop in ent.OriginalValues.PropertyNames)
{
//we cant use this because getdatabasevalues will error out when there are 2 rows in the db for this primarykey (U,A)
//var originalValue = ent.GetDatabaseValues().GetValue<object>(prop) == null ? "" : ent.GetDatabaseValues().GetValue<object>(prop).ToString();
var currentValue = ent.CurrentValues[prop] == null ? "" : ent.CurrentValues[prop].ToString();
// For updates, we only want to capture the columns that actually changed
var primaryKey = GetPrimaryKeyValue(ent);
if (originalValue != currentValue)
{
result.Add(new CDMA_CHANGE_LOG()
{
USERID = userId,
DATECHANGED = changeTime,
EVENTTYPE = "M", // Modified
ENTITYNAME = entityName,
PRIMARYKEYVALUE = primaryKey.ToString(),
PROPERTYNAME = prop,
OLDVALUE = originalValue,
NEWVALUE = currentValue,
CHANGEID = changeId
});
}
}
}
return result;
}
now i cant use originalValue = ent.GetDatabaseValues().GetValue(prop) because the records have two fields as primary key so i thought i could query the original value manually from the controller and send as
object originalEntity
so i'm wondering how do i cast originalEntity to the current entity
var originalValues = Convert.ChangeType(originalEntity, ent.GetType());
does not work.
i'm finding it difficult to get. thanks for any help.

Indexing into NSArray with JSON object

I receive an object that is sent as a pointer to a collection.
I can access the fields directly as an NSDictionary.
The emails field is sent as an array, and I receive it in parentheses. Currently I get the emailaddress by what I feel is a roundabout method.
How can I most efficiently get to the email address?
let allDoc = users.allDocuments[0]
print("allDoc: \(allDoc)")
let emailsArray = users.allDocuments[0].valueForKey("emails") as! NSArray
print("emailsArray: \(emailsArray)")
let emailAddress = emailsArray[0]["address"] as! String
print("emailAddress: \(emailAddress)")
Console output:
allDoc: <METDocument key: <collection: users, ID: kzzw3vcqukD62xEyz>, fields: {
emails = (
{
address = "xxxx#gmail.com";
verified = 1;
}
);
profile = {
address = {
city = "";
country = nor;
lineOne = "";
lineTwo = "";
zip = "";
};
card = {
last4 = 4242;
verified = 1;
};
filledOut = 1;
name = {
first = XXXX;
last = XXXX;
};
phone = 9999999999;
validated = 1;
};
}>
emailsArray: (
{
address = "xxxx#gmail.com";
verified = 1;
}
)
emailAddress: xxxx#gmail.com
If you just want the email address you could simply do:
let emailsAddress = users.allDocuments[0]["emails"][0][#"address"] as! String
print("emailAddress: \(emailAddress)")
But it really is better to use multiple lines. It makes the code much easier to read and debug. Also, putting all that onto one line doesn't allow any error checking. What if the #"emails" key has an empty array, for example? The code will crash.

BreezeJS "WHERE value IN array"

Can specify in the where clause that I want the data that has the column value equal to some values from an array?
For example:
EntityQuery.from('Customers')
.where('DepartmentID','in','[3,5,6]');
Or how else should I do it efficiently since the table has a lot of entries an it wouldn't be efficient to retrieve all of them? Is it efficient if I do it one by one?
Using Breeze's new JSON query feature introduced in 1.5.1, you can create a “WHERE value IN array” clause like this:
var jsonQuery = {
from: 'Customers',
where: {
'DepartmentID': { in: [3,5,6] }
}
}
var query = new EntityQuery(jsonQuery);
Just add multiple predicates -
var myArray = [3, 4, 5];
var predicate = new Breeze.Predicate;
var query = EntityQuery.from('Customers');
if (myArray) {
var criteriaPredicate = null;
$.each(myArray, function (index, item) {
criteriaPredicate = (index === 0)
? Predicate.create('DepartmentId', '==', item)
: criteriaPredicate.or('DepartmentId', '==', item);
if (Predicate.isPredicate(criteriaPredicate)) {
predicate = predicate.or(criteriaPredicate);
}
});
}
query = query.where(predicate);
That may not run 100% correctly but should show you what to do - create predicates dynamically and add them to a total predicate and then to the query.
A bit late to the party but I needed the same thing as was able to do it like this:
public getFeaturedRestaurants(restaurantIds: number[]) {
this.dataBreezeService.initialiseQuery('getFeaturedRestaurants', [restaurantIds]);
let query = new EntityQuery()
.from('restaurants')
.where("restaurantId", "in", restaurantIds)
.toType('Restaurant')
.expand('foodType, suburb.city')
return this.dataBreezeService.executeQueryCacheOrServerForList(query, false);
}

How to remove [ from beginning and end of the array using split function in c#

An array of Image Url path:
["http://cdncms.fonts.net/hero-images/FEX_Hero_Thumb.png ","http://cdncms.fonts.net/hero-images/Wilma_Hero_Thumb.png "]
asp.net mvc Controller :
public ActionResult Extract(string[] name)
{
//List<string> myList = name.ToList<string>();
for(int x = 0; x < name.Length; x++)
{
//string something = name[x];
var item = name[x];
Session["values"] = item;
}
char[] delimiter1 = new char[] { ',' }; // <-- Split on these
string[] array1 = Session["values"].ToString().Split(delimiter1, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in array1)
{
string exts = Path.GetExtension(item); //illegal character
string strRealname = Path.GetFileName(item); illegal character
}
I know this problem due to the presence of [ character at the beginning and last .I have tried but not succeeded .Any idea how to remove this using split function in C#
Assuming that you have correctly identified the problem, you could do this before making it an array:
var values = Session["values"].ToString();
if(values.StartsWith("[")) values = values.Substring(1);
if(values.EndsWith("]")) values = values.Substring(0, values.Length - 1);

Resources