Vibe.D - undefinded identifier (Dlang) - d

I'm trying to create simple REST api, but when i try to compile my code im getting
frontpage.d(15,3): Error: undefined identifier 'tmp', did you mean
alias 'cmp'?
Here is my code:
module service.frontpage;
import vibe.d;
#path("/api")
interface IFrontPageAPI
{
Json getHome();
}
class FrontPageAPI : IFrontPageAPI
{
this(auto tmp)
{
auto collect = tmp;
}
Json getHome()
{
logInfo("Getting HomePage from DB");
Bson query = Bson(["_id" : Bson("homepage")]);
auto result = collect.find(query);
logInfo("Iterating results...");
foreach (i, doc; result.byPair)
logInfo("Item %d: %s", i, doc.toJson().toString());
return result.toJson();
}
}
Can someone help me with it? tmp is temporary variable to pass mongoDB collection handler.

Same answer as on DLearn.
You need to
- use Class variables
- use types instead auto (here Mongo collection)
- return a proper Json
Have a look at this interactive example - and feel free to play with it. No output means no compilation error.

Related

What is the equivalent of TiXmlAttribute for tinyxml2 and how to use it?

I've encountered a problem that I'm not being able to solve using tinyxml2.
I have a function that receives as a parameter a XMLElement and I need to iterate over its attributes. With tinyxml, this worked:
void xmlreadLight(TiXmlElement* light){
for (TiXmlAttribute* a = light->FirstAttribute(); a ; a = a->Next()) {
//Do stuff
}
}
Using the same with tinyxml2, like in the example below, I get the following error:
a value of type const tinyxml2::XMLAttribute * cannot be used to initialize an entity of type tinyxml2::XMLAttribute *
void xmlreadLight(XMLElement* light){
for (XMLAttribute* a = light->FirstAttribute(); a ; a = a->Next()) {
//Do stuff
}
}
The XML code in question is:
<lights>
<light type="POINT" posX=-1.0 posY=1.0 posZ=-1.0 ambtR=1.0 ambtG=1.0 ambtB=1.0 />
</lights>
where light is the XMLElement passed into the function xmlreadLight. Not sure if my question is properly set up, so if theres some info missing, let me know.
Going by the error message, it looks like you need to do:
for (const XMLAttribute* a = light->FirstAttribute(); a ; a = a->Next()) { ...
^^^^^
Presumbably, the return type of FirstAttribute has been made const in tinyxml2.
If you check the Github repository for the tinyxml2.h file on line 1513 you will see this:
/// Return the first attribute in the list.
const XMLAttribute* FirstAttribute() const {
return _rootAttribute;
}

How to create empty json object correctly using web.json in cpp?

I want to create following json request:
{
"Value1":{},
"Value2":"some string value"
}
to achieve this I have tried following code in cpp:
json::value &refRequest
json::value jRequest = json::value();
refRequest[requestKey::Value1] = json::value(json::value::object()); //for creating empty object
refRequest[requestKey::Value2] = json::value::string("some string");
but it gives output as:
{
"Value1":},
"Value2":"some string value"
}
if you observe, instead of returning empty object as {} it gives the output as } and this results in to malformed request. I am not sure where exactly I am going wrong, any help will would be appreciated. Thanks
I believe your mistake is that you are constructing a json::value from a json::value::object()
According to the documentation the line should be fixed to:
refRequest[requestKey::Value1] = json::value::object();

C++ REST (Casablanca) - Failure while reading JSON

