Getting all Sensors for a Device Robustly - node.js

I'm trying to find out which telemetry-producing sensors (aka singals/time series') are attached to a device using the REST API. The deviceTemplates endpoint has all this information but there is no JSON schema for it's response anywhere. The responses are highly variable and hard to parse. I need a robust solution for any kind of device.
Any help/advice? Could the IoT Hub SDK help?

I would recommend using Json.Net Schema framework. It lets you determine your own custom JSON schema that would fit your needs.
Please refer the following documentation that helps you on how to Load your schema. Once you have the schema determined you can validate it against a device template and confirm if it follows the same pattern.
You can then parse the JSON file using Json.Net to extract the data you may need. Here is sample of the code that extracts contents from a device template. I have used "RS40 Occupancy Sensor.json" device template in my case.
public static void LoadJson()
{
using (StreamReader r = new StreamReader(#"Path to your JSON device template file"))
{
string json = r.ReadToEnd();
try
{
dynamic? array = JsonConvert.DeserializeObject(json);
if (array != null)
{
foreach (var item in array)
{
var contents = item.contents;
//filter contents to get telemetry data or other information
}
}
}
catch (Exception ex) { Console.WriteLine(ex); }
}

Related

generate handwash and toilets with Revit api

Within Revit, there is the possibility of locating toilets or handwash, using the option within the system and plumbing fixture. My question is is there the possibility of creating them using the Revit api? The only thing I've seen is the creation of some types of systems as shown by the following line of code:
public bool createHotWater(Connector baseConector, ConnectorSet set,
Document doc)
{
try
{
using (var trans = new Transaction(doc, "SystemHotWater"))
{
trans.Start();
PipingSystem piping = doc.Create.
NewPipingSystem(baseConector,
set,PipeSystemType.DomesticHotWater);
trans.Commit();
}
return true;
}
catch (Exception e)
{
return false;
}
}
I know that the above code only creates a hot water system, but I would like to know if there is an option to create toilets from the Revit api.
Yes, certainly this can be achieved programmatically as well as manually through the user interface. For this very purpose, the Family API for Creating Family Definitions was introduced in Revit 2010.

How to get single values from am gremlinquery in C# code

I am using gremlin with Azure Cosmos DB. I'm using this code to get a list of files from a graph database.
public async Task<List<string>> GetFilesWithMoreThanOneFilename()
{
List<string> list = new List<string>();
using (var gremlinClient = new GremlinClient(gremlinServer, new GraphSON2Reader(), new GraphSON2Writer(), GremlinClient.GraphSON2MimeType))
{
var resultSet = await gremlinClient.SubmitAsync<dynamic>("g.V().hasLabel('file').where(out().count().is(gt(1)))");
if (resultSet.Count > 0)
{
foreach (var result in resultSet)
{
string output = JsonConvert.SerializeObject(result);
list.Add(output);
}
}
}
return list;
}
The output string looks like this:
{"id":"0a37e4896b6310b6d152f6cf89336173ffb89b819f7955494322e0f0bec017b4","label":"file","type":"vertex","properties":{"fileSize":[{"id":"456b087c-7cf3-43ea-a482-0f31219bc520","value":"41096"}],"mimeType":[{"id":"d849b065-16f8-465b-986c-f8e0fdda9ac7","value":"text/plain"}]}}
My Question is how I can get a single value from the result. For example just the ID or the mimeType or is the only possiblity to work with the output and string manipulation?
Due to your output data is in json format, so you could use Newtonsoft.Json to read the data.
I create a json file with your data, you could just parse the json data without file. And just read the id and properties.fileSize
static void Main(string[] args)
{
JObject jsonData = JObject.Parse(File.ReadAllText( "test.json"));
Console.WriteLine("id:"+jsonData["id"].ToString());
Console.WriteLine("properties:"+jsonData["properties"]["fileSize"].ToString());
Console.ReadLine();
}
And here is the result:
Hope this could help you, if yo ustill have other questions, please let me know.
Update: if you want to get the value in the array, you could use this to get the value:
Console.WriteLine("mimeType.value:" + jsonData["properties"]["mimeType"][0]["value"].ToString());
In general, you should only retrieve the values that you actually need and not vertices with all their properties and then filter locally. This is equivalent to relational databases where you wouldn't usually do SELECT * and instead do something like SELECT name.
Additionally, you should specify the return type you're expecting which allows Gremlin.NET to deserialize the result for you so you don't have to do that yourself.
These two suggestions together give you something like this:
var names = await client.SubmitAsync<string>(
"g.V().hasLabel('person').where(out().count().is(gt(1))).values('name')");
Console.WriteLine($"First name: {names.First()}");
names is then just a ResultSet<string> which implements IReadOnlyCollection<string>.

Autodesk Design Automation API extract Text from DWG file

I would like to use the Autodesk Design Automation API to extract all Text and Header information from a .dwg file into a json object. Is this possible with the Design Automation API?
Any example would help.
Thankyou
#Kaliph, yes, without a plugin in .NET/C++/Lisp code, it is impossible to extract block attributes by script only. I'd recommend .NET. It would be easier for you to get started with if you are not familiar with C++.
Firstly, I'd suggest you take a look at the training labs of AutoCAD .NET API:
https://www.autodesk.com/developer-network/platform-technologies/autocad
pick the latest version if you installed a latest version of AutoCAD. The main workflow of API is same across different versions, though. you can also pick C++ (ObjectARX) if you like.
In the tutorials above, it demos how to work with block. And the blog below talks about how to get attributes:
http://through-the-interface.typepad.com/through_the_interface/2006/09/getting_autocad.html
I copied here for convenience:
using Autodesk.AutoCAD;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
namespace MyApplication
{
public class DumpAttributes
{
[CommandMethod("LISTATT")]
public void ListAttributes()
{
Editor ed =
Application.DocumentManager.MdiActiveDocument.Editor;
Database db =
HostApplicationServices.WorkingDatabase;
Transaction tr =
db.TransactionManager.StartTransaction();
// Start the transaction
try
{
// Build a filter list so that only
// block references are selected
TypedValue[] filList = new TypedValue[1] {
new TypedValue((int)DxfCode.Start, "INSERT")
};
SelectionFilter filter =
new SelectionFilter(filList);
PromptSelectionOptions opts =
new PromptSelectionOptions();
opts.MessageForAdding = "Select block references: ";
PromptSelectionResult res =
ed.GetSelection(opts, filter);
// Do nothing if selection is unsuccessful
if (res.Status != PromptStatus.OK)
return;
SelectionSet selSet = res.Value;
ObjectId[] idArray = selSet.GetObjectIds();
foreach (ObjectId blkId in idArray)
{
BlockReference blkRef =
(BlockReference)tr.GetObject(blkId,
OpenMode.ForRead);
BlockTableRecord btr =
(BlockTableRecord)tr.GetObject(
blkRef.BlockTableRecord,
OpenMode.ForRead
);
ed.WriteMessage(
"\nBlock: " + btr.Name
);
btr.Dispose();
AttributeCollection attCol =
blkRef.AttributeCollection;
foreach (ObjectId attId in attCol)
{
AttributeReference attRef =
(AttributeReference)tr.GetObject(attId,
OpenMode.ForRead);
string str =
("\n Attribute Tag: "
+ attRef.Tag
+ "\n Attribute String: "
+ attRef.TextString
);
ed.WriteMessage(str);
}
}
tr.Commit();
}
catch (Autodesk.AutoCAD.Runtime.Exception ex)
{
ed.WriteMessage(("Exception: " + ex.Message));
}
finally
{
tr.Dispose();
}
}
}
}
I have a sample on making signs on a drawing. It covers getting attributes and modifying attributes:
https://forge.autodesk.com/cloud_and_mobile/2016/02/sign-title-block-of-dwg-file-with-autocad-io-view-data-api.html
And I also have a sample on getting Table cells of a drawing:
https://forge.autodesk.com/blog/get-cell-data-autocad-table-design-automation-api
Hope these could help you to make the plugin for your requirements.
What do you mean by "Header" information? Can you give an example?
Finding an extracting all text objects is relatively easy if you are familiar with the AutoCAD .NET API (or C++ or Lisp).
Here's an example that extracts blocks and layer names:
https://github.com/Autodesk-Forge/design.automation-.net-custom.activity.sample

How to create complex types with Azure Stream Analytics queries

I try to transform flat JSON data from an Event Hub into a DocumentDB. The target structure should look like:
{
"id" : 1
"field_1" : "value_1",
"details" : {
"detail_field_1":"abc",
"detail_field_2":"def"
}
}
Created from source:
{
"id":1,
"field_1" : "value_1",
"detail_field_1":"abc",
"detail_field_2":"def"
}
I checked the documentation of Azure Stream Analytics but there ist no clear description how to create a proper Query.
Who one can help me?
You can leverage the new JavaScript UDF feature to write nested JSON objects to output.
Register a user-defined function, "UDF.getDetails()" as below:
function main(obj) {
//get details object from input payload
var details_obj = {};
details_obj.detail_field_1 = obj.detail_field_1;
details_obj.detail_field_2 = obj.detail_field_2;
return JSON.stringify(details_obj);
}
Then call the UDF in your query to get a string of the nested JSON object.
SELECT
id,
field_1,
UDF.getDetails(input) As details
INTO output
FROM input
Using JavaScript UDF feature, you can return complex JSON.
Example write function.
function main(obj) {
//get details object from input payload
var details_obj = {};
details_obj.detail_field_1 = obj.detail_field_1;
details_obj.detail_field_2 = obj.detail_field_2;
return details_obj;
}
You should not use JSON.stringify since it will make it a string instead of JSON object.
Use it like.
SELECT id, field_1, UDF.getDetails(input) As details
INTO output
FROM input

How to get Azure service pricing details programmatically?

Can anybody please tell me how can I programmatically get Azure service pricing details (pricing for Compute, Data Services , App Services, Network Services) from Azure website?
Does Azure provide the pricing details in JSON format?
Windows Azure does'not provide any such API as of today, although it is a much asked feature and hopefully they are working on it.
Check here:
http://feedback.windowsazure.com/forums/170030-billing/suggestions/1143971-billing-usage-api#comments
The only way for now could be to build your own data store with details mentioned here : http://azure.microsoft.com/en-us/pricing/calculator/
Unit wise price will be mentioned in the usage data csv, but unfortunately the only way for now is to download this csv for your subscription here: https://account.windowsazure.com/Subscriptions
Azure now provides API's to get usage and billing data. You can have a look at this blog which gives an overview of these API's and the feedback form here which contains links to some useful pages.
In summary use the following API's to get usage and billing data:
Resource usage
Resource ratecard
Not sure, if i am too late to answer.
I was looking for the same thing and stumble upon this post on stack overflow: Azure pricing calculator api. I was able to generate JSON string using this git hub repo: https://github.com/Azure-Samples/billing-dotnet-ratecard-api.
Hope this helps!
Late to the party but I found myself looking for this and nothing here got me what I wanted. Then I found this https://learn.microsoft.com/en-us/rest/api/cost-management/retail-prices/azure-retail-prices
It is pretty straight forward. Add the reference to the Json.NET .NET 4.0 to your project It shows up in your references as Newtonsoft.Json
//You will need to add these usings
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
private void btnGetRates_Click(object sender, EventArgs e)
{
string strUrl = "https://prices.azure.com/api/retail/prices?$filter=serviceName eq 'Virtual Machines' and skuName eq 'E64 v4' and reservationTerm eq '3 Years'";
string response = GetDataFromAPI(strUrl);
// Here is am turning the Json response into a datatable and then loading that into a DataGridView.
//You can use the Json response any way you wish
DataTable dt = Tabulate(response);
dgvAzureSKU.DataSource = null;
dgvAzureSKU.DataSource = dt;
}
public string GetDataFromAPI(string url)
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
var response = httpClient.GetStringAsync(new Uri(url)).Result;
return response;
}
}
public static DataTable Tabulate(string json)
{
var jsonLinq = JObject.Parse(json);
// Find the first array using Linq
var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
var trgArray = new JArray();
foreach (JObject row in srcArray.Children<JObject>())
{
var cleanRow = new JObject();
foreach (JProperty column in row.Properties())
{
if (column.Value is JValue) // Only include JValue types
{
cleanRow.Add(column.Name, column.Value);
}
}
trgArray.Add(cleanRow);
}
return JsonConvert.DeserializeObject<DataTable>(trgArray.ToString()); //This is what loads the data into the table
}
You can find some examples for that here https://learn.microsoft.com/en-us/azure/billing/billing-usage-rate-card-overview. Azure provides invoice, usage and ratecard APIs which can help you to do things like:
Azure spend during the month
Set up alerts
Predict bill
Pre-consumption cost analysis

Resources