sccm Query - Trying to create a query for all devices with a certain folder - sccm

I'm trying to use SCCM to update all devices with zoom to the latest version. It runs locally under the user, so a typical { SMS_G_System_ADD_REMOVE_PROGRAMS.DisplayName like "%Zoom%" } doesn't work. The best workaround we've come up with is to search for the Zoom folder under C:\Users\ %UserProfile%\AppData\Roaming\Zoom. So far we've tried various ways of doing this without any success. Does anyone have any suggestions?
SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_SoftwareFile on SMS_G_System_SoftwareFile.ResourceID = SMS_R_System.ResourceId where SMS_G_System_SoftwareFile.FileName = "Zoom.exe" and SMS_G_System_SoftwareFile.FilePath = "C:\Users\ %UserProfile%\AppData\Roaming\Zoom"
I was expecting a report where all workstations with said folder & file would appear.
It gives the error:
ConfigMgr Error Object:
instance of __ExtendedStatus
{
Operation = "ExecQuery";
ParameterInfo = "SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System inner join SMS_G_System_SoftwareFile on SMS_G_System_SoftwareFile.ResourceID = SMS_R_System.ResourceId where SMS_G_System_SoftwareFile.FileName = \"Zoom.exe\" and SMS_G_System_SoftwareFile.FilePath = \"C:\\Users\\%UserProfile%\\AppData\\Roaming\\Zoom\"";
ProviderName = "WinMgmt";
};
Error Code:
InvalidQuery
-------------------------------
Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlQueryException
The SMS Provider reported an error.
Stack Trace:
at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlQueryResultsObject.<GetEnumerator>d__75.MoveNext()
at Microsoft.ConfigurationManagement.ManagementProvider.QueryProcessorBase.ProcessQuery(Object sender, DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
-------------------------------
System.Management.ManagementException
Invalid query
Stack Trace:
at Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine.WqlQueryResultsObject.<GetEnumerator>d__75.MoveNext()
at Microsoft.ConfigurationManagement.ManagementProvider.QueryProcessorBase.ProcessQuery(Object sender, DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
-------------------------------

What you are looking for is "Configuration Item" and "Configuration Baseline", which are created as a pair (a CI/CB) and produces a resultant membership, which can be marshalled into a collection. I will warn you that the way CM organizes this is a bit byzantine. It will take some testing and tweaking to get the concept understood properly and then set up to your satisfaction.
Googling gave me this page, which has a fair enough description to get you started:
https://www.anoopcnair.com/how-create-sccm-configuration-items-baselines/
My best shoot-from-the-hip braindump:
Create the CI, which defines criteria (such as existence of a folder or file among many other possibilities, including writing your own script to use as the test)
Create the CB, which uses a CI against a Collection to evaluate, which then dumps the results behind the scenes into some internal table
Create the Collection (which can be done with assistance by right-clicking the CB and selecting the right context menu item) which scoops up this data into what you want (a collection of devices) based upon state data. The collection query is difficult to easily see what it's doing, because it uses referenced guids for the CI/CB as well as a state code (for compliant or non-compliant) that isn't really human-readable.
At this point you'll have what you want. But as warned before: the vagaries of setting up the CI/CB and collection are finicky. Expect to do a fair bit of googling and fiddling with the parameters before you get it right.

Related

How to solve common errors in Google Apps Script development

The Q&A is currently a subject of meta discussion, do participate. The current plan is to split where possible into Q&As. Answers to the A&A are community wiki and the question should become one when the status is resolved.
Preface
This Q&A strives to become a collection and a reference target for common errors encountered during development in Google Apps Script language in hopes to improve long-term maintainability of google-apps-script tag.
There are several similar and successful undergoings in other languages and general-purpose tags (see c++, android, php, php again), and this one follows suit.
Why it exists?
The amount of questions from both new and experienced developers regarding the meaning and solutions to errors encountered during development and production that can be effectively reduced to a single answer is substantial. At the time of writing, even running a query only by language tag yields:
"Cannot find method" 8 pages
"Cannot read property" 9 pages
"Cannot call ... in this context" 5 pages
"You do not have permission" 11 pages
Linking to a most relevant duplicate is hard and time-consuming for volunteers due to the need to consider nuances and often poorly-worded titles.
What it consists of?
Entries in this Q&A contain are designed to provide info on how to:
parse the error message structure
understand what the error entails
consistently reproduce (where applicable)
resolve the issue
provide a link to canonical Q&A (where possible)
Table of Contents
To help you navigate the growing reference please use the TOC below:
General errors
Service-specific errors
What this is not?
The scope of the Q&A is limited to common (not trivial). This is not:
a catch-all guide or "best practices" collection
a reference for general ECMAScript errors
GAS documentation
a resources list (we have a tag wiki for that)
What to add?
When adding an entry, please, consider the following:
is the error common enough (see "why" section for examples)?
can the solution be described concisely and be applicable for most cases?
Preface
The answer provides a guide on general errors that can be encountered when working with any Google service (both built-in and advanced) or API. For errors specific to certain services, see the other answer.
Back to reference
General errors
Message
TypeError: Cannot read property 'property name here' from undefined (or null)
Description
The error message indicates that you are trying to access a property on an Object instance, but during runtime the value actually held by a variable is a special data type undefined. Typically, the error occurs when accessing nested properties of an object.
A variation of this error with a numeric value in place of property name indicates that an instance of Array was expected. As arrays in JavaScript are objects, everything mentioned here is true about them as well.
There is a special case of dynamically constructed objects such as event objects that are only available in specific contexts like making an HTTP request to the app or invoking a function via time or event-based trigger.
The error is a TypeError because an "object" is expected, but "undefined" is received
How to fix
Using default values
Logical OR || operator in JavaScript has an intersting property of evaluating the right-hand side iff the left-hand is falsy. Since objects in JS are truthy, and undefined and null are falsy, an expression like (myVar || {}).myProp [(myVar || [])[index] for arrays] will guarantee that no error is thrown and the property is at least undefined.
One can also provide default values: (myVar || { myProp : 2 }) guarantees accessing myProp to return 2 by default. Same goes for arrays: (myVar || [1,2,3]).
Checking for type
Especially true for the special case, typeof operator combined with an if statement and a comparison operator will either allow a function to run outside of its designated context (i.e. for debugging purposes) or introduce branching logic depending on whether the object is present or not.
One can control how strict the check should be:
lax ("not undefined"): if(typeof myVar !== "undefined") { //do something; }
strict ("proper objects only"): if(typeof myVar === "object" && myVar) { //do stuff }
Related Q&As
Parsing order of the GAS project as the source of the issue
Message
Cannot convert some value to data type
Description
The error is thrown due to passing an argument of different type than a method expects. A common mistake that causes the error is accidental coercion of a number to string.
How to reproduce
function testConversionError() {
const ss = SpreadsheetApp.getActiveSheet();
ss.getRange("42.0",1);
}
How to fix
Make sure that the value referenced in the error message is of data type required by documentation and convert as needed.
Message
Cannot call Service and method name from this context
Description
This error happens on a context mismatch and is specific to container-bound scripts.
The primary use case that results in the error is trying to call a method only available in one document type (usually, getUi() as it is shared by several services) from another (i.e. DocumentApp.getUi() from a spreadsheet).
A secondary, but also prominent case is a result of calling a service not explicitly allowed to be called from a custom function (usually a function marked by special JSDoc-style comment #customfunction and used as a formula).
How to reproduce
For bound script context mismatch, declare and run this function in a script project tied to Google Sheets (or anything other than Google Docs):
function testContextMismatch() {
const doc = DocumentApp.getUi();
}
Note that calling a DocumentApp.getActiveDocument() will simply result in null on mismatch, and the execution will succeed.
For custom functions, use the function declared below in any cell as a formula:
/**
* #customfunction
*/
function testConversionError() {
const ui = SpreadsheetApp.getUi();
ui.alert(`UI is out of scope of custom function`);
}
How to fix
Context mismatch is easily fixed by changing the service on which the method is called.
Custom functions cannot be made to call these services, use custom menus or dialogs.
Message
Cannot find method Method name here
The parameters param names do not match the method signature for method name
Description
This error has a notoriously confusing message for newcomers. What it says is that a type mismatch occurred in one or more of the arguments passed when the method in question was called.
There is no method with the signature that corresponds to how you called it, hence "not found"
How to fix
The only fix here is to read the documentation carefully and check if order and inferred type of parameters are correct (using a good IDE with autocomplete will help). Sometimes, though, the issue happens because one expects the value to be of a certain type while at runtime it is of another. There are several tips for preventing such issues:
Setting up type guards (typeof myVar === "string" and similar).
Adding a validator to fix the type dynamically thanks to JavaScript being dynamically typed.
Sample
/**
* #summary pure arg validator boilerplate
* #param {function (any) : any}
* #param {...any} args
* #returns {any[]}
*/
const validate = (guard, ...args) => args.map(guard);
const functionWithValidator = (...args) => {
const guard = (arg) => typeof arg !== "number" ? parseInt(arg) : arg;
const [a,b,c] = validate(guard, ...args);
const asObject = { a, b, c };
console.log(asObject);
return asObject;
};
//driver IIFE
(() => {
functionWithValidator("1 apple",2,"0x5");
})()
Messages
You do not have permission to perform that action
The script does not have permission to perform that action
Description
The error indicates that one of the APIs or services accessed lacks sufficient permissions from the user. Every service method that has an authorization section in its documentation requires at least one of the scopes to be authorized.
As GAS essentially wraps around Google APIs for development convenience, most of the scopes listed in OAuth 2.0 scopes for APIs reference can be used, although if one is listed in the corresponding docs it may be better to use it as there are some inconsistencies.
Note that custom functions run without authorization. Calling a function from a Google sheet cell is the most common cause of this error.
How to fix
If a function calling the service is ran from the script editor, you are automatically prompted to authorize it with relevant scopes. Albeit useful for quick manual tests, it is best practice to set scopes explicitly in application manifest (appscript.json). Besides, automatic scopes are usually too broad to pass the review if one intends to publish the app.
The field oauthScopes in manifest file (View -> Show manifest file if in code editor) should look something like this:
"oauthScopes": [
"https://www.googleapis.com/auth/script.container.ui",
"https://www.googleapis.com/auth/userinfo.email",
//etc
]
For custom functions, you can fix it by switching to calling the function from a menu or a button as custom functions cannot be authorized.
For those developing editor Add-ons, this error means an unhandled authorization lifecycle mode: one has to abort before calls to services that require authorization in case auth mode is AuthMode.NONE.
Related causes and solutions
#OnlyCurrentDoc limiting script access scope
Scopes autodetection
Message
ReferenceError: service name is not defined
Description
The most common cause is using an advanced service without enabling it. When such a service is enabled, a variable under the specified identifier is attached to global scope that the developer can reference directly. Thus, when a disabled service is referenced, a ReferenceError is thrown.
How to fix
Go to "Resources -> Advanced Google Services" menu and enable the service referenced. Note that the identifier should equal the global variable referenced.
For a more detailed explanation, read the official guide.
If one hasn't referenced any advanced services then the error points to an undeclared variable being referenced.
Message
The script completed but did not return anything.
Script function not found: doGet or doPost
Description
This is not an error per se (as the HTTP response code returned is 200 and the execution is marked as successful, but is commonly regarded as one. The message appears when trying to make a request/access from browser a script deployed as a Web App.
There are two primary reasons why this would happen:
There is no doGet or doPost trigger function
Triggers above do not return an HtmlOutput or TextOutput instance
How to fix
For the first reason, simply provide a doGet or doPost trigger (or both) function. For the second, make sure that all routes of your app end with creation of TextOutput or HtmlOutput:
//doGet returning HTML
function doGet(e) {
return HtmlService.createHtmlOutput("<p>Some text</p>");
}
//doPost returning text
function doPost(e) {
const { parameters } = e;
const echoed = JSON.stringify(parameters);
return ContentService.createTextOutput(echoed);
}
Note that there should be only one trigger function declared - treat them as entry points to your application.
If the trigger relies on parameter / parameters to route responses, make sure that the request URL is structured as "baseURL/exec?query" or "baseURL/dev?query" where query contains parameters to pass.
Related Q&As
Redeploying after declaring triggers
Message
We're sorry, a server error occurred. Please wait a bit and try again.
Description
This one is the most cryptic error and can occur at any point with nearly any service (although DriveApp usage is particularly susceptible to it). The error usually indicates a problem on Google's side that either goes away in a couple of hours/days or gets fixed in the process.
How to fix
There is no silver bullet for that one and usually, there is nothing you can do apart from filing an issue on the issue tracker or contacting support if you have a GSuite account. Before doing that one can try the following common remedies:
For bound scripts - creating a new document and copying over the existing project and data.
Switch to using an advanced Drive service (always remember to enable it first).
There might be a problem with a regular expression if the error points to a line with one.
Don't bash your head against this error - try locating affected code, file or star an issue and move on
Syntax error without apparent issues
This error is likely to be caused by using an ES6 syntax (for example, arrow functions) while using the deprecated Rhino runtime (at the time of writing the GAS platform uses V8).
How to fix
Open "appscript.json" manifest file and check if runtimeVersion is set to "V8", change it if not, or remove any ES6 features otherwise.
Quota-related errors
There are several errors related to quotas imposed on service usage. Google has a comprehensive list of those, but as a general rule of thumb, if a message matches "too many" pattern, you are likely to have exceeded the respective quota.
Most likely errors encountered:
Service invoked too many times: service name
There are too many scripts running
Service using too much computer time for one day
This script has too many triggers
How to fix
In most cases, the only fix is to wait until the quota is refreshed or switch to another account (unless the script is deployed as a Web App with permission to "run as me", in which case owner's quotas will be shared across all users).
To quote documentation at the time:
Daily quotas are refreshed at the end of a 24-hour window; the exact time of this refresh, however, varies between users.
Note that some services such as MailApp have methods like getRemainingDailyQuota that can check the remaining quota.
In the case of exceeding the maximum number of triggers one can check how many are installed via getProjectTriggers() (or check "My triggers" tab) and act accordingly to reduce the number (for example, by using deleteTrigger(trigger) to get rid of some).
Related canonical Q&As
How are daily limitations being applied and refreshed?
"Maximum execution time exceeded" problem
Optimizing service calls to reduce execution time
References
How to make error messages more meaningful
Debugging custom functions
Service-specific errors
The answer concerns built-in service-related errors. For general reference see the other answer. Entries addressing issues with services listed in official reference are welcome.
Back to reference
SpreadsheetApp
The number of rows in the range must be at least 1
This error is usually caused by calling the getRange method where the parameter that sets the number of rows happens to equal to 0. Be careful if you depend on getLastRow() call return value - only use it on non-empty sheets (getDataRange will be safer).
How to reproduce
sh.getRange(1, 1, 0, sh.getLastColumn()); //third param is the number of rows
How to fix
Adding a guard that prevents the value from ever becoming 0 should suffice. The pattern below defaults to the last row with data (optional if you only need a certain number of rows) and to 1 if that also fails:
//willFail is defined elsewhere
sh.getRange(1, 1, willFail || sh.getLastRow() || 1, sh.getLastColumn());
Error: “Reference does not exist”
The error happens when calling a custom function in a spreadsheet cell that does not return a value. The docs do mention only that one "must return a value to display", but the catch here is that an empty array is also not a valid return value (no elements to display).
How to reproduce
Call the custom function below in any Google Sheets spreadsheet cell:
/**
* #customfunction
*/
const testReferenceError = () => [];
How to fix
No specific handling is required, just make sure that length > 0.
The number of rows or cells in the data does not match the number of rows or cells in the range. The data has N but the range has M.
Description
The error points to a mismatch in dimensions of range in relation to values. Usually, the issue arises when using setValues() method when the matrix of values is smaller or bigger than the range.
How to reproduce
function testOutOfRange() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sh = ss.getActiveSheet();
const rng = sh.getActiveRange();
const vals = rng.getValues();
try {
vals.push([]);
rng.setValues(vals);
} catch (error) {
const ui = SpreadsheetApp.getUi();
ui.alert(error.message);
}
}
How to fix
If it is routinely expected for values to get out of bounds, implement a guard that catches such states, for example:
const checkBounds = (rng, values) => {
const targetRows = rng.getHeight();
const targetCols = rng.getWidth();
const { length } = values;
const [firstRow] = values;
return length === targetRows &&
firstRow.length === targetCols;
};
The coordinates of the range are outside the dimensions of the sheet.
Description
The error is a result of a collision between two issues:
The Range is out of bounds (getRange() does not throw on requesting a non-existent range)
Trying to call a method on a Range instance referring to a non-existent dimension of the sheet.
How to reproduce
function testOB() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sh = ss.getActiveSheet();
const rng = sh.getRange(sh.getMaxRows() + 1, 1);
rng.insertCheckboxes();
}
How to fix
Check that number of rows (getMaxRow()) and columns (getMaxColumns()) are both greater or equal to the parameters passed to getRange() method call and change them accordingly.
Exception: You can't create a filter in a sheet that already has a filter.
Description
The message means that you are trying to call a createFilter method on a Range in a Sheet that already has a filter set (either via UI or script), thus violating the restriction on 1 filter per Sheet, to quote the documentation:
There can be at most one filter in a sheet.
How to reproduce
const testFilterExistsError = () => {
const sh = SpreadsheetApp.getActiveSheet();
const rng = sh.getDataRange();
const filter1 = rng.createFilter();
const filter2 = rng.createFilter();
};
How to fix
Add a guard that checks for the existence of the filter first. getFilter returns either a filter or null if called on a Range instance and is perfect for the job:
const testFilterGuard = () => {
const sh = SpreadsheetApp.getActiveSheet();
const rng = sh.getDataRange();
const filter = rng.getFilter() || rng.createFilter();
//do something useful;
};
UrlFetchApp
Attribute provided with no value: url
Description
The error is specific to UrlFetchApp service and happens when fetch or fetchAll method gets called with an empty string or non-string value.
How to reproduce
const response = UrlFetchApp.fetch("", {});
How to fix
Make sure that a string containing a URI (not necessarily valid) is passed to the method as its first argument. As its common root cause is accessing a non-existent property on an object or array, check whether your accessors return an actual value.

Xpath Part NULL, with xpaths set via content control toolkit

I've been able to set, via code, the xpaths for the placeholders found in the document.
for (Object o : finderSdtRun.results) {
if (o instanceof SdtRun){
SdtPr sdtPr=((SdtRun) o).getSdtPr();
Tag t = sdtPr.getTag();
CTDataBinding ctDataBinding = Context.getWmlObjectFactory().createCTDataBinding();
//JAXBElement jaxbDB = Context.getWmlObjectFactory().createSdtPrDataBinding(ctDataBinding);
sdtPr.setDataBinding(ctDataBinding);
ctDataBinding.setXpath("tuttappostaferragost");
ctDataBinding.setStoreItemID("something");
ObjectFactory factory = new org.opendope.xpaths.ObjectFactory();
DataBinding db = factory.createXpathsXpathDataBinding();
db.setXpath("tuttappostaferragost");
db.setStoreItemID("something");
Xpaths.Xpath xp = factory.createXpathsXpath();
xp.setDataBinding(db);
xp.setId("something");
try {
wordMLPackage.getMainDocumentPart().getXPathsPart().getContents().getXpath().add(xp);
} catch (Docx4JException e) {
e.printStackTrace();
}
;
The problem is that, once set, they are not recognized by word, so I thought to add the created Xpaths to a new XpathPart, and then add it to the main Document part.
But I failed because the method:
wordMLPackage.getMainDocumentPart().getXPathsPart()
returns null. This sounded reasonable, since only content control was set, without any Xpath.
Then I set the Xpaths via content control toolkit and the same line of code like above, returned me null, which added a lot of confusion in my yet confused ideas.
Is there any way to tell the document that new Xpath have been added to the document?
I mean, if there is a way to add Xpath via code (the w:databinding w:storedItemId tags), why it is not possible to make it work?
In general I want to add Xpath and all information necessary, via code, avoiding the use of any toolkit.
Thank you :D
First, you have to decide whether you want plain old Word databinding, or the additional OpenDoPE capabilities (which use the content control tag to support repeats, conditionals etc).
You only need an XPaths part if you are using the OpenDoPE extensions.
I'll assume for now that you are just looking to do basic Word content control databinding.
To set that up programmatically, you need to add a custom xml part, and a rel from it to its itemProps.xml part, which contains something like:
<ds:datastoreItem ds:itemID="{5448916C-134B-45E6-B8FE-88CC1FFC17C3}" xmlns:ds="http://schemas.openxmlformats.org/officeDocument/2006/customXml">
<ds:schemaRefs/>
</ds:datastoreItem>
(to add a part B to part A, use partA.addTargetPart)
You can see it is this part with gives the custom xml part its itemID; this corresponds with the value you set in:
DataBinding db = factory.createXpathsXpathDataBinding();
db.setStoreItemID("something");
Then, set the XPath via the method you were using.

Using "whose" on arrays in Javascript for Automation

Playing with the new JS for automation using Script Editor. I'm getting an error on the final line of the following:
var iTunes = Application("iTunes");
var sources = iTunes.sources();
var library = sources.whose({name : "Library"});
Confirmed that the sources array is as expected (two elements, one with name "Library" and one "Internet Radio"). But that final line chokes with Error on line 3: TypeError: undefined is not a function (evaluating 'sources.whose({name : "Library"})').
As far as I can tell, I'm using the right syntax for the whose function. (I also tried with an explicit _equals clause to the same result.) What am I doing wrong?
What am I doing wrong?
Short answer: it's not your fault. The JXA documentation is a sack of lies.
Longer explanation: an object's elements have nothing to do with Arrays. They represent a one-to-many relationship in an object graph, in this case, between a source object and zero or more library objects.
While many relationships may reflect the underlying implementation's containment hierarchy, there is no obligation to do so; e.g. Finder allows you to identify objects on the desktop in multiple ways:
items of folder "Desktop" of folder "jsmith" of folder "Users" of disk "Macintosh HD" of app "Finder"
items of folder "Desktop" of folder "jsmith" of folder "Users" of startup disk of app "Finder"
items of folder "Desktop" of home of app "Finder"
items of folder "Macintosh HD:Users:jsmith:Desktop" of app "Finder"
items of desktop of app "Finder"
items of app "Finder"
[etc.]
Apple event-based application scripting is based on remote procedure calls plus simple first-class queries. It's not OOP, regardless of superficial appearance: that's just syntactic sugar to make its queries easy to read and write.
...
In this case, your second line is telling iTunes to get a list (Array) of query objects (ObjectSpecifiers) that identify each of the source objects in your iTunes application:
var iTunes = Application("iTunes");
var sources = iTunes.sources();
Once you've got an Array, you can't use it to construct further queries, because JavaScript doesn't know how to build queries itself. What you actually want is this:
var iTunes = Application("iTunes");
var sourcesSpecifier = iTunes.sources;
var librarySpecifier = sourcesSpecifier.whose({name : "Library"});
That will give you an object specifier that identifies all of the source objects whose name is "Library". (If you only want to specify the first source object named "Library", use the byName method instead of whose; it's simpler.)
--
Personally, I consider all this somewhat academic as JXA's Apple event bridge implementation, like its documentation, is mostly made of Lame and Fail anyway. It mostly works up to a point, then poops on you beyond that. If your needs are modest and it's "good enough" to do then more power to you, but for anything non-trivial stick with AppleScript: it's the only supported solution that works right.
(The AppleScript/JXA team has no excuse for such crap work either: I sent them an almost-finished JavaScriptOSA reference implementation months ago to study or steal from as they wished, which they totally ignored. So you'll excuse my pissiness, as this was a solved problem long ago.)
This now works as theory would predict.
(function () {
'use strict';
var iTunes = Application('iTunes'),
filtered = iTunes.sources.whose({
name: 'Library'
});
return filtered().length;
})();
Based on the JavaScript for Automation Release Notes Mail.inbox.messages.whose(...) example, the following should work:
var iTunes = Application('iTunes');
var filtered = iTunes.sources.whose({name : 'Library'});
The apparent goal for the "special whose method" with "an object containing the query" is to be efficient by only bringing select items (or item references) from the OS X object hierarchy into the resulting JavaScript array.
However, ... the whose feature of JXA appeared to have some bugs in the earlier OS X v10.10 release.
So, since the array in question is small (i.e. 2 items), filtering can be done fast & reliably on the JavaScript side after getting the elements as a JS array.
Workaround Example 1
var iTunes = Application('iTunes');
var sources = iTunes.sources();
var librarySource = null;
for (key in sources) {
var name = sources[key].name();
if (name.localeCompare("Library") == 0) {
librarySource = sources[key];
}
}
Workaround Example 2
var iTunes = Application('iTunes');
var sources = iTunes.sources();
function hasLibraryName(obj) {
var name = obj.name();
if (name.localeCompare("Library") == 0) {
return true;
}
return false;
}
var filtered = sources.filter(hasLibraryName);
In OS X 10.11.5 this seems to be working just fine.
library = Application("iTunes").sources.whose({name:'Library'})()[0]
library.properties()
// {"class":"source", "id":64, "index":1, "name":"Library", "persistentID":"2D8F973150E0A3AD", "kind":"library", "capacity":0, "freeSpace":0}
Note the addition of () after the whose clause to resolve the object specifier into an array of references and then the [0] to get the first (and only, in my case) library object reference, which can then be used to get the properties of that library.
In case the source is not named "Library" in other languages or regions, I would probably use this instead:
library = Application("iTunes").sources.whose({kind:"kLib"})()[0]

NUnit- Custom Property Attribute display in Test Explorer window

I created custom property attribute to link every system test to its driving requirements which is similar to something described in the link below:
NUnit - Multiple properties of the same name? Linking to requirements
I used the code given in the above link
[Requirements(new string[] { "FR50082", "FR50084" })]
[Test]
public void TestSomething(string a, string b) { // blah, blah, blah
Assert.AreNotEqual(a, b); }
which gets displayed in Test explorer (filter by traits) as :-
Requirements[System.String[]] (1)
TestSomething.....
But this is not what I was expecting. I require every requirement to get displayed individually though they are associated to the same test case in test explorer window.
I want to get it displayed as (in test explorer):-
Requirements[FR50082] (1)
TestSomething.....
Requirements[FR50084] (1)
TestSomething.....
and so on....
So, if I am associating n number of Requirements to a test case, the test explorer should display the same test case n times under different requirements. Please let me know how could this be achieved ??
It sounds like you are heading down the BDD (Behavior Driven Design) route. SpecFlow is a good choice in .Net if you don't mind a VS extension.
The big win for you I think would be that you can reuse step definitions, what you're calling TestSomething. You can set up different contexts, your Requirements, as I'm reading them, and in the Then step call your TestSomething to verify all is well.

Coded UI error: The following element is not longer availabe

I recorded some test cases with CUIT in VS2010. Everything worked fine the day before. So, today I run again, all the test failed, with the warning: The following element is no longer available ... and I got the exception : Can't perform "Click" on the hidden control, which is not true because all the controls are not hidden. I tried on the other machine, and they failed as well.
Does anyone know why it happens? Is it because of the web application for something else? Please help, thanks.
PS: So I tried to record a new test with the same controls that said "hidden controls", and the new test worked!? I don't understand why.
EDIT
The warning "The following element blah blah ..." appears when I tried to capture an element or a control while recording. The source code of the button is said 'hidden'
public HtmlImage UIAbmeldenImage
{
get
{
if ((this.mUIAbmeldenImage == null))
{
this.mUIAbmeldenImage = new HtmlImage(this);
#region Search Criteria
this.mUIAbmeldenImage.SearchProperties[HtmlImage.PropertyNames.Id] = null;
this.mUIAbmeldenImage.SearchProperties[HtmlImage.PropertyNames.Name] = null;
this.mUIAbmeldenImage.SearchProperties[HtmlImage.PropertyNames.Alt] = "abmelden";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.AbsolutePath] = "/webakte-vnext/content/apps/Ordner/images/logOut.png";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.Src] = "http://localhost/webakte-vnext/content/apps/Ordner/images/logOut.png";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.LinkAbsolutePath] = "/webakte-vnext/e.consult.9999/webakte/logout/index";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.Href] = "http://localhost/webakte-vnext/e.consult.9999/webakte/logout/index";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.Class] = null;
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.ControlDefinition] = "alt=\"abmelden\" src=\"http://localhost/web";
this.mUIAbmeldenImage.FilterProperties[HtmlImage.PropertyNames.TagInstance] = "1";
this.mUIAbmeldenImage.WindowTitles.Add("Akte - Test Akte Coded UI VS2010");
#endregion
}
return this.mUIAbmeldenImage;
}
}
Although I am running Visual Studio 2012, I find it odd that we started experiencing the same problem on the same day, I can not see any difference in the DOM for the Coded UI Tests I have for my web page, but for some reason VS is saying the control is hidden and specifies the correct ID of the element it is looking for (I verified that the ID is still the same one). I even tried to re-record the action, because I assumed that something must have changed, but I get the same error.
Since this sounds like the same problem, occurring at the same time I am thinking this might be related to some automatic update? That's my best guess at the moment, I am going to look into it, I will update my post if I figure anything out.
EDIT
I removed update KB2870699, which removes some voulnerability in IE, this fixed the problems I was having with my tests. This update was added on the 12. september, so it fits. Hope this helps you. :)
https://connect.microsoft.com/VisualStudio/feedback/details/800953/security-update-kb2870699-for-ie-breaks-existing-coded-ui-tests#tabs
Official link to get around the problem :
http://blogs.msdn.com/b/visualstudioalm/archive/2013/09/17/coded-ui-mtm-issues-on-internet-explorer-with-kb2870699.aspx
The problem is more serious than that! In my case I can't even record new Coded UI Tests. After I click in any Hyper Link of any web page of my application the coded UI test builder cannot record that click "The following element is no longer available....".
Apparently removing the updates, as said by AdrianHHH do the trick!
Shut down VS2010, launch it again "Run as administrator".
There may be a field in the SearchProperties (or possible the FilterProperties) that has a value set by the web site, or that represents some kind of window ID on your desktop. Another possibility is that the web page title changes from day to day or visit to visit. Different executions of the browser or different visits to the web page(s) create different values. Removing these values from the SearchProperties (or FilterProperties) or changing the check for the title from an equals to a contains for a constant part of the title should fix the problem. Coded UI often searches for more values than the minimum set needed.
Compare the search properties etc for the same control in the two recorded tests.
Update based extra detail given in the comments:
I solved a similar problem as follows. I copied property code similar to that shown in your question into a method that called FindMatchingControls. I checked how many controls were returned, in my case up to 3. I examined various properties of the controls found, by writing lots of text to a debug file. In my case I found that the Left and Top properties were negative for the unwanted, ie hidden, controls.
For your code rather than just using the UIAbmeldenImage property, you might call the method below. Change an expression such as
HtmlImage im = UIMap.abc.def.UIAbmeldenImage;
to be
HtmlImage im = FindHtmlHyperLink(UIMap.abc.def);
Where the method is:
public HtmlImage FindHtmlHyperLink(HtmlDocument doc)
{
HtmlImage myImage = new HtmlImage(doc);
myImage.SearchProperties[HtmlImage.PropertyNames.Id] = null;
myImage.SearchProperties[HtmlImage.PropertyNames.Name] = null;
myImage.SearchProperties[HtmlImage.PropertyNames.Alt] = "abmelden";
myImage.FilterProperties[HtmlImage.PropertyNames.AbsolutePath] = "/webakte-vnext/content/apps/Ordner/images/logOut.png";
myImage.FilterProperties[HtmlImage.PropertyNames.Src] = "http://localhost/webakte-vnext/content/apps/Ordner/images/logOut.png";
myImage.FilterProperties[HtmlImage.PropertyNames.LinkAbsolutePath] = "/webakte-vnext/e.consult.9999/webakte/logout/index";
myImage.FilterProperties[HtmlImage.PropertyNames.Href] = "http://localhost/webakte-vnext/e.consult.9999/webakte/logout/index";
myImage.FilterProperties[HtmlImage.PropertyNames.Class] = null;
myImage.FilterProperties[HtmlImage.PropertyNames.ControlDefinition] = "alt=\"abmelden\" src=\"http://localhost/web";
myImage.FilterProperties[HtmlImage.PropertyNames.TagInstance] = "1";
myImage.WindowTitles.Add("Akte - Test Akte Coded UI VS2010");
UITestControlCollection controls = myImage.FindMatchingControls();
if (controls.Count > 1)
{
foreach (UITestControl con in controls)
{
if ( con.Left < 0 || con.Top < 0 )
{
// Not on display, ignore it.
}
else
{
// Select this one and break out of the loop.
myImage = con as HtmlImage;
break;
}
}
}
return myImage;
}
Note that the above code has not been compiled or tested, it should be taken as ideas not as the final code.
I had the same problem on VS 2012. As a workaround, you can remove that step, and re-record it again. That usually works.
One of the biggest problem while analyzing the Coded UI test failures is that the error stack trace indicates the line of code which might be completely unrelated to the actual cause of failure.
I would suggest you to enable HTML logging in your tests - this will display step by step details of how Coded UI tried to execute the tests - with screenshots of your application. It will also highlight the control in red which Coded UI is trying to search/operate upon.This is very beneficial in troubleshooting the actual cause of test failures.
To enable tracing you can just add the below code to your app.config file --

Resources