I was trying my hands with C++ REST APIs
I wrote to json using below way.
json::value resp;
std::vector<Portfolio> portfolio;
// Populate portfolio
this->PortfolioList(usrStr, pwdStr, portfolio);
std::vector<Portfolio>::iterator it;
for (it = portfolio.begin(); it != portfolio.end(); it++)
{
char costBuff[40]; _itoa_s(it->GetTotalCost(), costBuff, 10);
char qtyBuff[40]; _itoa_s(it->GetQuantity(), qtyBuff, 10);
json::value portfolioEntry;
portfolioEntry[U("username")] = json::value::string(utility::conversions::to_string_t(it->GetUserName()));
portfolioEntry[U("stockCode")] = json::value::string(utility::conversions::to_string_t(it->GetStockCode()));
portfolioEntry[U("quantity")] = json::value::string(utility::conversions::to_string_t(qtyBuff));
portfolioEntry[U("totalcost")] = json::value::string(utility::conversions::to_string_t(costBuff));
resp[utility::conversions::to_string_t(it->GetStockCode())] = portfolioEntry;
}
For this I got output as below
{
"11002":{"quantity":11002,"totalcost":"272","username":"arunavk"},
"11003":{"quantity":11003,"totalcost":"18700","username":"arunavk"},
"11004":{"quantity":11004,"totalcost":"760","username":"arunavk"},
"11005":{"quantity":11005,"totalcost":"32","username":"arunavk"}
}
Now, on the receiving end, I tried to read it as below
for (int i = 0; i < size; i++)
{
table->elementAt(i, 0)->addWidget(new Wt::WText(this->response[i][0].as_string()));
table->elementAt(i, 1)->addWidget(new Wt::WText(this->response[i][1].as_string()));
table->elementAt(i, 2)->addWidget(new Wt::WText(this->response[i][2].as_string()));
table->elementAt(i, 3)->addWidget(new Wt::WText(this->response[i][3].as_string()));
}
But it fails. What am I missing ?
Pardon me, I am new to this REST and Casablanca and JSON
From JSON point of view the following
{
"11002":{"quantity":11002,"totalcost":"272","username":"arunavk"},
"11003":{"quantity":11003,"totalcost":"18700","username":"arunavk"},
"11004":{"quantity":11004,"totalcost":"760","username":"arunavk"},
"11005":{"quantity":11005,"totalcost":"32","username":"arunavk"}
}
is java script object with properties "11002", ... "11005", is not array. So if you want to get value of property you have to use property name:
this->response["11002"]["quantity"]
because when you use integer index the json::value::operator [] supposes that you want to access the array element. Here is details https://microsoft.github.io/cpprestsdk/classweb_1_1json_1_1value.html#a56c751a1c22d14b85b7f41a724100e22
UPDATED
If you do not know properties of the recieved object, you can call the value::as_object method (https://microsoft.github.io/cpprestsdk/classweb_1_1json_1_1value.html#a732030bdee11c2f054299a0fb148df0e) to get JSON object and after that you can use specilized interface to iterate through the fields with begin and end iterators: https://microsoft.github.io/cpprestsdk/classweb_1_1json_1_1object.html#details

How to return an JSON object I made in a reduce function

I need your help about CouchDB reduce function.
I have some docs like:
{'about':'1', 'foo':'a1','bar':'qwe'}
{'about':'1', 'foo':'a1','bar':'rty'}
{'about':'1', 'foo':'a2','bar':'uio'}
{'about':'1', 'foo':'a1','bar':'iop'}
{'about':'2', 'foo':'b1','bar':'qsd'}
{'about':'2', 'foo':'b1','bar':'fgh'}
{'about':'3', 'foo':'c1','bar':'wxc'}
{'about':'3', 'foo':'c2','bar':'vbn'}
As you can seen they all have the same key, just the values are differents.
My purpse is to use a Map/Reduce and my return expectation would be:
'rows':[ 'keys':'1','value':{'1':{'foo':'a1', 'at':'rty'},
'2':{'foo':'a2', 'at':'uio'},
'3':{'foo':'a1', 'at':'iop'}}
'keys':'1','value':{'foo':'a1', 'bar','rty'}
...
'keys':'3','value':{'foo':'c2', 'bar',vbn'}
]
Here is the result of my Map function:
'rows':[ 'keys':'1','value':{'foo':'a1', 'bar','qwe'}
'keys':'1','value':{'foo':'a1', 'bar','rty'}
...
'keys':'3','value':{'foo':'c2', 'bar',vbn'}
]
But my Reduce function isn't working:
function(keys,values,rereduce){
var res= {};
var lastCheck = values[0];
for(i=0; i<values.length;++i)
{
value = values[i];
if (lastCheck.foo != value.foo)
{
res.append({'change':[i:lastCheck]});
}
lastCheck = value;
}
return res;
}
Is it possible to have what I expect or I need to use an other way ?
You should not do this in the reduce function. As the couchdb wiki explains:-
If you are building a composite return structure in your reduce, or only transforming the values field, rather than summarizing it, you might be misusing this feature.
There are two approaches that you can take instead
Transform the results at your application layer.
Use the list function.
Lists functions are simple. I will try to explain them here:
Lists like views are saved in design documents under the key lists. Like so:
"lists":{
"formatResults" : "function(head,req) {....}"
}
To call the list function you use a url like this
http://localhost:5984/your-database/_design/your-designdoc/_list/your-list-function/your-view-name
Here is an example of list function
function(head, req) {
var row = getRow();
if (!row){
return 'no ingredients'
}
var jsonOb = {};
while(row=getRow()){
//construct the json object here
}
return {"body":jsonOb,"headers":{"Content-Type" : "application/json"}};
}
The getRow function is of interest to us. It contains the result of the view. So we can query it like
row.key for key
row.value for value
All you have to do now is construct the json like you want and then send it.
By the way you can use log
to debug your functions.
I hope this helps a little.
Apparently now you need to use
provides('json', function() { ... });
As in:
Simplify Couchdb JSON response

Get Returned text from ScriptManager(javascript) - INDESIGN SDK Plugin

I am using javascript inside my Plugin for Indesign CS6.
It is working fine.
But I need the return value from my javascript code now inside my c++ code.
I am using this site as reference:
https://blogs.adobe.com/indesignsdk/running-a-script-from-an-indesign- plug-in/
I need something like that:
scriptRunner->RunScript("function xpto(){return 'Hello World';};xpto()", params);
// fake method
const char *string_return = scriptRunner->getReturnCode();
are there something like that on scriptManager?
ps: it is not a indesign server. I put this tag because this site do not let me create a new tag...
Best Regards,
Use RunScriptParams::QueryScriptRequestData() .
From the SDK documents:
Query the IScriptRequestData that is used to pass arguments and return
the result.
The key is to get the iScript object from the 'RunScriptParams' object after the script has run. Then is it straight forward. Here is some sample code:
RunScriptParams params(scriptRunner);
IScriptRequestData* requestData = params.QueryScriptRequestData();
params.SetUndoMode(RunScriptParams::kFastUndoEntireScript);
if (scriptRunner->RunScript(script,params) != kSuccess) return NULL;
IScript *iScript = params.QueryTarget();
int resultsCount = requestData->GetNumReturnData(iScript);
PMString resultString;
if (resultsCount > 0) {
ScriptReturnData resultOne = requestData->GetNthReturnData(iScript,0);
ScriptData scriptReturnOne = resultOne.GetReturnValue();
scriptReturnOne.GetPMString(resultString);
}
The return value is in resultString.