I am trying to port cocos2dx application for Windows phone 8. I am trying to use iXMLHTTPRequest class to perform Network calls in C++.
I am trying to download zip file using this but dont know what and where I am doing wrong. Here is my code which I am using, Please help me to figure out the issue and what I should do to make it working.
void HTTPRequest::sendRequest(){
m_cancelHttpRequestSource = cancellation_token_source();
// Set up the GET request parameters.
std::string s_str = std::string(urlString);
std::wstring wid_str = std::wstring(s_str.begin(), s_str.end());
const wchar_t* w_char = wid_str.c_str();
auto uri = ref new Uri( ref new String(w_char));
String ^temp = uri->AbsoluteUri;
auto token = m_cancelHttpRequestSource.get_token();
// Send the request and then update the UI.
onHttpRequestCompleted(m_httpRequest.GetAsync(uri, token));
}
void HTTPRequest::onHttpRequestCompleted(concurrency::task httpRequest)
{
httpRequest.then([this](task previousTask)
{
try
{
wstring response = previousTask.get();
if (m_httpRequest.GetStatusCode() == 200)
{
size_t strSize;
FILE* fileHandle;
auto local = Windows::Storage::ApplicationData::Current->LocalFolder;
auto localFileNamePlatformString = local->Path + "\\test1.zip";
// Create an the xml file in text and Unicode encoding mode.
if ((fileHandle = _wfopen(localFileNamePlatformString->Data(), L"wb")) == NULL) // C4996
// Note: _wfopen is deprecated; consider using _wfopen_s instead
{
wprintf(L"_wfopen failed!\n");
return(0);
}
// Write a string into the file.
strSize = wcslen(response.c_str());
if (fwrite(response.c_str(), sizeof(wchar_t), strSize, fileHandle) != strSize)
{
wprintf(L"fwrite failed!\n");
}
// Close the file.
if (fclose(fileHandle))
{
wprintf(L"fclose failed!\n");
}
}
else
{
// The request failed. Show the status code and reason.
wstringstream ss;
ss << L"The server returned "
<< m_httpRequest.GetStatusCode()
<< L" ("
<< m_httpRequest.GetReasonPhrase()
<< L')';
//String ^responseText = ref new String(ss.str().c_str());
m_delegate->parserError(requestType->getCString(), "Print Status Code later");
}
}
catch (const task_canceled&)
{
// Indicate that the operation was canceled.
//String ^responseText = "The operation was canceled";
m_delegate->parserError(requestType->getCString(), "Operation has canceled");
}
catch (Exception^ e)
{
// Indicate that the operation failed.
//String ^responseText = "The operation failed";
m_delegate->parserError(requestType->getCString(), "The operation failed");
// TODO: Handle the error further.
(void)e;
}
}, task_continuation_context::use_current());
}
Related
When using the Alloy API to perform parsing on the following string:
Module mod = CompUtil.parseEverything_fromString("run {} for 5")
I receive the following error:
Fatal error:
Parser Exception
at edu.mit.csail.sdg.alloy4compiler.parser.CompParser.alloy_parseStream(CompParser.java:2260)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseRecursively(CompUtil.java:178)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseEverything_fromFile(CompUtil.java:280)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil.parseEverything_fromString(CompUtil.java:333)
at edu.mit.csail.sdg.alloy4compiler.parser.CompUtil$parseEverything_fromString.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:136)
at MyOM.MyOMPlugin.Modularize(MyOMPlugin.groovy:107)
...
--------------------------------------------------------------------------
class file:
package MyOM
class MyOMPlugin extends Plugin{
void Modularize() throws Err{
//line 107 is the only line in the method and is below
Module mod = CompUtil.parseEverything_fromString("run {} for 5")
}
}
I am performing this task in a groovy class file within a groovy project. The code works fine until I run it in conjunction with the plugin I am using.
EDIT:
The parse function is what causes the parse exception and the code for that method is included below for reference:
#Override public Symbol parse() throws java.lang.Exception {
int act; // current action code
Symbol lhs_sym = null; // the Symbol/stack element returned by a reduce
short handle_size, lhs_sym_num; // information about production being reduced with
boolean logging = "yes".equals(System.getProperty("debug"));
production_tab = production_table();
action_tab = action_table();
reduce_tab = reduce_table();
init_actions();
user_init();
// start
cur_token = scan();
stack.removeAllElements();
stack.push(getSymbolFactory().startSymbol("START", 0, start_state()));
tos = 0;
for (_done_parsing = false; !_done_parsing; ) {
act = get_action(((Symbol)stack.peek()).parse_state, cur_token.sym);
if (act > 0) { // "shift"; thus, we shift to the encoded state by pushing it on the stack
if (logging) System.out.println("shift " + cur_token.sym);
cur_token.parse_state = act-1;
stack.push(cur_token);
tos++;
cur_token = scan();
} else if (act<0) { // "reduce"
if (logging) System.out.println("reduce " + ((-act)-1));
lhs_sym = do_action((-act)-1, this, stack, tos);
lhs_sym_num = production_tab[(-act)-1][0];
handle_size = production_tab[(-act)-1][1];
for (int i = 0; i < handle_size; i++) { stack.pop(); tos--; }
act = get_reduce(((Symbol)stack.peek()).parse_state, lhs_sym_num);
lhs_sym.parse_state = act;
stack.push(lhs_sym);
tos++;
} else { // "error"
if (logging) System.out.println("error");
syntax_error(cur_token);
done_parsing();
}
}
return lhs_sym;
}
I am following this sample to implement a background server universal app. Here is the experimental code:
void MainPage::OnConnectionReceived(StreamSocketListener^ sender, StreamSocketListenerConnectionReceivedEventArgs^ args)
{
OutputDebugString(L"Connection received\n");
// No idea how to transfer request handling from foreground to background task!
}
void MainPage::OnNavigatedTo(NavigationEventArgs^ e)
{
// Code to register background task is omitted
auto listener = ref new StreamSocketListener();
listener->Control->QualityOfService = SocketQualityOfService::Normal;
try
{
listener->EnableTransferOwnership(Task->TaskId, SocketActivityConnectedStandbyAction::Wake);
}
catch (...)
{
OutputDebugString(L"Error: cannot transfer ownership\n");
}
listener->ConnectionReceived += ref new TypedEventHandler<StreamSocketListener^, StreamSocketListenerConnectionReceivedEventArgs^>(this, &MainPage::OnConnectionReceived);
create_task(listener->BindServiceNameAsync("56789", SocketProtectionLevel::PlainSocket))
.then([this]()
{
OutputDebugString(L"Server started on port 56789\n");
auto m_httpClient = ref new HttpClient();
auto request = ref new HttpRequestMessage(HttpMethod::Get, ref new Uri("http://" + ip + ":56789/"));
auto request_operation = m_httpClient->SendRequestAsync(request, HttpCompletionOption::ResponseContentRead);
return create_task(request_operation);
}).then([this](task<HttpResponseMessage^> previousTask)
{
try {
auto response = previousTask.get();
// Code to process the response is omitted as it is irrelevant to the question
}
catch (Exception^ ex)
{
OutputDebugString(("Error: " + ex->Message + "\n")->Data());
}
});
}
At run time, I get the error: The attempted operation is not supported for the type of object referenced. which suggests that BindServiceNameAsync fails and I have no idea why as I have followed the documentation to do EnableTransferOwnership before doing the binding. What did I do wrong here?
You are getting The attempted operation is not supported for the type of object referenced. because you are using SocketActivityConnectedStandbyAction::Wake. Change it to SocketActivityConnectedStandbyAction::DoNotWake.
The following pseudo-code should give you an idea what else you need to do to make StreamSocketListener working with SocketActivityTrigger:
// TODO: task = socketTaskBuilder.Register();
socketListener = new StreamSocketListener();
socketListener.ConnectionReceived += OnConnected;
await socketListener.BindServiceNameAsync(port);
socketListener.EnableTransferOwnership(
task.TaskId,
SocketActivityConnectedStandbyAction.DoNotWake);
// This is required, otherwise you may get error:
// A device attached to the system is not functioning.
// (Exception from HRESULT: 0x8007001F)
await socketListener.CancelIOAsync();
socketListener.TransferOwnership(socketId);
Then, in the background task do:
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
var details = taskInstance.TriggerDetails as
SocketActivityTriggerDetails;
var socketInformation = details.SocketInformation;
var streamSocket = socketInformation.StreamSocket;
var socketListener = socketInformation.StreamSocketListener;
switch (details.Reason)
{
case SocketActivityTriggerReason.ConnectionAccepted:
// TODO: read, write, etc.
break;
default:
// ...
break;
}
// ...
deferral.Complete();
}
Response of QNetworkReply::readAll is empty when QNetworkReply::error() != NoError.
Is this normal?
I've a Node+Express server that always send a detailed description in case of http status different of 200; I cant get this description from my Qt client base on QNAM. Qt version is 5.3, OS Win 7 64b.
This is my code, really I don't think this can help.
PendingRequest *Foo::sendMsg(QStandardItem *requestItem, HTTP_METHOD_ID method, QString path)
{
PendingRequest *pReq = new PendingRequest(method);
QString url = QString("https://%1:%2%3").arg(host, QString::number(port), path);
QNetworkRequest qNetReq = QNetworkRequest(QUrl(url));
//set headears
qNetReq.setHeader(QNetworkRequest::KnownHeaders::UserAgentHeader, HttpUserAgent);
qNetReq.setRawHeader("Connection", "Keep-Alive");
if(!credentials.isEmpty())
{
qNetReq.setRawHeader("Authorization", QByteArray("Basic ")+credentials);
}
if(!sessionId.isEmpty())
{
qNetReq.setRawHeader("Session-Id", sessionId);
}
//send request
QNetworkReply *reply;
if(method == HTTP_METHOD_ID::POST)
{
qNetReq.setHeader(QNetworkRequest::KnownHeaders::ContentTypeHeader, "application/json");
QByteArray data = outHandlerList[outHandlerIndex](requestItem);
reply = netManager.post(qNetReq, data);
}
else
{
reply = netManager.get(qNetReq);
}
connect(reply, SIGNAL(finished()), this, SLOT(handleResponse()));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(handleSslErrors(QList<QSslError>)));
return pReq;
}
and this where I handle response:
void Foo::handleResponse()
{
QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
if(reply->hasRawHeader("Session-Id"))
sessionId = reply->rawHeader("Session-Id");
PendingRequest *pReq = pendingRequestMap.contains(reply) ? pendingRequestMap.take(reply) : 0;
Q_ASSERT(pReq);
QStandardItem *responseItem = 0;
QString error;
if(reply->error() != QNetworkReply::NoError)
{
qDebug() << "readAll: ", reply->readAll(), "error: ", reply->errorString();
error = reply->errorString();
}
else
{
responseItem = inHandlerList[pReq->inHandlerIndex](reply, error, pReq);
}
reply->deleteLater();
}
Thanks a lot for your help.
From the documentation:
QByteArray QIODevice::readAll()
This is an overloaded function.
Reads all available data from the device, and returns it as a
QByteArray.
This function has no way of reporting errors; returning an empty
QByteArray() can mean either that no data was currently available for
reading, or that an error occurred.
I had the same problem, spent hours debugging and searching online for solutions...
The resolution is to connect QIODevice::readyRead to as per the documentation:
connect(reply, &QIODevice::readyRead, this, [=]() {
QByteArray response = reply->readAll();
qDebug() << response;
});
You now have the server reply regardless of the HTTP error code.
Im new with plugin. my problem is, When the case is created, i need to update the case id into ledger. What connect this two is the leadid. in my case i rename lead as outbound call.
this is my code. I dont know whether it is correct or not. Hope you guys can help me with this because it gives me error. I manage to register it. no problem to build and register but when the case is created, it gives me error.
using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Client;
using System.Net;
using System.Web.Services;
/*
* Purpose: 1) To update case number into lejar
*
* Triggered upon CREATE message by record in Case form.
*/
namespace UpdateLejar
{
public class UpdateLejar : IPlugin
{
/*public void printLogFile(String exMessage, String eventMessage, String pluginFile)
{
DateTime date = DateTime.Today;
String fileName = date.ToString("yyyyMdd");
String timestamp = DateTime.Now.ToString();
string path = #"C:\CRM Integration\PLUGIN\UpdateLejar\Log\" + fileName;
//open if file exist, check file..
if (File.Exists(path))
{
//if exist, append
using (StreamWriter sw = File.AppendText(path))
{
sw.Write(timestamp + " ");
sw.WriteLine(pluginFile + eventMessage + " event: " + exMessage);
sw.WriteLine();
}
}
else
{
//if no exist, create new file
using (StreamWriter sw = File.CreateText(path))
{
sw.Write(timestamp + " ");
sw.WriteLine(pluginFile + eventMessage + " event: " + exMessage);
sw.WriteLine();
}
}
}*/
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
//for update and create event
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity targetEntity = (Entity)context.InputParameters["Target"];
// Verify that the entity represents a connection.
if (targetEntity.LogicalName != "incident")
{
return;
}
else
{
try
{
//triggered upon create message
if (context.MessageName == "Create")
{
Guid recordid = new Guid(context.OutputParameters["incidentid"].ToString());
EntityReference app_inc_id = new EntityReference();
app_inc_id = targetEntity.GetAttributeValue<EntityReference>("new_outboundcalllid");
Entity member = service.Retrieve("new_lejer", ((EntityReference)targetEntity["new_outboundcallid"]).Id, new ColumnSet(true));
//DateTime createdon = targetEntity.GetAttributeValue<DateTime>("createdon");
if (app_inc_id != null)
{
if (targetEntity.Attributes.Contains("new_outboundcallid") == member.Attributes.Contains("new_outboundcalllistid_lejer"))
{
member["new_ringkasanlejarid"] = targetEntity.Attributes["incidentid"].ToString();
service.Update(member);
}
}
}
tracingService.Trace("Lejar updated.");
}
catch (FaultException<OrganizationServiceFault> ex)
{
//printLogFile(ex.Message, context.MessageName, "UpdateLejar plug-in. ");
throw new InvalidPluginExecutionException("An error occurred in UpdateLejar plug-in.", ex);
}
catch (Exception ex)
{
//printLogFile(ex.Message, context.MessageName, "UpdateLejar plug-in. ");
tracingService.Trace("UpdateLejar: {0}", ex.ToString());
throw;
}
}
}
}
}
}
Please check,
is that entity containing the attributes or not.
check it and try:
if (targetEntity.Contains("new_outboundcallid"))
((EntityReference)targetEntity["new_outboundcallid"]).Id
member["new_ringkasanlejarid"] = targetEntity.Attributes["incidentid"].ToString();
What is new_ringkasanlejarid's type? You're setting a string to it. If new_ringkasanlejarid is an entity reference, this might be causing problems.
You might want to share the error details or trace log, all we can do is assume what the problem is at the moment.
I have another question about a "JDWP Error: 21" logged: Unexpected JDWP Error 21
I am trying to parse some XML I gather from a servlet into a J2ME MIDlet with the code below. So far unsuccessfully, I think due to the JDWP error on my HttpConnection how ever the InputStream is filled with XML and once parsed everything inside the Document is null.
Has anyone got and ideas about the JDWP error, and also does that code look like it should work?
In MIDlet I am using JSR-172 API javax.xml.parsers.*.
if(d==form1 && c==okCommand)
{
// Display Webpage
webPage = new TextBox(txtField.getString(),
"",
100000,
TextField.ANY
);
Display.getDisplay(this).setCurrent(webPage);
try
{
HttpConnection conn = (HttpConnection)Connector.open("http://localhost:8080/Blogging_Home/Interface?Page=Bloggers&Action=VIEW&Type=XML");
conn.setRequestMethod(HttpConnection.GET);
int rc = conn.getResponseCode();
getConnectionInformation(conn, webPage);
webPage.setString(webPage.getString() + "Starting....");
String methodString = getStringFromURL("");
if (rc == HttpConnection.HTTP_OK)
{
InputStream is = null;
is = createInputStream(methodString);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document document;
try
{
builder = factory.newDocumentBuilder();
document = builder.parse(is);
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
webPage.setString(webPage.getString() + "ERROR:" + rc);
}
}
catch(Exception ex)
{
// Handle here
webPage.setString("Error" + ex.toString());
}