TestCases collections is not retrieved correctly through SDK but only with Web Service api - rally

SDK retrieval of TestCases collection from the TestSet object is not working correctly IMO as TestCase collection is not a full array of objects and TestCases collection has very scarce information.
Web service API returns them correctly and so far only 2.0p5 returns them correctly and neither of 2.0rc rc2 and rc3 returns them as expected
Am I doing something wrong?
I just need to get TestCases collection with all fully qualified objects for each test case when I retrieve a TestSet object.

AppSDK rc2 works with v2.0 of WS API. v2.0 removed the ability to return child collections in the same response for performance reasons. Per WS API documentation fetching a collection will return an object with the count and the url from which to get the collection data. To get full objects a separate request is needed. In app example in this github repo when a testset is selected from a combobox, and testset loaded, TestCases collection is hydreated:
_onDataLoaded: function(store, records){
if ((records.length === 0) && (this._grid)) {
this._grid.destroy();
}
var that = this;
var promises = [];
_.each(records, function(tcr) {
promises.push(that._getTestCase(tcr, that));
});
Deft.Promise.all(promises).then({
success: function(results) {
that._testcaseresults = results;
that._createGrid(records);
}
});
},
_getTestCase: function(tcr, scope) {
var deferred = Ext.create('Deft.Deferred');
var that = scope;
var testcaseOid = tcr.get('TestCase').ObjectID;
Rally.data.ModelFactory.getModel({
type: 'Test Case',
scope: this,
success: function(model, operation) {
fetch: ['FormattedID','Name','Method'],
model.load(testcaseOid, {
scope: this,
success: function(record, operation) {
var testName = record.get('Name');
var testFid = record.get('FormattedID');
var testMethod = record.get('Method');
var tcrRef = tcr.get('_ref');
var tcrOid = tcr.get('ObjectID');
var tcrVerdict = tcr.get('Verdict');
var tcrBuild = tcr.get('Build');
result = {
"_ref" : tcrRef,
"ObjectID" : tcrOid,
"Verdict" : tcrVerdict,
"Build" : tcrBuild,
"TestCaseName" : testName,
"TestCase" : testFid,
"Method" : testMethod
};
deferred.resolve(result);
}
});
}
});
return deferred;
}

Related

using promises with getCollection

I'm trying to figure out how to apply the promises infrastructure in the case where I'm looping through a list of portfolio items to extract data for highcharts use and need to retrieve data from the related user stories. The goal is to create a way to not attempt to instantiate the chart object until all async callbacks are completed. Here's a code snippet illustrating what I'm trying to do - in this example, the getCollection() method's callback function is not being executed until all of the outer loop features have been retrieved.
_.each(records, function(feature) {
var rname = (feature.get('Release')) ? feature.get('Release')._refObjectName: "None";
//various other feature record extraction steps
feature.getCollection('UserStories').load({
fetch: ['FormattedID', 'Name', 'InProgressDate','AcceptedDate'],
callback: function(stories, operation, success){
Ext.Array.each(stories, function(story) {
var storyname = story.get('FormattedID') + ': ' + story.get('Name');
// other chart data extraction steps
}
});
}
});
});
I'd check out the guide in the docs on working with promises, especially the section on retrieving hierarchical data:
https://help.rallydev.com/apps/2.0/doc/#!/guide/promises-section-retrieving-hierarchical-data
The basic idea is to keep an array of all the promises representing the child collection store loads and then to use a Deft.Promise.all to wait for them all to finish before continuing.
So something like this, based on your code above:
var childStoryPromises = [];
_.each(records, function(feature) {
var rname = (feature.get('Release')) ? feature.get('Release')._refObjectName: "None";
// various other feature record extraction steps
var userStoriesStore = feature.getCollection('UserStories');
var promise = userStoriesStore.load({
fetch: ['FormattedID', 'Name', 'InProgressDate','AcceptedDate']
});
childStoryPromises.push(promise);
feature.userStoriesStore = userStoriesStore; //save reference for later
});
//wait for all stores to load
Deft.Promise.all(childStoryPromises).then({
success: function() {
_.each(records, function(feature) {
var userStories = feature.userStoriesStore.getRange();
//extract user story data here
});
},
scope: this
});

