XDT Transform: InsertBefore - Locator Condition is ignored - web-config

I have a web.config file in which I need to either insert the <configSections /> element or manipulate children of that node if it already exists.
If it already exists I don't want to insert it again (obviously, as it is only allowed to exist once).
Normally, that would not be a problem, however:
If this element is in a configuration file, it must be the first child element of the element.
Source: MSDN.
So if I use xdt:Transform="InsertIfMissing" the <configSections /> element will always be inserted after any existing child elements (and there are always some), violating the above restriction of it having to be the first child element of <configuration />
I attempted to make this work in the following way:
<configSections
xdt:Transform="InsertBefore(/configuration/*[1])"
xdt:Locator="Condition(not(.))" />
Which works perfect, if the <configSections /> element doesn't already exist. However, the condition I've specified seems to be ignored.
In fact, I've tried a few conditions like:
Condition(not(/configuration[configSections]))
Condition(/configuration[configSections] = false())
Condition(not(/configuration/configSections))
Condition(/configuration/configSections = false())
Finally, out of desperation, I tried:
Condition(true() = false())
It still inserted the <configSections /> element.
It is important to note that I'm trying to include this in a NuGet package, so I will be unable to use a custom transform (like the one AppHarbor uses).
Is there any other clever way to get my element in the right place only if it doesn't yet exist?
To test this out, use AppHarbors config transform tester. Replace the Web.config with the following:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="initialSection" />
</configSections>
</configuration>
And Web.Debug.config with the following:
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<configSections
xdt:Transform="InsertBefore(/configuration/*[1])"
xdt:Locator="Condition(true() = false())" />
<configSections>
<section name="mySection" xdt:Transform="Insert" />
</configSections>
</configuration>
The result will show two <configSections /> elements, the one containing "mySection" being the first, as specified in the InsertBefore Transform.
Why was the Locator Condition not taken into account?

So after facing the same issue, I came up with a solution. It's not pretty nor elegant, but it works. (At least on my machine)
I just split the logic into 3 different statements. First, I add an empty configSections at the correct position (first). Then I insert the new config to the last configSections, which would be the new one if it is the only one, or a previously existing one otherwise.
Lastly I remove any empty configSections elemnt which might exist. I'm using RemoveAll for no good reason, you should probably use Remove.
The overall code looks like so:
<configSections xdt:Transform="InsertBefore(/configuration/*[1])" />
<configSections xdt:Locator="XPath(/configuration/configSections[last()])">
<section name="initialSection" xdt:Locator="Match(name)" xdt:Transform="InsertIfMissing" />
</configSections>
<configSections xdt:Transform="RemoveAll" xdt:Locator="Condition(count(*)=0)" />
The question which still remains unanswered is why Locator conditions are not taken into account for InsertBefore. Or why I can't handle an empty match set for InsertBefore, because that would allowed me to do fun things such as
//configuration/*[position()=1 and not(local-name()='configSections')]
Which to be honest is a much clearer way of doing what I want to achieve.

Related

SelectSingleNode relative to root node on passed XML

