WCF DataService 5 Any on single Entity (Client-Side) - silverlight

I have a question according to the WCF Data Services 5.0.1 Any/All-Features. I want to use it in a Silverlight 5 Application and I want to query against an Entity called "Employee" (with a unique EmpNo=personalNr) and check if it already exists (therefore, I check if there is an Employee with the same personalNrfor validation purposes)..
In older versions it was not possible to do this on the Client. I had to call a custom Service Operation on the Server which returned a boolean value.
Is there a way to do this on the Client likes this (and get a boolean value as a result):
bool result = this.Context.Employees.Any(e => e.PersonalNr.Equals(personalNr, StringComparison.OrdinalIgnoreCase));
Thanks in advance!
Steve

The any/all feature is only usable inside the filter expression and it is used to query based on related entities or collection properties. If you want to check just for existence of an employee without any relationship, you can do that without any/all. The idea is to simply filter all employees on the given condition and see if you get at least 1 result back.
Now since you're doing this in Silverlight, the operation must be asynchronous, so a simple statement like above will not work. You could do something like:
var query = (DataServiceQuery<Employee>)this.Context.Employees.Where(e => e.PersonalNr.ToLower() == personalNr.ToLower()).Take(1);
query.BeginExecute((ar) =>
{
var results = query.EndExecute(ar);
// The usage of Any here is simply because it's the easiest way to do this
// and it is not used over OData/WCF DS, this is simply checking if the results returned
// from the service contain at least one result.
bool employeeExists = results.Any();
}, null);
Few notes about the code above:
The WCF Data Services doesn't support the Equals method with comparison options and the OData protocol doesn't support case insensitive string comparison either. So to workaround that, simply convert all values to lower case before comparing.
The Take(1) is used to only ask for the first value which matches the condition. Since we're only gonna use the existence of the result anyway, we don't need to ask the service for all the results (small optimization).

Related

Get selected values in a checkbox group in xpages

I have a checkbox group and I am trying to get the values ​​selected via SSJS, but so far I have not been successful. I've tried several syntaxes, such as:
document1.getItemValueArray ("nameField")
and
getComponent ("nameField") getSelectedValues ​​();
Does anyone know a way to get the selected values ​​from a checkbox group?
document1.getFirstItem("nameField").getValues() may be what you want. If it's one value, it will be a string, not a Vector, which may be a problem with getItemValueArray().
With ODA (OpenNTF Domino API), we extended the getItemValue() method to take a second parameter and cast the result to that kind of object. That has a big benefit for this kind of scenario, allowing getItemValue("nameField", ArrayList.class) to always return an ArrayList even for a single value, plus ArrayList is a much better and more modern Java (so relevant also for SSJS) construct than a Vector.

Most efficient way to increment a value of everything in Firebase

Say I have entries that look like this:
And I want to increment the priority field by 1 for every Item in the list of Estimates.
I can grab the estimates like this:
var estimates = firebase.child('Estimates');
After that how would I auto increment every Estimates priority by 1?
FOR FIRESTORE API ONLY, NOT FIREBASE
Thanks to the latest Firestore patch (March 13, 2019), you don't need to follow the other answers above.
Firestore's FieldValue class now hosts a increment method that atomically updates a numeric document field in the firestore database. You can use this FieldValue sentinel with either set (with mergeOptions true) or update methods of the DocumentReference object.
The usage is as follows (from the official docs, this is all there is):
DocumentReference washingtonRef = db.collection("cities").document("DC");
// Atomically increment the population of the city by 50.
washingtonRef.update("population", FieldValue.increment(50));
If you're wondering, it's available from version 18.2.0 of firestore. For your convenience, the Gradle dependency configuration is implementation 'com.google.firebase:firebase-firestore:18.2.0'
Note: Increment operations are useful for implementing counters, but
keep in mind that you can update a single document only once per
second. If you need to update your counter above this rate, see the
Distributed counters page.
EDIT 1: FieldValue.increment() is purely "server" side (happens in firestore), so you don't need to expose the current value to the client(s).
EDIT 2: While using the admin APIs, you can use admin.firestore.FieldValue.increment(1) for the same functionality. Thanks to #Jabir Ishaq for voluntarily letting me know about the undocumented feature. :)
EDIT 3:If the target field which you want to increment/decrement is not a number or does not exist, the increment method sets the value to the current value! This is helpful when you are creating a document for the first time.
This is one way to loop over all items and increase their priority:
var estimatesRef = firebase.child('Estimates');
estimatesRef.once('value', function(estimatesSnapshot) {
estimatesSnapshot.forEach(function(estimateSnapshot) {
estimateSnapshot.ref().update({
estimateSnapshot.val().priority + 1
});
});
});
It loops over all children of Estimates and increases the priority of each.
You can also combine the calls into a single update() call:
var estimatesRef = firebase.child('Estimates');
estimatesRef.once('value', function(estimatesSnapshot) {
var updates = {};
estimatesSnapshot.forEach(function(estimateSnapshot) {
updates[estimateSnapshot.key+'/priority'] = estimateSnapshot.val().priority + 1;
});
estimatesRef.update(updates);
});
The performance will be similar to the first solution (Firebase is very efficient when it comes to handling multiple requests). But in the second case it will be sent a single command to the server, so it will either fail or succeed completely.

