PowerShell System.Xml.Linq Unable to Parse XML to HTML - html

I am currently trying to use to use this script provided to format an HTML table (https://gallery.technet.microsoft.com/scriptcenter/PowerShell-HTML-Notificatio-e1c5759d#content)
I managed to get most of the functions to work but cant get the Add-HTMLTableColor function to work.
The code I am using is the following:
$params = #{
Column = "Used (GB)"
ScriptBlock = {[double]$args[0] -gt [double]$args[1]}}
Get-PSDrive -PSProvider FileSystem | New-HTMLTable -setAlternating $false | Add-HTMLTableColor -Argument 40 -attrValue "background-color:#FFFF99;" #params
However, it throws a Error: Namespace incorrect.
I dug into the script provided on TechNet and noticed that the Parse function of System.Xml.Linq returns on big XML node instead of separate XML node when HTML is passed on. It does state that it requires System.Xml.Linq v2 and I have only managed to find the dll for v3 and v4?
Is the incorrect version the root of the problem or is there another reason why it cant manage to parse the HTML into XML properly? Or is it another problem completely?

I tested another library that uses the System.Xml.Linq dll file from the system. It returned an error also when attempting to use the dll as well.
After replacing the Linq dll requirement with an assmebly import of the Linq functionality, both functions in the both library was working.
As such, it is determined that the Linq dll is not fully compatible with PowerShell and is unable to perfectly parse HTML to XML.
The solution is to either use custom assmebly import (such as the one in this script) or to use a different library all together.

Related

Cast JSON to PowerShell with proper Auto-Completion (IntelliSense)