Given xml of
$xml = [Xml]#"
<Package>
<Copy_Ex>
</Copy_Ex>
<Move_Ex>
<Rules>
<Rule>
<Property>os</Property>
<Operator>-eq</Operator>
<Value>Windows10</Value>
</Rule>
</Rules>
<Task>
<Rules>
<Rule>
<Property>lastWriteTime</Property>
<Operator>-gt</Operator>
<Value>6W</Value>
</Rule>
</Rules>
</Task>
</Move_Ex>
</Package>
"#
I want to be able to select a single node from the xml, say <Move_Ex>, and pass it to a function, then independently access the two <Rules> nodes. I can do that now with
function Test {
param (
[Xml.XmlElement]$task
)
if ($nodeRules = $task.SelectSingleNode('//Rules')) {
Write-PxXmlToConsole $nodeRules
}
if ($taskRules = $task.SelectSingleNode('//Task/Rules')) {
Write-PxXmlToConsole $taskRules
}
}
$task = $xml.SelectSingleNode('//Move_Ex')
Test $task
But // is searching the entire document, NOT just the [Xml.XmlElement] that I passed. So if I have a different <Rules> node in the <Copy_Ex> node, THAT is what gets returned by the first SelectSingleNode(). What I think I need is a way to identify the root node of the passed element, not the entire document. But I can't seem to find a way to do that consistently. My understanding is that while // finds the sequence of nodes anywhere in the document, / only finds it relative to the root node. Which should mean that
$task = $xml.SelectSingleNode('/Move_Ex')
finds only that <Move_Ex> in the root, and if I had another one somewhere else I would be fine. However, that doesn't return anything at all, which has me worried I don't really understand how either / or // works, which makes the chances of getting what I need to work unlikely.
I have looked at the documentation for [Xml.XmlElement] and GetElementsByTagName() seems to be finding just the elements in my passed element. Write-Host "$($task.GetElementsByTagName('Rules').Count)" in the function returns a 2, so not finding any <Rules> node I have put in <Copy_Ex>.
I also tried just dot referencing things, so
Write-PxXmlToConsole $task.Rules
Write-PxXmlToConsole $task.Task.Rules
And that seems to be working also. But again, ONLY when the element being passed is selected with // rather than /, and I worry that in a much more complex XML with hundreds of <Rules> nodes I won't be getting consistent results.
So, two questions...
1: What is the difference between / and // in this situation, and why isn't /Move_Ex working as "expected" in $task = $xml.SelectSingleNode('/Move_Ex')?
2: Is the dot referencing approach the "correct" way to limit my access to just the passed Element? Or is there another/better way?
I should note here that I did verify that // does break down if make the XML more realistic. So with this XML
$xml = [Xml]#"
<Package>
<Copy_Ex>
<Rules>
<Rule>
<Property>os</Property>
<Operator>-eq</Operator>
<Value>WindowsXP</Value>
</Rule>
</Rules>
<PreTask>
<Move_Ex>
<Rules>
<Rule>
<Property>os</Property>
<Operator>-eq</Operator>
<Value>WindowsVista</Value>
</Rule>
</Rules>
<Task>
<Rules>
<Rule>
<Property>lastWriteTime</Property>
<Operator>-gt</Operator>
<Value>8W</Value>
</Rule>
</Rules>
</Task>
</Move_Ex>
</PreTask>
</Copy_Ex>
<Move_Ex>
<Rules>
<Rule>
<Property>os</Property>
<Operator>-eq</Operator>
<Value>Windows10</Value>
</Rule>
</Rules>
<Task>
<Rules>
<Rule>
<Property>lastWriteTime</Property>
<Operator>-gt</Operator>
<Value>6W</Value>
</Rule>
</Rules>
</Task>
</Move_Ex>
</Package>
"#
Where I need to select only the <Move_Ex> in the <Package> node
$task = $xml.SelectSingleNode('/Move_Ex')
selects nothing, while
$task = $xml.SelectSingleNode('//Move_Ex')
selects the <Move_Ex> node nested in <Copy_Ex>, which is not at all what I want and need.
Note that all Write-PxXmlToConsole does is exactly that.
function Write-PxXmlToConsole ($xml) {
$stringWriter = New-Object System.IO.StringWriter
$xmlWriter = New-Object System.Xml.XmlTextWriter $stringWriter
$xmlWriter.Formatting = "indented"
$xml.WriteTo($xmlWriter)
$xmlWriter.Flush()
$stringWriter.Flush()
Write-Host $stringWriter.ToString()
Write-Host
}
EDIT: With respect to my first question, and based on what #Prophet has already said, I realized I was conflating Root NODE and Root ELEMENT, and now I see this in my related links. Some good additional info about Root node, root element, document element, etc.
Maybe I'm missing something or misunderstanding your question, but it seems to me that the answer is very simple:
The difference between / and //:
/ will go to the direct child of the passed argument while // will look for any element below the passed argument.
By default XPath searches starting from the root node. This is why '/Move_Ex' returns nothing. There is no Move_Ex element directly below the root.
To start searching from current node, not from the root, you should put a dot . at the prefix of the XPath expression.
So, to get the Rules nodes inside the passed element you should use this XPath: '//.Rules'

Mybatis Generator's bug: configuration items should be ordered?