Angular-translate: Set custom loader option from controller

Today, I have an config for the translateProvider looking like this:
App.config(['$translateProvider', function ($translateProvider) {
$translateProvider.preferredLanguage('en-US');
$translateProvider.useLoader('TranslationLoader', { versionIdentifier : 127} );
$translateProvider.useMissingTranslationHandler('MissingTranslationHandler');
}]);
The problem is that I don't know the value of the formIdentifier-option at configuration time. I get this value after resolving the first state in ui-route. I've tried to set the translationProvides loader in the state's controller, but realized that that's not possible :)
Any ideas?
angular-translate allows you to use any service as a loader as long as it meets a desired interface. But it doesn't restrict you in ways of how you pass additional parameters to the loader. So, you may pass them just like you want.
For example, you can set additional parameters directly to the loader. Just implement setters for them on top of your loader:
module.factory('Loader', [
'$q',
function($q) {
var myParam;
var loader = function(options) {
var allParams = angular.extend({}, { myParam: myParam }, options);
var deferred = $q.defer();
// load stuff
return deferred.promise;
};
loader.setMyParam = function(param) {
myParam = param;
};
return loader;
}])
Also, you may try to set these parameters with some helper service (either sync or async:
module.factory('SyncLoader', [
'$q', '$injector',
function($q, $injector) {
var loader = function(options) {
var helper = $injector.get(options.helper);
var myParam = helper.getMyParam();
var deferred = $q.defer();
// load stuff
return deferred.promise;
};
return loader;
}]);
or
module.factory('AsyncLoader', [
'$q', '$injector',
function($q, $injector) {
var loader = function(options) {
var helper = $injector.get(options.helper);
var deferred = $q.defer();
helper.getMyParam()
.then(function success(myParam) {
// load stuff
}, function error() {
// fail, probably
});
return deferred.promise;
};
return loader;
}]);
Also, it might be possible to use events somehow. Or, maybe, there are some other ways possible. It depends on a specific architecture.

How we get and post api in Titanium alloy?

How can we get and post api in Titanium alloy?
I am having the api of userDetails, I just want that how can i code to get the data from api.
function getUserDetails(){
}
Thanks in advance.
As you mentioned, you are using Titanium alloy.
So another approach be to extend the Alloy's Model and Collection ( which are based on backbone.js concept ).
There are already some implementation at RestAPI Sync Adapter also proper description/usage at Titanium RestApi sync.
I also provide the description and methodology used, in-case link gets broken:
Create a Model : Alloy Models are extensions of Backbone.js Models, so when you're defining specific information about your data, you do it by implementing certain methods common to all Backbone Models, therefor overriding the parent methods. Here we will override the url() method of backbone to allow our custom url endpoint.
Path :/app/models/node.js
exports.definition = {
config: {
adapter: {
type: "rest",
collection_name: "node"
}
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
url: function() {
return "http://www.example.com/ws/node";
},
});
return Collection;
}
};
Configure a REST sync adapter : The main purpose of a sync adapter is to override Backbone's default sync method with something that fetches your data. In our example, we'll run through a few integrity checks before calling a function to fetch our data using a Ti.Network.createHTTPClient() call. This will create an object that we can attach headers and handlers to and eventually open and send an xml http request to our server so we can then fetch the data and apply it to our collection.
Path :/app/assets/alloy/sync/rest.js (you may have to create alloy/sync folders first)
// Override the Backbone.sync method with our own sync
functionmodule.exports.sync = function (method, model, opts)
{
var methodMap = {
'create': 'POST',
'read': 'GET',
'update': 'PUT',
'delete': 'DELETE'
};
var type = methodMap[method];
var params = _.extend(
{}, opts);
params.type = type;
//set default headers
params.headers = params.headers || {};
// We need to ensure that we have a base url.
if (!params.url)
{
params.url = model.url();
if (!params.url)
{
Ti.API.error("[REST API] ERROR: NO BASE URL");
return;
}
}
//json data transfers
params.headers['Content-Type'] = 'application/json';
switch (method)
{
case 'delete':
case 'create':
case 'update':
throw "Not Implemented";
break;
case 'read':
fetchData(params, function (_response)
{
if (_response.success)
{
var data = JSON.parse(_response.responseText);
params.success(data, _response.responseText);
}
else
{
params.error(JSON.parse(_response.responseText), _response.responseText);
Ti.API.error('[REST API] ERROR: ' + _response.responseText);
}
});
break;
}
};
function fetchData(_options, _callback)
{
var xhr = Ti.Network.createHTTPClient(
{
timeout: 5000
});
//Prepare the request
xhr.open(_options.type, _options.url);
xhr.onload = function (e)
{
_callback(
{
success: true,
responseText: this.responseText || null,
responseData: this.responseData || null
});
};
//Handle error
xhr.onerror = function (e)
{
_callback(
{
'success': false,
'responseText': e.error
});
Ti.API.error('[REST API] fetchData ERROR: ' + xhr.responseText);
};
for (var header in _options.headers)
{
xhr.setRequestHeader(header, _options.headers[header]);
}
if (_options.beforeSend)
{
_options.beforeSend(xhr);
}
xhr.send(_options.data || null);
}
//we need underscore
var _ = require("alloy/underscore")._;
Setup your View for Model-view binding : Titanium has a feature called Model-View binding, which allows you to create repeatable objects in part of a view for each model in a collection. In our example we'll use a TableView element with the dataCollection property set to node, which is the name of our model, and we'll create a TableViewRow element inside. The row based element will magically repeat for every item in the collection.
Path :/app/views/index.xml
<Alloy>
<Collection src="node">
<Window class="container">
<TableView id="nodeTable" dataCollection="node">
<TableViewRow title="{title}" color="black" />
</TableView>
</Window>
</Alloy>
Finally Controller : Binding the Model to the View requires almost no code at the controller level, the only thing we have to do here is load our collection and initiate a fetch command and the data will be ready to be bound to the view.
Path :/app/controllers/index.js
$.index.open();
var node = Alloy.Collections.node;
node.fetch();
Further reading :
Alloy Models
Sync Adapters
Hope it is helpful.
this is the solution for your problem:-
var request = Titanium.Network.createHTTPClient();
var done=false;
request.onload = function() {
try {
if (this.readyState == 4 && !done) {
done=true;
if(this.status===200){
var content = JSON.parse(this.responseText);
}else{
alert('error code' + this.status);
}
}
} catch (err) {
Titanium.API.error(err);
Titanium.UI.createAlertDialog({
message : err,
title : "Remote Server Error"
});
}
};
request.onerror = function(e) {
Ti.API.info(e.error);
};
request.open("POST", "http://test.com");
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send({ test: 'test'});
if you don't get your answer please let me know.
Thanks

