I am consuming Wcf Rest Service into Angular JS Web Application. I am posting multi request from angular js application to wcf . When i post the request to wcf service i got following errors in console application .
The server encountered an error processing the request. The exception message is 'Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[System.String]' to type 'System.IConvertible'.'. See server logs for more details. The exception stack trace is:
Here is the Linq Query ..
public bool cheekCreditScore(Credit_Crad credit)
{
int i = 600;
//int j = 700;
//int k = 800;
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
var query = (from x in context.Credit_Score
where x.Account_Holder_First_Name == credit.account_first_name && x.Account_Holder_First_Name == credit.account_last_name
select x.Credit_Score1);
if ((Convert.ToDouble(i) < Convert.ToDouble(query)))//**Error on this line**
{
return true;
}
else
{
return false;
}
}
}
Here is screen shot on debugging mode ..
Here is the screen shot when i run the application .
Your query returns credit score of all the account holders(assuming a worst case where two or more account holder has same name ), hence you need to narrow it down to single or first result.
var query = (from x in context.Credit_Score
where x.Account_Holder_First_Name == credit.account_first_name
&& x.Account_Holder_First_Name == credit.account_last_name
select x.Credit_Score1).FirstOrDefault();
I have been trying to get all the users for my web application (GAE for Java backend) using gitkitClient.getAllUsers(). I'm just getting started with Identity Toolkit and have 10-12 users.
When I call gitkitClient.getAllUsers() it doesn't find any user and returns this warning:
com.google.identitytoolkit.GitkitClient$1 getNextResults
WARNING: JSONObject["email"] not found.
If I call it with a parameter for max results gitkitClient.getAllUsers(5), it returns 5 users correctly. But if I pass 7, it again doesn't find any user, and returns the same warning (as above). I know that I have 10+ users.
If I use gitkitClient.getUserByEmail("test#example.com") I can get the users that are not returned in the first 5.
Here's my code sample:
Iterator<GitkitUser> allUsers = gitkitClient.getAllUsers();
int count = 0;
if (allUsers != null) {
while (allUsers.hasNext()) {
count++;
GitkitUser gUser = allUsers.next();
logger.info("" + count + ". User email : " + gUser.getEmail() + " Id : " + gUser.getLocalId());
}
}
Am I missing something?
Are you using the iterator like this:
val userIterator = gitkitClient.getAllUsers();
while (userIterator.hasNext()) {
LOG.warning(userIterator.next().getEmail)
}
I've not been keeping to close an eye on the number of users, but this seems to return ALL of the known users.
B.
You can get the child count via
firebase_node.once('value', function(snapshot) { alert('Count: ' + snapshot.numChildren()); });
But I believe this fetches the entire sub-tree of that node from the server. For huge lists, that seems RAM and latency intensive. Is there a way of getting the count (and/or a list of child names) without fetching the whole thing?
The code snippet you gave does indeed load the entire set of data and then counts it client-side, which can be very slow for large amounts of data.
Firebase doesn't currently have a way to count children without loading data, but we do plan to add it.
For now, one solution would be to maintain a counter of the number of children and update it every time you add a new child. You could use a transaction to count items, like in this code tracking upvodes:
var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
return (current_value || 0) + 1;
});
For more info, see https://www.firebase.com/docs/transactions.html
UPDATE:
Firebase recently released Cloud Functions. With Cloud Functions, you don't need to create your own Server. You can simply write JavaScript functions and upload it to Firebase. Firebase will be responsible for triggering functions whenever an event occurs.
If you want to count upvotes for example, you should create a structure similar to this one:
{
"posts" : {
"-JRHTHaIs-jNPLXOQivY" : {
"upvotes_count":5,
"upvotes" : {
"userX" : true,
"userY" : true,
"userZ" : true,
...
}
}
}
}
And then write a javascript function to increase the upvotes_count when there is a new write to the upvotes node.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.countlikes = functions.database.ref('/posts/$postid/upvotes').onWrite(event => {
return event.data.ref.parent.child('upvotes_count').set(event.data.numChildren());
});
You can read the Documentation to know how to Get Started with Cloud Functions.
Also, another example of counting posts is here:
https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js
Update January 2018
The firebase docs have changed so instead of event we now have change and context.
The given example throws an error complaining that event.data is undefined. This pattern seems to work better:
exports.countPrescriptions = functions.database.ref(`/prescriptions`).onWrite((change, context) => {
const data = change.after.val();
const count = Object.keys(data).length;
return change.after.ref.child('_count').set(count);
});
```
This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.
This hinges on the fact that the Firebase REST API offers a shallow=true parameter.
Assume you have a post object and each one can have a number of comments:
{
"posts": {
"$postKey": {
"comments": {
...
}
}
}
}
You obviously don't want to fetch all of the comments, just the number of comments.
Assuming you have the key for a post, you can send a GET request to
https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true.
This will return an object of key-value pairs, where each key is the key of a comment and its value is true:
{
"comment1key": true,
"comment2key": true,
...,
"comment9999key": true
}
The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length).
This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.
Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).
The 'trick' here is to use the node priority to as the vote count...
The data is:
vote/$issueBeingVotedOn/user/$uniqueIdOfVoter = thisVotesCount, priority=thisVotesCount
vote/$issueBeingVotedOn/count = 'user/'+$idOfLastVoter, priority=CountofLastVote
,"vote": {
".read" : true
,".write" : true
,"$issue" : {
"user" : {
"$user" : {
".validate" : "!data.exists() &&
newData.val()==data.parent().parent().child('count').getPriority()+1 &&
newData.val()==newData.GetPriority()"
user can only vote once && count must be one higher than current count && data value must be same as priority.
}
}
,"count" : {
".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
newData.getPriority()==data.getPriority()+1 "
}
count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.
}
}
Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.
<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
window.fb = new Firebase('https:...vote/iss1/');
window.fb.child('count').once('value', function (dss) {
votes = dss.getPriority();
for (var i=1;i<10;i++) vote(dss,i+votes);
} );
function vote(dss,count)
{
var user='user/zz' + count; // replace with auth.id or whatever
window.fb.child(user).setWithPriority(count,count);
window.fb.child('count').setWithPriority(user,count);
}
</script>
The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)
The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).
write a cloud function to and update the node count.
// below function to get the given node count.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.userscount = functions.database.ref('/users/')
.onWrite(event => {
console.log('users number : ', event.data.numChildren());
return event.data.ref.parent.child('count/users').set(event.data.numChildren());
});
Refer :https://firebase.google.com/docs/functions/database-events
root--|
|-users ( this node contains all users list)
|
|-count
|-userscount :
(this node added dynamically by cloud function with the user count)
Background
I have a list of sObjects I need to insert, but I must first check if the insert will be successful. So, I'm setting a database save point before performing the insert and checking the save results (for the insert statement). Because, I don't want to process if any errors occurred, if there were any errors in the insert results, the database is rolled back to the save point.
Problem & Question
I need to collect the errors for each save (insert) result and associate each error to the specific sObject record that caused the error. According to the documentation Save results contain a list of errors, the Salesforce ID of the record inserted (if successful), and a success indicator (boolean).
How do I associate the Save Result to the original sObject record inserted?
Code/Example
Here's an example I put together that demonstrates the concept. The example is flawed, in that the InsertResults don't always match the sObjectsToInsert. It's not exactly the code I'm using in my custom class, but it uses the same logic.
Map<Id,sObject> sObjectsToInsert; // this variable is set previously in the code
List<Database.SaveResult> InsertResults;
Map<String,sObject> ErrorMessages = new Map<String,sObject>();
System.SavePoint sp = Database.setSavepoint();
// 2nd parameter must be false to get all errors, if there are errors
// (allow partial successes)
InsertResults = Database.insert(sObjectsToInsert.values(), false);
for(Integer i=0; i < InsertResults.size(); i++)
{
// This method does not guarantee the save result (ir) matches the sObject
// I need to make sure the insert result matches
Database.SaveResult ir = InsertResults[i];
sObject s = sObjectsToInsert.values()[i];
String em = null; // error message
Integer e = 0; // errors
if(!ir.isSuccess())
{
system.debug('Not Successful');
e++;
for(Database.Error dbe : ir.getErrors()) { em += dbe.getMessage()+' '; }
ErrorMessages.put(em, s);
}
}
if(e > 0)
{
database.rollback(sp);
// log all errors in the ErrorMessages Map
}
Your comment says the SaveResult list is not guaranteed to be in order, but I believe that it is. I've used this technique for years and have never had an issue.
I am looking for a way to mass update case Status and leave a success message or failure message with failed case ID.
I currently have validation rules and triggers for update or cases. But I need to keep show at least the first failed case ID in the error message.
Is there a way to put a variable in the validation rule error message? Or its explicitly string?
I currently use a validation rule but I cant show the failed case in my error message because I cant put a variable in the error message.
Check this Link it might help you http://appexchange.salesforce.com/listingDetail?listingId=a0N30000003IleFEAS
You need to use a before trigger in this case and compare the list of selected cases before and after the update.
Or you can create a custom button and add it to the page and run the desired javascript to check what changed before and after.
something like this :
{!REQUIRESCRIPT("/soap/ajax/13.0/connection.js")}
var idArray = {!GETRECORDIDS($ObjectType.Case)};
var err = [];
var caseObj;
for (i=0; i< idArray.length ; i++){
caseObj = new sforce.SObject("Case");
caseObj.Id = idArray[i];
caseObj.Status = *** //change status here;
var result = sforce.connection.update([caseObj]);
if (result[0].success=='false') {
err.push("\n"+result[0].errors.message + " Case ID "+idArray[i]);
}
}
if(err.length >0)
{
alert(" The following cases have failed to change status: \n\n" +err);
}
location.reload(true);