If I put "<commentGenerator>" after "<jdbcConnection>", MBG proposed an error that context content should match: blablabla...
But when I put "<commentGenerator>" before "<jdbcConnection>", everything is ok. Here I have something to complain to the official website that if the order of these items is need, why you do not tell us! What an important thing! You r kidding the freshmen. Maybe it is some where I do not know, but this is a key point to build the MBG's configuration file successfully, why not put this NOTE on the top of the tutorial or somewhere eye-catching?
<generatorConfiguration >
<classPathEntry location="D:\mariadb-java-client-1.1.7.jar" />
<context id="db" >
<commentGenerator>
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
</commentGenerator>
<jdbcConnection driverClass="org.mariadb.jdbc.Driver"
connectionURL="jdbc:mariadb://localhost:3306/dbname"
userId="root"
password="password"
/>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- Model Class -->
<javaModelGenerator targetPackage="org.infrastructure.model" targetProject="infrastructure\src\main\java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- XML Files -->
<sqlMapGenerator targetPackage="sqlMap" targetProject="infrastructure\src\main\config">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- DAO -->
<javaClientGenerator type="XMLMAPPER" targetPackage="org.infrastructure.dao" targetProject="infrastructure\src\main\java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- Tables -->
<table tableName="user" domainObjectName="User" ></table>
</context>
</generatorConfiguration>
First of all, in your xml configuration file, it doesn't contains a valid root element, which always should be like <!DOCTYPE .../>. About how to add a correct root element of mybatis generator configuration file, please see example from MyBatis GeneratorXML Configuration File Reference.
If you correctly specified root element such as following:
<!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"
>
This root element contains a typical DTD declaration located at http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd. This is the definition of the order of these items is need. And we are going to see what it looks like.
From line 47 of this document type definition, it defines element named context. The content is as following:
<!--
The context element is used to describe a context for generating files, and the source tables.
-->
<!ELEMENT context (property*, plugin*, commentGenerator?, jdbcConnection, javaTypeResolver?,javaModelGenerator, sqlMapGenerator?, javaClientGenerator?, table+)>
Which obviously defined the order of the element in context, that is:
property*, plugin*, commentGenerator?, jdbcConnection,
javaTypeResolver?,javaModelGenerator, sqlMapGenerator?,
javaClientGenerator?, table+
In this element, all children must occurs as following rules:
+ for specifying that there must be one or more occurrences of the item — the effective content of each occurrence may be different;
* for specifying that any number (zero or more) of occurrences is allowed — the item is optional and the effective content of each occurrence may be different;
? for specifying that there must not be more than one occurrence — the item is optional;
If there is no quantifier, the specified item must occur exactly one time at the specified position in the content of the element.
After we understanding its real meaning, why you could not change the order of commentGenerator and jdbcConnection should be clear.
Maybe you want to know how to make the element out of order, question How to define DTD without strict element order could be useful.
Wish it helpful.

Qlikview REST connector pagination namespaced XML