Updating MVC Model List using Knockout.js

I am working on an app which connects to XSockets via WCF and am able to get the data on the client side. I want to display this data using Grid.Mvc and have seen samples of using knockout.js, but I am not sure how to push this into my IEnumerable model so that I can see the View updated.
I have tried using the following code
#{
var initialData = new JavaScriptSerializer().Serialize(Model); }
$(function() {
ws = new XSockets.WebSocket("ws://127.0.0.1:4502/Book");
var vm = ko.mapping.fromJSON('#Html.Raw(initialData)');
ko.applyBindings(vm);
//Just write to the console on open
ws.bind(XSockets.Events.open, function (client) {
console.log('OPEN', client);
ws.bind('SendBook', function (books) {
jQuery.ajax({
type: "POST",
url: "#Url.Action("BooksRead", "Home")",
data: JSON.stringify(books),
dataType: "json",
contentType: "application/json",
success: function (result) {
//This doesnt work
/vm.push({Name:'Treasure Island',Author:'Robert Louis Stevenson'});
//vm.pushAll(result)
},
error: function (result){},
async: false
});
});
});
I am always receiving a null value for the parameter in the the BooksRead JsonResult method.
The model is a simple one
public class BookModel
{
public string Name {get; set;}
public string Author {get; set;}
}
I am returning a BookModel IEnumerable as my Model from the home controller on load and would want to insert new books into it as I receive them in the socket bind. This is because I am using it to generate the grid.
#Html.Grid(Model).Columns(c =>
{
c.Add(b => b.Name).Titled("Title");
c.Add(b => b.Author);
})
I would appreciate any pointers and guidance as to how I can go about achieving this.Many thanks
UPDATE
I am now able to get values in the controller action method after removing the dataType & contentType parameters from the ajax call. The controller method is as follows
public JsonResult BooksRead(string books)
{
BookModel data = JsonConvert.DeserializeObject<BookModel>(books);
List<BookModel> bookList = (List<BookModel>) TempData["books"];
if (bookList != null && data != null)
{
bookList.Add(data);
var bookString = JsonConvert.SerializeObject(bookList);
return Json(bookString);
}
return Json("");
}
I have added a vm.push call in the success handler and am passing the result value to it, but it still doesnt seem to add the new book in the Model. It seems I am doing it the wrong way as I am new to knockout js, jquery & ajax and trying to learn as I go along so please pardon my ignorance
UPDATE 2
I have made a few more changes.Like Uffe said, I have removed the Ajax call. I am adapting the StockViewModel from the StockTicker example to my BookViewModel and have added a parameter to the ctor to take in my IEnumerable model. This works & the item is added. The AddOrUpdate is working fine too & the objects are added to the collection but how can I get my model to be updated in the grid.
#{
var initialData = #Html.Raw(JsonConvert.SerializeObject(Model));
}
$(function() {
vm = new BookViewModel(#Html.Raw(initialData));
ko.applyBindings(vm);
ws = new XSockets.WebSocket("ws://127.0.0.1:4502/Book");
//Just write to the console on open
ws.bind(XSockets.Events.open, function(client) {
console.log('OPEN', client);
ws.bind('SendBook', function (msg) {
vm.AddOrUpdate(msg.book);
});
ws.bind(XSockets.Events.onError, function (err) {
console.log('ERROR', err);
});
});
});
The ViewModel is as follows
var BookViewModel = function(data) {
//this.Books = ko.observableArray(data);
this.Books = ko.observableArray(ko.utils.arrayMap(data, function(book) {
return new BookItem(book);
}));
this.AddOrUpdate = function(book) {
this.Books.push(new BookItem(book));
};
};

Knockoutjs - function inside viewmodel causing undesirable recursion

In my Knockout view model I have a Save() function which sends a jQuery POST request. Inside this POST request is a call to ko.toJS(this).
Whenever I call this Save function the browser becomes unresponsive and eventually tells me that there's too much recursion. Upon debugging (by using breakpoints), I found that when I call toJS() it appears to do some degree of cloning of the object, and in doing this cloning it calls the Save() function, which in turn calls toJS()... and there's the recursion.
Why exactly does this happen, and is there a way to avoid it without using toJSON()?
[I have another question regarding toJSON, and which explains why I don't want to use it.]
For the sake of completeness, here is my view model.
function vmDictionary(dict) {
if (dict === null || dict === undefined) {
return;
}
var self = this;
// directly-assigned variables
self.Concepts = new vmConcepts(dict.Concepts);
self.Deleted = ko.observable(dict.Deleted);
self.Description = ko.observable(dict.Description);
self.IncludeInSearch = ko.observable(true);
self.ID = ko.observable(dict.ID);
self.Languages = ko.observableArray(dict.Languages);
self.LastUpdate = new vmChangeRecord(dict.LastUpdate);
self.Name = ko.observable(dict.Name);
self.Public = ko.observable(dict.Public);
self.TemplateName = function(observable, bindingContext) {
return "dictionary-template";
};
// computed variables
self.PublicText = ko.computed(function() {
return sp.Utils.Localize(self.Public
? "Public"
: "Private");
});
// exposed functions
self.Save = function () {
$.ajax({
data: ko.toJSON(self),
dataType: "json",
type: "POST",
url: [...],
statusCode: {
200: function (response) {
console.log(response);
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
console.log(xmlHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
};
}
UPDATE: added the entire view model (above).
You must be doing something wrong, works in a little fiddle for me
http://jsfiddle.net/brN9s/
ViewModel = function() {
this.someData = ko.observable("Test");
this.dto = ko.observable();
};
ViewModel.prototype = {
Save: function() {
this.dto(ko.toJS(this));
}
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
viewModel.Save();