Breeze.js Passthrough Predicate Odata Url - breeze

I am attempting to create an odata url with multiple breeze.js passthrough predicates using documentation from the folowing link: http://www.getbreezenow.com/documentation/query-using-json.
However the generated url looks nothing like an odata url eg:
var query = breeze.EntityQuery.from('User').using(this.manager).where("{ { 'userName': { '=': '123456' } } }");
var url = query._toUri(this.manager);
url is "User?$filter=%7B%20%7B%20'userName'%3A%20%7B%20'%3D'%3A%20'123456'%20%7D%20%7D%20%7D&$orderby=UserName" rather than "User?$filter=(UserName eq '123456')&$orderby=UserName".

I don't think you want a passthru query because this just passes your where clause thru intact without any processing. This is what happens when you quote the entire where clause.
If you want your query converted to 'odata' syntax then try the following:
var query = breeze.EntityQuery.from('Customers').using(em)
.where({ 'userName': { '==': '123456' } });
Note that the 'where' argument is NOT in quotes ( it is a standard javascript object), and the operator is '==', not '=';
or even simpler
var query = breeze.EntityQuery.from('Customers').using(em)
.where( { userName: '123456' });
Further info:
There are two forms of urls that can be generated from any breeze query. An OData form and a JSON form. If you want OData, (the default) then you either do nothing because it is the default or you can tell breeze explicitly with:
breeze.core.config.initializeAdapterInstance("uriBuilder", "odata");
If you want the json form, you would use
breeze.core.config.initializeAdapterInstance("uriBuilder", "json");
It also possible that you added a line to use the 'json' uriBuilder. Just omit this line if you want OData urls. You can still construct the query via the json syntax, but the URL will be output using OData syntax.
The Json form ( or uri) is useful for non OData servers.

Related

Neo4j Python REST API

Query via Python REST-APi
message: Invalid input: ':'
Hello,
i am starting a query via my Python-Neo4j-Api.
But the code ist not working, resulting in the the error message above.
But the same query is working in the Neo4J Desktop App.
Why is it working in the Neo4j Desktop App, but not via my Api Query. Why is the : before param a Problem?
I am new to Python and Neo4j, please help.
King regards.
Trying to query via a Python-Neo4j-RestAPI.
Below is the syntax on passing parameters in neo4j python driver. Unfortunately, you cannot use labels or relationship types in the parameter. If you need to pass labels (like Human:Moviestar) then you can use string function in python like this: passing parameters in neo4j using python
name = "Tom Cruise"
placeOfBirth = "Syracuse, New York, United States"
query = "Create (n:Human:Moviestar { name: $name, placeOfBirth: $placeOfBirth})"
session = driver.session()
result = session.run(query, name=name, placeOfBirth=placeOfBirth)
I see that you have been working with the database though the browser application. So commands that are prefixed with ":" like :params or :connect are browser commands and is not valid cypher. Instead, in python pass your parameters as the second argument to your to your session.run() function or transaction. Then use variable substitution to in your cypher query.
params = {"name": "Tom Hanks" }
with driver.session as session:
result = session.run ("MATCH (p:person) where p.name = $name return p", params)