We have a XML file that is on somewebsite and looks in a way like this (confidential parts stripped)
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<feed xml:base="https://somewebsite.com/crm/" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
<title type="text">Accounts</title>
<id></id>
<updated>2016-02-04T08:36:56Z</updated>
<link rel="self" title="Accounts" href="Accounts" />
<entry>
<title type="text"></title>
<updated>2016-02-04T08:36:56Z</updated>
<author>
<name />
</author>
<content type="application/xml">
<m:properties>
<d:Type>A</d:Type>
<d:UniqueTaxpayerReference m:null="true" />
<d:VATLiability m:null="true" />
<d:VATNumber m:null="true" />
<d:Website m:null="true" />
</m:properties>
</content>
</entry>
<link rel="next" href="https://somewebsite.com/Accounts?$skiptoken=guid'ee6bc390-a8ac-4bbd-8a4d-0a1f04ab9bd3'" />
</feed>
We use the new Rest connector to get the data out of this XML file.
The XML has pagination and every 60 entries you can load the next 60 with the link at the bottom of this xml file.
The problem i have is when, in the REST connector, we want to enable pagination with these setting:
Pagination Type: Next URL
Next URL field path:
/*[name()="feed"]/*[name()="link"][contains(#rel,"next")]/#href
It doesn't seem to work...
side note: the XML file has namespaces so i need to target the elements this way instead of /feed/link/...
I'm using Xpath syntax to target the link href, but maybe this is not the way to go? Or maybe the REST connector isn't using Xpath syntax?
Really hope someone can help me!
Actually it turns out that this seems to be due to a "bug" in the "Qlik REST Connector 1.0" so the pagination doesn't work.
But there is a fix for it:
1) Make sure that the Qlik REST Connector 1.0 connect dialog box has the NextUrl set to:
feed/link/attr:href
2) When the SQL has been generated after using the SELECT-button and going through the wizard you have to modify the sub-SELECT that reads like this:
.....
(SELECT
"attr:rel" AS "rel",
"attr:title" AS "title",
"attr:href" AS href,
"__FK_link"
FROM "link" FK "__FK_link"),
.....
On line 05 you will have to remove the text AS href.
So it should look like this:
.....
(SELECT
"attr:rel" AS "rel",
"attr:title" AS "title",
"attr:href",
"__FK_link"
FROM "link" FK "__FK_link"),
....
3) Find the LOAD statement that loads from this sub-select with a RESIDENT [MasterREST further down in the load script and make sure that the reference to href is changed to [attr:href] - or else you will get an error message while loading.
Should look like this after the change:
[link]:
LOAD [rel],
[title],
[attr:href],
[__FK_link] AS [__KEY_feed]
RESIDENT RestConnectorMasterTable
WHERE NOT IsNull([__FK_link]);
This worked for me:
/*[name()='feed']/*[name()='link'][#rel='next']/#href
Yours should also work actually, maybe whatever you are using does not agree with double quotes instead of single quotes.

XPath: what's the different between "begin with one slash" and "begin with 2 slashes"?

I read some Xpath code, some begin with "/xxxx", some begin with "//xxxx". What're their differences? Do they have different behavior just in "Select" or different also in other behaviors?
I didn't find corresponding explanations on this site, any hints?
Thanks.
Beginning an XPath with one slash will retrieve the root of the document, so that /xxxx will match only the <xxxx> element that is the root of the XML.
Example:
<?xml version="1.0"?>
<xxxx> <!-- this one will match -->
<level>
<xxxx /> <!-- this one won't -->
</level>
</xxxx>
Whereas //xxxx will match all <xxxx> elements anywhere in the document.
Example:
<?xml version="1.0"?>
<xxxx> <!-- this one will match -->
<level>
<xxxx /> <!-- this one will match as well -->
<sublevel>
<xxxx /> <!-- and also this one -->
</sublevel>
</level>
</xxxx>

Adding a VersionOne expression using the REST API

I am trying to create a new 'Expression' in VersionOne - effectively adding a new 'comment' to a conversation.
In theory, the rest-1.v1/Data API should allow this, but I can't figure out how to do it - there is precious little documentation about using the API (using POST) to create objects.
FWIW, here's what I'm doing (after successfully accessing the server with valid credentials):
URL:
/rest-1.v1/Data/Expression
XML:
<Asset href="<Server Base URI>/rest-1.v1/Data/Expression">
<Attribute name="AssetType">Expression</Attribute>
<Relation name="InReplyTo" />
<Attribute name="AuthoredAt">2014-05-28T21:48:37.940</Attribute>
<Attribute name="Content">A new comment</Attribute>
<Attribute name="AssetState">64</Attribute>
<Relation name="Author">
<Asset href="<Server Base URI>/rest-1.v1/Data/Member/2015" idref="Member:2015" />
</Relation>
<Relation name="BelongsTo">
<Asset href="<Server Base URI>/rest-1.v1/Data/Conversation/2018" idref="Conversation:2018" />
</Relation>
<Attribute name="Author.Name">user#example.com</Attribute>
<Attribute name="Author.Nickname">User Name</Attribute>
<Relation name="Mentions">
<Asset href="<Server Base URI>/rest-1.v1/Data/Story/2017" idref="Story:2017" />
</Relation>
</Asset>
I keep getting a 400 Bad Request the following error:
<Error href="<Server Base URI>/rest-1.v1/Data/Expression">
<Message>Violation'Required'AttributeDefinition'Content'Expression</Message>
<Exception class="VersionOne.DataException">
<Message>Violation'Required'AttributeDefinition'Content'Expression</Message>
</Exception>
</Error>
I assume I'm missing something obvious - does anyone know what it is?
IF you examine the metadata for a VersionOne Expression, you will see 3 required fields (Author,AuthoredAt,Content). Logically this makes sense to be able to just create a single, zombie expression but I witnessed otherwise. This might be a mistake in the stylesheet or just my browser because it seems POSTing with only those three will return a 400 error. To get a guaranteed working payload, include the relation "inReplyTo" and that is all that you will need to create an expression within the context of a particular Conversation.
Given that you are responding to an existing expression (comment) This should work fine.
POST to rest-1.v1/Data/Expression
<Asset>
<Relation name="Author" act="set">
<Asset idref="Member:2015" />
</Relation>
<Attribute name="AuthoredAt">2014-05-02T21:48:37.940</Attribute>
<Attribute name="Content" act="set">A new comment</Attribute>
<Relation name="InReplyTo" act="set">
<Asset idref="Expression:xxxxx" />
</Relation>
</Asset>
You don't need Asset state or mentions or belongs to. AssetState is readonly, and BelongsTo is filled in automatically after your Expression is created. It inherits a reference to the containing Conversation from the Expression object entered in the InReplyTo field and the Mentions relation is optional.
FYI,
I believe that you didn't see the Legend on the right hand side of a the meta query output as seen in a browser. Real quick here, when you do a meta query, the items with * are required to Post, Bold items are Read/Write optional, the italicized items are readonly, and the bold items towards the bottom that are appended with ": operation" is the operation that you are allow to do against that particular asset.