In the Microsoft.Azure.Devices.Provisioning.ClientProvisioningDeviceClient SDK, what is the JSON structure to set displayName? - azure-iot-hub

I am using C# and using the Microsoft.Azure.Devices.Provisioning.ClientProvisioningDeviceClient SDK and trying to set displayName during the call to RegisterAsync(ProvisioningRegistrationAdditionalData, CancellationToken).
I have:
var pnpPayload = new ProvisioningRegistrationAdditionalData
{
JsonData = $"{{ \"modelId\": \"{parameters.ModelId}\", \"displayName\": \"{parameters.DeviceName}\" }}",
};
return await pdc.RegisterAsync(pnpPayload, cancellationToken);
and the JsonData is:
"{ \"modelId\": \"dtmi:iotDevicesAnywhere:MfrAIUTModelIAA5Level_3o3;1\", \"displayName\": \"Test Device 1 - I90\" }"
but it is not setting the display name. What should be the structure of the JSON Data be?

Related

Kraken API authentication sample converted from python to Google apps script is not returning the same output

I am trying to convert python kraken API auth to Google Script to use it in a Google Spreadsheet, but with no luck.
# python sample
def get_kraken_signature(urlpath, data, secret):
postdata = urllib.parse.urlencode(data)
encoded = (str(data['nonce']) + postdata).encode()
message = urlpath.encode() + hashlib.sha256(encoded).digest()
mac = hmac.new(base64.b64decode(secret), message, hashlib.sha512)
sigdigest = base64.b64encode(mac.digest())
return sigdigest.decode()
api_sec = "kQH5HW/8p1uGOVjbgWA7FunAmGO8lsSUXNsu3eow76sz84Q18fWxnyRzBHCd3pd5nE9qa99HAZtuZuj6F1huXg=="
data = {
"nonce": "1616492376594",
"ordertype": "limit",
"pair": "XBTUSD",
"price": 37500,
"type": "buy",
"volume": 1.25
}
signature = get_kraken_signature("/0/private/AddOrder", data, api_sec)
print("API-Sign: {}".format(signature))
# prints API-Sign: 4/dpxb3iT4tp/ZCVEwSnEsLxx0bqyhLpdfOpc6fn7OR8+UClSV5n9E6aSS8MPtnRfp32bAb0nmbRn6H8ndwLUQ==
I ended up with this, but it's not returning the same output.
# google script sample from my sheet
function get_kraken_sinature(url, data, nonce, secret) {
var message = url + Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, Utilities.base64Encode(nonce + data));
var base64Secret = Utilities.base64Decode(secret);
var mac = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message, secret);
return Utilities.base64Encode(mac);
}
signature = get_kraken_signature("/0/private/AddOrder", data, api_sec)
print("API-Sign: {}".format(signature))
# prints API-Sign: Jn6Zk8v41uvMWOY/RTBTrb7zhGxyAOTclFFe7lySodBnEnXErfJgIcQb90opFwccuKDd0Nt1l71HT3V9+P8pUQ==
Both code samples should do the same, and are supposed to output an identical API-Sign key. They are not at this stage, and I am wondering why is that.
I believe your goal is as follows.
You want to convert your python script to Google Apps Script.
In your Google Apps Script, you have already confirmed that the script for requesting works fine. You want to convert get_kraken_signature of your python script to Google Apps Script.
In this case, how about the following modified script?
Modified script:
function get_kraken_sinature(url, data, nonce, secret) {
var str = Object.entries(data).map(([k, v]) => `${k}=${v}`).join("&");
var message = Utilities.newBlob(url).getBytes().concat(Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, nonce + str));
var mac = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message, Utilities.base64Decode(secret));
return Utilities.base64Encode(mac);
}
// Please run this function.
function main() {
const data = {
"nonce": "1616492376594",
"ordertype": "limit",
"pair": "XBTUSD",
"price": 37500,
"type": "buy",
"volume": 1.25
};
var url = "/0/private/AddOrder";
var nonce = "1616492376594";
var secret = "kQH5HW/8p1uGOVjbgWA7FunAmGO8lsSUXNsu3eow76sz84Q18fWxnyRzBHCd3pd5nE9qa99HAZtuZuj6F1huXg==";
var res = get_kraken_sinature(url, data, nonce, secret);
console.log(res)
}
References:
computeDigest(algorithm, value)
computeHmacSignature(algorithm, value, key)

Consume tensor-flow serving inception model using C# client (PREDICT API)