Filename with a hash (#) not uploading

I'm attempting to send a file to OneDrive using the following code:
$uri = "/me/drive/items/$folderId/children('{$fileName}')/content";
$graph = $this->graph->create($user);
$client = $this->graph->createClient();
$item = $graph->createRequest("PUT", $uri)
->attachBody($fileContent)
->setReturnType(Model\DriveItem::class)
->execute($client);
This works great if $fileName is something like Test.doc
But for some reason, when the filename has a hash (#) in the filename, then I get an error:
object(Microsoft\Graph\Model\DriveItem)#1509 (1) {
["_propDict":protected]=>
array(1) {
["error"]=>
array(3) {
["code"]=>
string(10) "BadRequest"
["message"]=>
string(36) "Bad Request - Error in query syntax."
["innerError"]=>
array(2) {
["request-id"]=>
string(36) "ff3fe15f-b1ee-4e92-8abd-2400b1c1b5cf"
["date"]=>
string(19) "2018-10-04T14:30:51"
}
}
}
Can someone possibly clarify if this is a bug or actual behaviour (i.e. you cannot have a # in a filename)
Thanks
I guess you are utilizing Microsoft Graph Library for PHP, special characters such as # needs to be escaped.
So, either replace the hash with %23 (percent encoding) or use rawurlencode function as shown below:
$fileName = rawurlencode("Guide#.docx");
$requestUrl = "https://graph.microsoft.com/v1.0/drives/$driveId/root:/$fileName:/content";
try {
$item = $client->createRequest("PUT", $requestUrl)
->attachBody($fileContent)
->setReturnType(Model\DriveItem::class)
->execute();
} catch (\Microsoft\Graph\Exception\GraphException $ex) {
print $ex;
}
Although the file name have support # in name, but it doesn't mean the Product Team provide the API or adjust the existing API first time, the API you use may not have fully adjusted to suit thore latest naming rules. So it should be actual behavior now but not bug/or you can treat it as none-existed feature.
There are a related issue in the SharePoint dev issue list, although they aren't same one, but the suggestion is the same, vote the exising feature or submit an new one on UserVoice.

ajax post to external database from Rails app

I am trying to insert data from a form built with Ruby on Rails to my SQL Server database. I have connected my database correctly and can pull data from it. I am now trying to post back to it. I am needing help with figuring out how to get the data from the form into the correct columns in my table in the database.
My ajax:
<script>
$('#Favorites').on('submit',function(event){
    var $form = $(this),
    data = $form.serialize();
    var url = 'http://localhost:3000/welcome/insert';
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function(){
            
alert('Your form has been successfully submitted!');
document.getElementById('Favorites').reset();
window.location.reload();
        },
        fail:function(){
            alert('something went wrong...try again');
        }
    });
return false;
});
</script>
My controller function:
def insert
#ipinsert=Ipdw.connection.execute("insert into [DB_Test02].[dbo].[My_Table] (Report_Name,Report_Link)
values ('I am cool','www.google.com')")
end
Currently I just have a dummy insert statement here to make sure that I can insert into the tables and I can. I just need to know how to break out the form values sent to the controller and how to tell Rails what table and columns to put those values into.
Rails will format the data for you. In controller like this:
{'Report_Name': 'some name', 'Report_link': 'www.example.com'}
and will be accessible via the params.
Your job is now to format the data correctly for the manual execution of the SQL query.
insert_values = "('%s', '%s')" % params['Report_Name'], params['Report_link']
#ipinsert=Ipdw.connection.execute("insert into [DB_Test02].[dbo].[My_Table] (Report_Name,Report_Link) values #{insert_values}")
For the problem of which table to add to your DB server you could specify this in hidden fields in your form and every fieled should have a name, When you say $form.serialize(); it turns it to something like FirstName=Amr&SecondName=Adel and so on where FirstName is the name of the field and Amr is the value of the field, Then you put this serialization into a form of JSON format like {"data": $form.serialize()} and add dataType: "JSON" to your post request, In your Insert function you can get it through params[:data] and split it with& to be something like ['FirstName=Amr','SecondName=Adel'] and every element split it with = so you can get something like this [['FirstName','Amr'], ['SecondName','Adel']].
Hope this helps.

Grails RestBuilder query parmeters

I'm writing some functional tests for a Grails controller, and I feel it's getting messy when testing the query parameters.
I know that I can do this, but it just seems clunky.
Map getParms = [id:1, x:foo, y:bar, z:baz]
RestResponse response = builder.get("http://example.com/api/{id}?x={x}&y={y}&z={z}") {
urlVariables getParams
}
Ideally I'd like to:
Fill the base URL (i.e. the Id) using the urlVariables argument above
Pass another map of query params that appends each as a key value pair
Something like:
Map queryParms = [x:foo, y:bar, z:baz]
RestResponse response = builder.get("http://example.com/api/{id}") {
urlVariables id:1
queryVariables queryParams
}
I feel this would be much more 'DRY', and easier to read/write.
Does anyone know if such a mechanism exists? I know I could put together a class to do it, but I was hoping to avoid this if there is an existing implementation.
You can do as below.
Map queryParams = [x: 'foo', y: 'bar', z: 'baz']
RestResponse response = builder.get("http://example.com/api/{id}", queryParams) {
urlVariables id:1
}
RestBuilder's get() is overloaded to accept three params: String url, Map queryParams and the RequestCustomizer closure
I felt the same awkwardness when initially using the API. Currently I'm doing something slightly more concise:
RestResponse response = builder.get("http://example.com/api/{id}?x={x}&y={y}", [id:1, x:'foo', y:'bar'])
It doesn't feel that bad, kinda same style with named sql parameters in groovy SQL

Mongo and Node.js: unable to look up document by _id

I'm using the Express framework and Mongodb for my application.
When I insert objects into the database, I use a custom ObjectID. It's generated using mongo's objectid function, but toString()ed (for reasons i think are irrelevant, so i won't go into them). Inserts look like this:
collection.insert({ _id: oid, ... })
The data is in mongo - i can db.collection.find().pretty() from mongo's cli and see it exactly as it's supposed to be. But when I run db.collection.find({_id: oid}) from my application, I get nothing ([] to be exact). Even when I manually hardcode the objectID that I'm looking for (that I know is in the database) into my query, I still can't get an actual result.
As an experiment, I tried collection.find({title: "test title"}) from the app, and got exactly the result I wanted. The database connection is fine, the data structure is fine, the data itself is fine - the problem is clearly with the _id field.
Query code:
var sid = req.param("sid");
var db = req.db;
var collection = db.get("stories");
collection.find({'_id': sid }, function(err, document) {
console.log(document.title);
});
Any ideas on how I can get my document by searching _id?
update: per JohnnyHK's answer, I am now using findOne() as in the example below. However, it now returns null (instead of the [] that i was getting). I'll update if I find a solution on my own.
collection.findOne({'_id': sid }, function(err, document) {
console.log(document);
});
find provides a cursor as the second parameter to its callback (document in your example). To find a single doc, use findOne instead:
collection.findOne({'_id': sid }, function(err, document) {
console.log(document.title);
});

Resources