I´m having trouble populating a list with the result from an API using ReactiveOauth for wp7.
It works when i´m populating the listbox directly. But I can´t figure out how to add the object to a list instead. The list is always empty when doing it like this .Subscribe(a => lista.Add(new Device ...
Any suggestions is very appreciated.
var token = TelldusWrapper.Security.GetToken();
var lista = new List<Device>();
var client = new OAuthClient(ConsumerKey, ConsumerSecret, token)
{
Url = "http://api.telldus.com/xml/devices/list",
Parameters = { { "supportedMethods", "TELLSTICK_TURNON" } }
};
client.GetResponseText().Select(s => XElement.Parse(s))
.SelectMany(x => x.Descendants("device"))
.Select(x => new
{
Text = x.Attribute("id").Value,
Name = x.Attribute("name").Value
})
.ObserveOnDispatcher()
.Subscribe(a => listbox.Items.Add(new Device { Id = a.Text, Name = a.Name }), ex => MessageBox.Show(ex.ToString()));
//.Subscribe(a => lista.Add(new Device { Id = a.Text, Name = a.Name }), ex => MessageBox.Show(ex.ToString()));
Related
Following value is being retrieved in a Cypress custom command,
listOfResults = [{"name":"x","amount":"99"}, {"name":"y","amount":"88"}]
and the command is,
Cypress.Commands.add("getResultList", (keyWord, ...args) => {
var listOfResults = [];
cy.get('[class="result"]')
.each((resultItem) => {
var singleResult = {};
//Retrive Title
cy.wrap(resultItem)
.find('.name')
.invoke("text")
.then((val) => {
const title = val.replaceAll("\n", "");
singleResult.title = title;
});
//Retrive price
cy.wrap(resultItem)
.find('.price')
.invoke("text")
.then((val) => {
const price = val.replaceAll("\n", "");
singleResult.amount = price;
});
cy.then(() => {
listOfResults.push(singleResult);
});
})
.then(() => {
cy.log(listOfResults);//prints. correctly
cy.wrap(listOfResults);
//tried also return cy.wrap(listOfResults);
});
});
and in test, I am trying to access and store it.
//fetch all data in Search Results page and store it
var resultList = cy.getResultList();
cy.log("length:" + resultList.length);
But it is not getting stored and resultList.length logs undefined. How could we make the command to return a value?
I think just adding two returns will be ok,
Cypress.Commands.add("getResultList", (keyWord, ...args) => {
var listOfResults = [];
return cy.get('[class="result"]')
.each((resultItem) => {
var singleResult = {};
//Retrive Title
cy.wrap(resultItem)
.find('.name')
.invoke("text")
.then((val) => {
const title = val.replaceAll("\n", "");
singleResult.title = title;
});
//Retrive price
cy.wrap(resultItem)
.find('.price')
.invoke("text")
.then((val) => {
const price = val.replaceAll("\n", "");
singleResult.amount = price;
});
cy.then(() => {
listOfResults.push(singleResult);
});
})
.then(() => {
cy.log(listOfResults);//prints. correctly
cy.wrap(listOfResults);
return cy.wrap(listOfResults); // this modifies the outer return
});
});
Must be used in test with .then() like any command
cy.getResultList(keyword).then(resultList => {
...
To illustrate better the point Alapan makes, in a custom command the result of the last command is automatically returned.
So this is the minimum needed for your command
Cypress.Commands.add("getResultList", (keyWord, ...args) => {
var listOfResults = [];
cy.get('[class="result"]')
.each((resultItem) => {
var singleResult = {};
//Retrive Title
cy.wrap(resultItem)
.find('.name')
.invoke("text")
.then((val) => {
const title = val.replaceAll("\n", "");
singleResult.title = title;
});
//Retrive price
cy.wrap(resultItem)
.find('.price')
.invoke("text")
.then((val) => {
const price = val.replaceAll("\n", "");
singleResult.amount = price;
});
cy.then(() => {
listOfResults.push(singleResult);
});
})
cy.wrap(listOfResults) // last command, Cypress returns this
});
In custom command you have to do:
return cy.wrap(listOfResults)
Then in your test:
cy.getResultList(keyWord, ...args).then((listOfResults) => {
//Do something here with listOfResults
})
Since wrap() is returning a Cypress.Chainable, we can call .then() on our commands.
I have the next code, and it was working properly. to execute a request to my method fetchDropdownDataByFederationId, but now I have a requirement to execute the same method x number of times.
fetchInProgress(queryString?): Observable<IPerson[]> {
let PersonList: IPerson[] = [];
return this.getItems<IPerson[]>('', queryString).pipe(
take(1),
switchMap((wls: IPerson[]) => {
PersonList = [...wls];
//const createdbyIds = [...new Set(wls.map((f) => f.createdBy))];
return this.teamPageService.getInformation(wls.createdBy);
}),
map((teams:any) => {
console.log('> teams', teams);
for (let i = 0; i < PersonList.length; i++) {
//update information
}
//console.log('> Final value: ', PersonList);
return PersonList;
})
);
}
But, I'm not finding a way to execute my SwitchMap x number of times and get the results back to use them in my map method to parse the information.
I just moved my SwitchMap to mergeMap, something like this:
mergeMap((wls: IWalklist[]) => {
//let allIds = wls.contact.map(id => this.getSingleData(id._id) );
let drops: Dropdown[] = [];
walklistList = [...wls];
const allIds = [...new Set(wls.map((f) => f.createdBy))];
return forkJoin(...allIds).pipe(
map((idDataArray) => {
drops.push(
this.teamPageService.getInformation('');
);
return drops;
})
)
}),
But still no luck.
Can some help me? how can I fix it?
I try to retrieve datas in a subcollection based on the key received on the first call.
Basically, I want a list of all my user with the total of one subcollection for each of them.
I'm able to retrieve the data from the first Payload, but not from pointRef below
What is the correct way to achieve that?
getCurrentLeaderboard() {
return this.afs.collection('users').snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data()
const id = a.payload.doc.id;
const pointRef: Observable<any> = this.afs.collection('users').doc(`${id}`).collection('game').valueChanges()
const points = pointRef.map(arr => {
const sumPoint = arr.map(v => v.value)
return sumPoint.length ? sumPoint.reduce((total, val) => total + val) : ''
})
return { id, first_name: data.first_name, point:points };
})
})
}
I tried to put my code in a comment, but I think it's better formated as a answer.
First you need subscribe your pointRef and you can change your code like this.
getCurrentLeaderboard() {
return this.afs.collection('users').snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data()
const id = a.payload.doc.id;
const pointRef: Observable<any> = this.afs.object(`users/${id}/game`).valueChanges() // <--- Here
const pointsObserver = pointRef.subscribe(points => { //<--- And Here
return { id, first_name: data.first_name, point:points };
})
})
}
....
//Usage:
getCurrentLeaderboard.subscribe(points => this.points = points);
And if you going to use this function alot, you should start to denormalize your data.
Does the Elasticsearch NEST API expose access to /{index}/{_aliases}/*? I am trying to get a list of indexes mapped to a given alias and I cannot seem to find an appropriate method.
{
"ntdev-events017-v1": {
"aliases": {
"ntdev-events017": {}
}
}
}
http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-aliases.html
You can use GetAlias method on ElasticClient.
Take a look on this example:
var indexName = "sampleindex";
var uri = new Uri("http://localhost:9200");
var settings = new ConnectionSettings(uri).SetDefaultIndex(indexName).EnableTrace();
var client = new ElasticClient(settings);
client.CreateIndex(descriptor => descriptor.Index(indexName));
var putAliasResponse = client.PutAlias(descriptor => descriptor
.Index(indexName).Name("alias1"));
var putAliasResponse2 = client.PutAlias(descriptor => descriptor
.Index(indexName).Name("alias2"));
var aliasesForIndex = client.GetAlias(descriptor => descriptor
.Index(indexName))
.Indices[indexName]
.Select(x => x.Name).ToList();
var indexesMappedToAlias = client.GetAlias(descriptor => descriptor.Alias("alias2"))
.Indices.Select(x => x.Key).ToList();
I am attempting to see if the results of a view model are performing the correct actions.
My observables are setup as follows:
public FilterBoxViewModel()
{
var asyncFilterResults = this.filterItemsCommand.RegisterAsyncTask(x =>
this.PerformFilter(x as string));
this.filteredItems = new ObservableAsPropertyHelper<IEnumerable<IFilterBoxItem>>(
asyncFilterResults, _ => this.RaisePropertyChanged("FilteredItems"));
this.WhenAnyValue(x => x.SearchTerm)
.Throttle(TimeSpan.FromMilliseconds(50))
.Skip(1)
.Subscribe(this.filterItemsCommand.Execute);
}
Then further down I have
private async Task<IEnumerable<IFilterBoxItem>> PerformFilter(string searchTerm)
{
if (string.IsNullOrWhiteSpace(searchTerm))
{
return Enumerable.Empty<IFilterBoxItem>();
}
// Perform getting the items on the main thread and async await the results.
// This is provide a immutable version of the results so we don't cause
// threading issues.
var items = await Observable.Start(
() => this.FilterBoxManager.RootElements.GetAllItemsEnumerable()
.ToList().Select(x => new { Name = x.Name, Item = x }),
RxApp.MainThreadScheduler);
return
items.Where(x =>
x.Name.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase) >= 0)
.Select(x => x.Item);
}
In my test, I am running the test schedular and advancing it, however, I am getting the PerformFilter performing at different times than I expect
eg my test is:
(new TestScheduler()).With(scheduler =>
{
var viewModel = new FilterBoxViewModel();
var testManager = new TestManager { RootElements = this.sampleItems };
viewModel.FilterBoxManager = testManager;
viewModel.SearchTerm = "folder";
scheduler.AdvanceBy(TimeSpan.FromMilliseconds(51).Ticks);
Assert.AreEqual(viewModel.FilteredItems.Select(x => x.Name), folderSearchResults);
viewModel.SearchTerm = "apple";
Assert.AreEqual(viewModel.FilteredItems.Select(x => x.Name), appleSearchResults);
});
How do I make the tester more predictable?
I am running ReactiveUI 5.5.1 and in a XAML application.
Your Throttle doesn't set a scheduler, this is a classic TestScheduler mistake