I have been trying to implement a C# client application to interact with Tensorflow serving server for few weeks now with no success. I have a Python client which works successfully but I can not replicate its functionality with C#. The Python client
import requests
#import json
from keras.preprocessing.image import img_to_array, array_to_img, load_img
from keras.preprocessing import image
flowers = 'c:/flower_photos/cars/car1.jpg'
image1 = img_to_array(image.load_img(flowers, target_size=(128,128))) / 255
payload = {
"instances": [{"image":image1.tolist()},
]
}
print("sending request...")
r = requests.post('http://localhost:8501/v1/models/flowers/versions/1:predict', json=payload)
print(r.content)
The server responds correctly. I am using Tensorflow version 1.12.0 with corresponding latest serving image. They are all working fine.
According to REST API documentation, the API structure is given but its not clear to me at all. I need to send the image to server. How could I add the image payload to JSON request in C# ? After going through many sites, I found that image should be in base64string.
So I did the image conversion into base64
private string GetBase64ImageBytes(string ImagePath)
{
using (Image image = Image.FromFile(ImagePath))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
The request portion is as follows : (server responds with metadata correctly for the GET request)
public string PostImageToServerAndClassify(string imageArray)
{
//https://stackoverflow.com/questions/9145667/how-to-post-json-to-a-server-using-c
string result = null;
string ModelName = cmbProjectNames.Text.Replace(" ", "");
string status_url = String.Format("http://localhost:{0}/v1/models/{1}/versions/{2}:predict", txtPort.Text, ModelName, txtVersion.Text);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(status_url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
try
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
// string json = "{"+ #"""instances""" + ": [{" + #"""image""" + #":" + imageArray + "}]}";
// imageArray = #""" + imageArray + #""";
string json = "{ " + #"""instances""" + ": [{" + #"""image""" + #": { " + #"""b64"": """ + imageArray + #"""}}]}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
With the POST request, I get the error message "The remote server returned an error: (400) Bad Request.". Also server terminates its service. In Postman I get
the detailed error info as :
{ "error": "Failed to process element: 0 key: image of \'instances\' list. Error: Invalid argument: JSON Value: {\n \"b64\": \"/9j/4AAQSkZJRgABAQEAAAAAAAD/4QBSRXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAZKGAAcAAAAcAAAALAAAAABVTklDT0RFAABBAHAAcABsAGUATQBhAHIAaw ... .....(image string data)
So this feels like that I am sending the incorrect data format.
Could someone please tell me what is wrong here ? Any example of image conversion and POST request is highly appreciated. I can not find anywhere that base64string format is the right format for the image in TF site. Python client data format is different hence really need to know what is the right format with any reference documents.
The nearest reference I found here with JAVA client but did not work with mine may be due to TF version difference.

Crunchbase Data API v3.1 to Google Sheets

I'm trying to pull data from the Crunchbase Open Data Map to a Google Spreadsheet. I'm following Ben Collins's script but it no longer works since the upgrade from v3 to v3.1. Anyone had any luck modifying the script for success?
var USER_KEY = 'insert your API key in here';
// function to retrive organizations data
function getCrunchbaseOrgs() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Organizations');
var query = sheet.getRange(3,2).getValue();
// URL and params for the Crunchbase API
var url = 'https://api.crunchbase.com/v/3/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
var json = getCrunchbaseData(url,query);
if (json[0] === "Error:") {
// deal with error with fetch operation
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
sheet.getRange(6,1,1,2).setValues([json]);
}
else {
if (json[0] !== 200) {
// deal with error from api
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
sheet.getRange(6,1,1,2).setValues([["Error, server returned code:",json[0]]]);
}
else {
// correct data comes back, filter down to match the name of the entity
var data = json[1].data.items.filter(function(item) {
return item.properties.name == query;
})[0].properties;
// parse into array for Google Sheet
var outputData = [
["Name",data.name],
["Homepage",data.homepage_url],
["Type",data.primary_role],
["Short description",data.short_description],
["Country",data.country_code],
["Region",data.region_name],
["City name",data.city_name],
["Blog url",data.blog_url],
["Facebook",data.facebook_url],
["Linkedin",data.linkedin_url],
["Twitter",data.twitter_url],
["Crunchbase URL","https://www.crunchbase.com/" + data.web_path]
];
// clear any old data
sheet.getRange(5,1,sheet.getLastRow(),2).clearContent();
// insert new data
sheet.getRange(6,1,12,2).setValues(outputData);
// add image with formula and format that row
sheet.getRange(5,2).setFormula('=image("' + data.profile_image_url + '",4,50,50)').setHorizontalAlignment("center");
sheet.setRowHeight(5,60);
}
}
}
This code no longer pulls data as expected.
I couldn't confirm about the error messages when you ran the script. So I would like to show about the clear difference point. It seems that the endpoint was changed from https://api.crunchbase.com/v/3/ to https://api.crunchbase.com/v3.1/. So how about this modification?
From :
var url = 'https://api.crunchbase.com/v/3/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
To :
var url = 'https://api.crunchbase.com/v3.1/odm-organizations?query=' + encodeURI(query) + '&user_key=' + USER_KEY;
Note :
From your script, I couldn't also find query. So if the script doesn't work even when you modified the endpoint, please confirm about it. You can see the detail of API v3 Compared to API v3.1 is here.
References :
API v3 Compared to API v3.1
Using the API
If this was not useful for you, I'm sorry.

Acumatica: How do I get an attachment file from SO Screen using Web API?

I'd folow the example From I200 pdf for a stock item, but I dont' know how to download the file from an Sales Order. Does anybody has a clue?
IN202500Content stockItemSchema = context.IN202500GetSchema();
var commands = new Command[]
{
new Value
{
Value = "AAMACHINE1",
LinkedCommand = stockItemSchema.StockItemSummary.InventoryID
},
new Value
{
FieldName = "T2MCRO.jpg",
LinkedCommand =
stockItemSchema.StockItemSummary.ServiceCommands.Attachment
}
};
var stockItemAttachment =
context.IN202500Export(commands, null, 1, false, true);
You were almost there, in the "stockItemAttachment" variable you should have the content of the file "T2MCRO.jpg" in byte format.
The only thing you have left to do is to write it to your file system.
You can use the following command :
File.WriteAllBytes(Path, Convert.FromBase64String(stockItemAttachment[0][0]));

NetSuite API - How to send tracking number back to Invoice or Sales Order?

I'm integrating a shipping solution with NetSuite via the SOAP API. I can retrieve the shipAddress via the searchRecord call. Now I need to send the tracking number, service used, and cost back into NetSuite. Hoping someone can point me in the right direction as searching hasn't turned up any answers for me. An example XML would be great.
Im pretty much pasting what I was had an external developer attempt to implement as the response but I don't understand how to setup the envelope to receive it within NS on a record...I think this is what is handling the update post to Field:
'
var a = new Array();
a['Content-Type'] = 'text/xml; charset=utf-8';
a['POST'] = '/FedexNSService/Service1.asmx HTTP/1.1';
a['Content-Length'] = data.length;
a['SOAPAction'] = 'https://wsbeta.fedex.com:443/web-services/ship/ReturnFedexLable';
nlapiLogExecution('DEBUG', 'Results', 'data : ' + data);
var response = nlapiRequestURL('http://sonatauat.adaaitsolutions.com/FedexNSService/Service1.asmx?op=ReturnFedexLable', data, a, null,null);
nlapiLogExecution('DEBUG', 'response', response);
var responseXML = nlapiStringToXML(response.getBody());
nlapiLogExecution('DEBUG', 'responseXML', responseXML);
var responseCode = response.getCode();
nlapiLogExecution('DEBUG', 'responseCode', responseCode);
var body = response.getBody();
nlapiLogExecution('DEBUG', 'body', body);
nlapiLogExecution('DEBUG', 'responseXML '+responseXML, 'responseCode : ' + responseCode);
nlapiLogExecution('DEBUG', 'body ', 'body : ' +body);
var imageurl ='';
if(responseXML != null)
{
var rawfeeds = nlapiSelectNodes(responseXML, "//Tracking");
var FileInternalId = nlapiSelectValue(rawfeeds[0], "FileInternalId");
var TrackingIds = nlapiSelectValue(rawfeeds[1], "TrackingIds");
nlapiLogExecution('DEBUG', 'FileInternalId '+FileInternalId, 'TrackingIds : '+TrackingIds );
if(FileInternalId)
{
var image=nlapiLoadFile(5985);
imageurl=image.getURL();
imageurl = ("https://system.netsuite.com"+imageurl);
nlapiLogExecution('DEBUG','image',imageurl);
}
}
return imageurl;
'
In order to update a sales order with the information via SOAP you need to create a sales order object, set the values and call either an update, or an upsert method:
[JAVA]
SalesOrder so = new SalesOrder();
so.setExternalId("externalID"); //This should correspond to the previous external ID for updates.
...set_other_fields_as_required...
WriteResponse wr = ns.getPort().update(so); //ns = _port if you're using the samples
[C#]
var so = new SalesOrder();
so.externalId = "externalID";
...set_other_fields_as_required...
var wr = Service.upsert(so);
PHP should be similar, but I haven't used the PHP toolkit so I can't say for certain.
This should help get you started.