How do I simplify this query?
var cookieList = _httpContextAccessor.HttpContext.Request.Cookies.ToList()
.Select(cookie => new { cookie.Key, cookie.Value })
.AsEnumerable()
.Select(cookie => $"{cookie.Key}={cookie.Value}")
.ToList()
var cookieList = _httpContextAccessor.HttpContext.Request.Cookies // assumed IEnumerable otherwise .ToList is ok
.Select(cookie => $"{cookie.Key}={cookie.Value}")
.ToList()
Related
I want to use a better solution if exists so it will make the following simpler.
If this.projectguid is empty then want to use the switchMap call otherwise the other one.
Can anyone suggest me a better solution for this?
getWorksheet(): Observable<Worksheet | number> {
if(this.projectsGuid === '') {
return this.apiService.get('projects/latest')
.pipe(
switchMap((res: {id: string, name: string}) => {
this.projectsGuid = res.id
let getUrl = `projects/${this.projectsGuid}/questionnaires/${this.questionnaireId}/worksheets/latest`;
return this.apiService.get<Worksheet>(getUrl).pipe(
catchError((err) => {
return of(err.status);
})
);
})
)
} else {
let getUrl = `projects/${this.projectsGuid}/questionnaires/${this.questionnaireId}/worksheets/latest`;
return this.apiService.get<Worksheet>(getUrl).pipe(
catchError((err) => {
return of(err.status);
})
);
}
}
You could define a projectGuid$ observable that emits the this.projectsGuid value if not empty, and otherwise emits the result of the http call (mapped to just the id):
const projectGuid$ = this.projectsGuid !== ''
? of(this.projectsGuid)
: this.apiService.get('projects/latest').pipe(
map(({id}) => id),
tap(guid => this.projectsGuid = guid)
);
Then you can pipe the projectGuid to the call to fetch the worksheet:
return projectGuid$.pipe(
map(guid => `projects/${guid}/questionnaires/${this.questionnaireId}/worksheets/latest`),
switchMap(url => this.apiService.get<Worksheet>(url).pipe(
catchError(err => of(err.status))
))
);
I'm using the following code to bulkindex documents. It works for everything except my Product model, but only when I try to index more than a few documents. If I do only 1 document it works fine. If I do 10, it fails. My Product model is not very complex, but it does have some nested documents with infinite self-referencing loops, but I did add ReferenceLoopHandling.Ignore to handle it.
public bool BulkIndex<T>(IEnumerable<T> items) where T : class
{
var waitHandle = new CountdownEvent(1);
var bulkAll = _client.BulkAll(items, b => b
.BackOffRetries(2)
.BackOffTime(TimeSpan.FromSeconds(5))
.RefreshOnCompleted(true)
.MaxDegreeOfParallelism(4)
.Size(100)
.Index(typeof(T).Name.ToLower())
);
bulkAll.Subscribe(new BulkAllObserver(
onNext: (b) => { Console.Write("."); },
onError: (e) => { throw e; },
onCompleted: () => waitHandle.Signal()
));
waitHandle.Wait();
return true;
}
new JsonNetSerializer(builtInSerializer, connectionSettings, () => new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}))
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
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()));