What is the difference between a model object queried by filter and an object queried by get() in Django?

I keep coming across this issue where I am trying to update a record using the update() method.
It always works when I query an object using filter.
my_dictionary = {"key":"Val","another":"Val"}
thing = Thing.objects.filter(pk=1)
thing[0].update(**my_dictionary) wrote it wrong in the original question.
thing.update(**my_dictionary)
When I query the object using get() it keeps telling me that the object has no method update()
my_dictionary = {"key":"Val","another":"Val"}
thing = Thing.objects.get(pk=1)
thing.update(**my_dictionary)
Isn't a model object the same in both cases? Why would one have an update method and the other one not? Any insight would be greatly appreciated.
The documentation is very explicit about this:
filter() will always give you a QuerySet, even if only a single object matches the query - in this case, it will be a QuerySet containing a single element.
If you know there is only one object that matches your query, you can use the get() method on a Manager which returns the object directly.
Your first snippet returns a QuerySet, which has an update method. The second snippet returns a model instance, which doesn't.
Note that you have not shown the exact code you are using: thing[0].update would give exactly the same error as the second snippet.
You're using QuerySet.update() and ModelInstance.save().
If you’re just updating a record and don’t need to do anything with the model object, the most efficient approach is to call update(), rather than loading the model object into memory. For example, instead of doing this:
e = Entry.objects.get(id=10)
e.comments_on = False
e.save()
...do this:
Entry.objects.filter(id=10).update(comments_on=False)

Custom query filter

I have entities in my datastore like this:
class Location(ndb.Model):
x = ndb.IntegerProperty(required = True)
y = ndb.IntegerProperty(required = True)
(other properties here)
Now I need to filter the entities in my datastore based on their distance from a user defined location. Can I somehow pass a function that checks if the location is correct as a filter, or is there a better approach to this?
Directly using the datastore, definitely not.
You would need to grab everything and do the computations via your code.
for instance if your userLocation is (5,4), and you have a max distance of 10, you would need to grab everything with x>-5 and x<15 and y>-6 and y< 14 and manually take off those who are too far.

C#, Linq data from EF troubles

I don't have much experience with programming. I am working (to learn) on a project. I am using C# 4.0 and WPF 4 with EF (SQLite). I am having problemw with LINQ.
Here is the code in question (I hope this is enough, let me know if more is needed)
private void cboSelectCompany_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
using (ShippingEntities context = new ShippingEntities())
{
var companies = from company in context.Deliveries
where company.State == cboSelectCompany.SelectedItem.ToString()
select company;
txtDeliveryName.Text = companies.Name;
txtDeliveryState.Text = companies.State;
}
The last two lines don't work. Am I misunderstanding what LINQ is returning? I just get this error
Error 5 'System.Linq.IQueryable<SqliteDemo.Delivery>' does not contain a definition for 'State' and no extension method 'State' accepting a first argument of type 'System.Linq.IQueryable<SqliteDemo.Delivery>' could be found (are you missing a using directive or an assembly reference?) c:\users\dan\documents\visual studio 2010\Projects\SqliteDemo\SqliteDemo\DeliveryCompanies.xaml.cs 49 51 SqliteDemo
If anyone could give me some pointers or to a good reference I would appreciate it
You're close!
Linq is returning a Queryable set of Deliveries, which hasn't executed yet. My guess based on reading your code is that you're expecting at most one result, and then you want to put those values into a UI of some sort. In that case what you'll want to do is:
Take your IQueryable and execute it
Make sure you grab the first (or, alternatively enforce that there is only one) row
Set the appropriate values in the UI.
So, leave the line with the query there, and then change the rest to something like this:
var company = companies.FirstOrDefault();
txtDeliveryName.Text = company.Name;
txtDeliveryState.Text = company.State;
Insert null-checking as appropriate, and go check out the differences between First, FirstOrDefault, Single, and SingleOrDefault to see which one seems most correct for your particular situation.
Well, looks like companies.State doesn't compile, because companies is a list of SqliteDemo.Delivery (and not just a SqliteDemo.Delivery).
What do you want to achieve? Imagine that your LINQ query returns several results, is it possible?
Just use companies.FirstOrDefault() or companies.Single() to access first item becouse by default LINQ returns collection of items not just single item.

Resources