Is there a way to geth autocompletion with IntelliSense in Visual Studio Code work properly, when I read a json file and cast it to a PowerShell like:
$config = Get-Content "SOME_PATH" | ConvertFrom-Json
$config.attribute1
The problem is that the file needs to be in memory before it can get the structure off the json file and propose attributes.
If I get the code out and execute it in the powershell terminal and then go back to the code editor, the autocompletion works fine.
Currently IntelliSense doesn't do this.
Some of the reasons are because when you are coding, often times the specified file could not exist, be a different test version than expected, the file could be huge, malformed, etc. By default, it is sometimes safer to just not do this.
By running it in the terminal and loading it in memory, you are explicitly telling IntelliSense what you are using, and then it now "knows" about the object, and can then properly suggest the correct properties and attributes.
As #mklement0 suggests, using the keyboard shortcut F8 will conveniently execute the current line/selection in the integrated terminal, which would load the object into memory, and allow you to use IntelliSense in the editor.
To complement HAL9256's helpful answer:
First, some background information; find a working solution in the bottom section.
IntelliSense for variables in Visual Studio Code works if their type is either:
explicitly declared (e.g., [datetime] $var = ...)
or can be inferred from an assigned value.
If an assignment is based on a command (cmdlet, function, script) call, the type can only be inferred from commands with explicitly defined output type(s):
many, but by no means all, cmdlets do declare their output types
functions and scripts must use the [OutputType(<type>)] attribute.
Additionally, with the nondescript [pscustomobject] type returned by ConvertFrom-Json - which has no inherent properties, only those you add on demand; a "property bag" - you only get IntelliSense:
if a variable was assigned from a custom-object literal (e.g., $var = [pscustomobject] #{ one = 1; two = 2 })
if you cast a custom object to a specific type, assuming instances of that type can be constructed from the custom object's properties, something that PowerShell makes easy - see this answer.
Solution with a custom class (PSv5+)
Visual Studio Code's IntelliSense (via the PowerShell Extension) does recognize the members of instances of PS custom classes defined via the PSv5+ class statement.
You can therefore use a custom class to mirror the structure of the JSON object you're loading and convert the [pscustomobject] "property bags" returned by ConvertFrom-Json to an instance of that class by way of a cast.
Note: The inherent limitation of this approach is that your class must anticipate all property names that the underlying JSON objects contain, and the two must be kept in sync; otherwise:
if a property name changes on the JSON side, your code will break if the class definition isn't updated accordingly.
if new properties are added on the JSON side, these will be inaccessible unless the class definition is updated accordingly.
class definitions can either be:
directly embedded in a script
imported from modules via the using module statement (note that using Import-Module does not load a module's classes).
To implement the solution at hand, you can use a class definition in one of two ways:
(a) Define a class directly in your script that matches the structure of the JSON objects, and cast the [pscustomobject] instance returned from ConvertFrom-Json to that type; a variable assigned this way supports IntelliSense.
(b) Wrap the JSON-loading functionality in a module that performs the above inside the module, and passes the class instance out from a function that declares its [OutputObject()] to be of that type; code that imports that module with using module will then get IntelliSense for variables that capture the output from that function.
A simple demonstration of (a):
# Define a class whose properties mirror the underlying JSON.
class Config {
$foo
$bar
}
# Load the JSON and cast the resulting [pscustomobject] to the class.
# Note: This cast only works if the JSON object's set of properties
# is either the same as that of the [Config] type or a subset of it.
[Config] $config = '{ "foo": "bar", "bar": 42 }' | ConvertFrom-Json
# Variable $config supports IntelliSense, because its is now known
# as type Config.
$config. # shows list of properties

building dynamic urls in Karate and writing json output to a file

How to build dynamic urls in Karate feature file? I tried something like this and didn't work.
Feature: PMS API Status Check
Background:
* url baseUrl
* def spirit = 'SANRS'
Scenario: Get guest details.
Given path "'#(spirit)'/reservation/all"
Url is not evaluating to SANRS and goes as spirit. Also how do I change write the json response to a file. I see we can read the file using read(fileName) but did not see examples for writing to a file.
The '#(foo)' notation applies only to JSON, XML or the right-hand-side of a match statement.
Please use it like a normal JS expression:
Given path spirit, 'reservation', 'all'
Please do look at the documentation and examples !
Yes, there is no example for writing to a file, because this is not recommended for tests. If you really want to do this - just write a custom Java or JavaScript function, refer to the docs for "Calling Java".

How do I make a HTTP request in 4D v12 database

My 4D database has a method that calls an external application to make an HTTP request to an API site, e.g. https://somewhere.com/api/?key=somekey&param=someparam. The request returns a JSON response. However, the external application only returns a call success or fail. I am not able to extract the JSON response.
My 4D database is still in version 12 and have no plans to migrate yet to latest version. Is there any way for me to make an HTTP request and get the JSON response? I was thinking of using the built-in PHP engine and make cURL call. Has anybody done this in 4D?
I recommend using Keisuke Miyako's OAuth plugin. https://github.com/miyako/4d-plugin-oauth. It comes with a cURL library and a JSON parsing library. I use it to pull JSON data from an api source. It looks like he's depricated the plug-in but has links to the separate components.
http://sources.4d.com/trac/4d_keisuke/wiki/Plugins/
ARRAY LONGINT($optionNames;0)
ARRAY TEXT($optionValues;0)
C_BLOB($inData;$outData)
$url:="https://api.atsomewhere.com/blahblah"
$error:=cURL ($url;$optionNames;$optionValues;$inData;$outData)
If ($error=0)
$jsonText:=BLOB to text($outData;UTF8 text without length)
$root:=JSON Parse text ($jsonText)
JSON GET CHILD NODES ($root;$nodes;$types;$names)
$node:=JSON Get child by name ($root;"Success";JSON_CASE_INSENSITIVE)
$status:=JSON Get bool ($node)
If ($status=1)
$ResponseRoot:=JSON Get child by name ($root;"Response";JSON_CASE_INSENSITIVE)
$node1:=JSON Get child by name ($ResponseRoot;"SourceId";JSON_CASE_INSENSITIVE)
$node2:=JSON Get child by name ($ResponseRoot;"SourceName";JSON_CASE_INSENSITIVE)
$output1:=JSON Get text ($node1)
$output2:=JSON Get text ($node2)
End if
End if
4D v12 has built-in support for PHP. I used the PHP EXECUTE command to call a PHP file. But since 4D v12 PHP does not have native support for cURL I used file_get_contents()
My 4D code is as follows:
C_TEXT($result)
C_TEXT($param1)
C_BOOLEAN($isOk)
$param1:="Tiger"
//someFunction is a function in index.php. $result will hold the JSON return value.
//I pass value "Tiger" as parameter
$isOk:=PHP Execute("C:\\index.php";"someFunction";$result;$param1)
C:\index.php contains the PHP script that 4D v12 will run. The code is
<?php
function someFunction($p1){
$somekey = 'A$ga593^bna,al';
$api_URL = 'https://somewhere.com/api/?key='. $somekey. '&param='.$p1;
return file_get_contents($api_URL);
}
?>
This approach is applicable for GET request. But this already serves my purpose.

How to convert String values to json object in java without using org.json

I'm trying to convert a JSON String value `{"name:ganesh,sex:male,age:22"} ) into key and value set using json in gwt can anyone help me with some ideas please.
Since you don't want to use org.json, I imagine that you need to convert JSON on the client side. If this is the case, you will need to use GWT's JSON libraries. They could be inherited into your GWT project by adding these lines to your .gwt.xml file:
<inherits name="com.google.gwt.json.JSON" />
<inherits name="com.google.gwt.http.HTTP" />
You'll also need to import the com.google.gwt.json packages into your class files.
The getting started guide to using JSON in GWT can be found here. It also provides examples for decoding JSON.
Your string must be of the form
"{'name':'ganesh','sex':'male','age':'22'}"
or
'{"name":"ganesh","sex":"male","age":"22"}'
You can use one of the following ways ...
Use javascript eval. Embed the eval in JSNI
public static native String eatString(String jstring) /*-{
eval("var hello = " + jstring + ";");
return hello;
}-*/;
Pass the String as script in a JSP GWT hosting file. This way, you can only doing once - when the GWT app is loaded with its hosting file. Your JSP will generate the javascript dynamically for each loading.
Place the following in hour GWT hosting html file, before the script tag where GWT module is called.
<script>
var hello = {'name':'ganesh','sex':'male','age':'22'};
</script>
Then in your GWT app, use the GWT Dictionary class to reference any javascript objects declared in the hosting file.
Use the following utilities, in particular JsonRemoteScriptCall.java to read remote, out of SLD-SOP javascript objects into your GWT app. http://code.google.com/p/synthfuljava/source/browse/trunk/gwt/jsElements/org/synthful/gwt/javascript/#javascript%2Fclient.
Please be warned - out of SLD-SOP objects can be hazardous. Read up on Second level domain, same origin policy browser security.
Use RestyGWT and pretend that the data from the server comforms to REST data structure. But of course, use of json.org and google JSON utils has already been done for you.

How can I get the json object which represents a Yahoo! pipe

It seems that Yahoo pipes are represented using JSON. I want to download these JSON objects for some research purpose. Usually a Yahoo pipe is rendered in a browser editor thru a url like this: http://pipes.yahoo.com/pipes/pipe.edit?_id=XgRo96h13BGtJWvS8SvLAg, but you can't get the corresponding JSON object to this Yahoo pipe. Does anyone know how to get JSON objects representing Yahoo pipes and store them in any persistent form?
It is possible to get hold of a JSON description of a Yahoo Pipe using a URL of the form:
http://pipes.yahoo.com/pipes/pipe.info?_out=json&_id=PIPE_ID
The pipe2py python library demonstrates how to grab the JSON description of a pipe and "compile" it to a Python equivalent that can be run on your own server.
The post Exporting Yahoo Pipe Definitions, Compiling Them to Python, and Running Them in Scraperwiki describes how you can use pipe2py in the Scraperwiki environment to compile and execute pipes on Scraperwiki using pipe definitions imported directly from Yahoo Pipes, or exported from Yahoo Pipes and then stored locally in a Scraperwiki database table.
When I load that page in a browser I can see that it makes an ajax request for:
http://pipes.yahoo.com/pipes/ajax.pipe.load?id=XgRo96h13BGtJWvS8SvLAg&_out=json&modinfo=true&rnd=7560&.crumb=MjvGjpzhPLl
That's your object but I'm not sure if I'm answering your question of how to "get it". If you need to get it through a program you would need a script that loges into pipes and extracts that url.
A quick way, while not automated, is to use an HTTP analyzer. Here's a process for getting the object using HttpFox (I use v0.8.9) for Firefox. With the analyzer running, load the edit page for a pipe, like the one you linked:
http://pipes.yahoo.com/pipes/pipe.edit?_id=XgRo96h13BGtJWvS8SvLAg
Look at the request with a URL that starts with:
http://pipes.yahoo.com/pipes/ajax.pipe.load?id=....
Next, explore the content of the request (there's a 'Content' tab in HttpFox). That's the JSON object representing the pipe structure.
Use pipe.run?[your pipe id here]&_render=json as opposed to pipe.edit
So in your case to get the json it would be - http://pipes.yahoo.com/pipes/pipe.run?_id=XgRo96h13BGtJWvS8SvLAg&_render=json
I guess how you implement the client is dependent on what you like writing in/what other functionality you need.
You could also do it the other way around and use the web service service module to post the data to a script that can extract the json and persist it to a database. You could check out json.org.