cannot convert 'const wchar_t*' to 'LPCSTR' {aka 'const char*'} - wchar-t

Please help me with this code, I don't know how to change it so I can fix it and run it
std::wstring stemp = std::wstring(filename.begin(), filename.end());
hBitmapG = (HBITMAP)LoadImage(GetModuleHandle(NULL), stemp.c_str(), IMAGE_BITMAP,
0, 0, LR_LOADFROMFILE);
if (!hBitmapG) {
DWORD err = GetLastError();
std::wstring errorMsg = L"Failed to LoadImage - '" + stemp + L"', error code (" + std::to_wstring((long long)err) + L")";
MessageBox(NULL, errorMsg.c_str(), L"WinCanvas::DrawBitmap()", MB_OK);
PostMessage(hWnd, WM_DESTROY, NULL, NULL); // Post a message to destroy (shutdown) the program
return FALSE;
}

You can use MessageBoxW function to use wide characters in MessageBox.

Related

Protractor need to break from For LOOP when if is executed

Can anyone Please Help me in this in the below code, my requirement is once If is true, I should come out from For loop
===================================================
for (i = 0; i < 50; i++) {
element(By.xpath("//*[text() = '" + InvoiceREFnumberCompany + "']")).isPresent().then(function(result) {
if (result )
{
element(By.xpath("//*[text() = '" + InvoiceREFnumberCompany + "']")).click();
break;
}
else
{
obj1.ClickOnRefreshButton.click();
}
});
}
Output
Failures:
NPOInvoice-Fire -- NPO Fire Collabrate with PTC user
Message:
[31m Failed: Illegal break statement[0m
Stack:
SyntaxError: Illegal break statement

CFileDialog constructor can't spot TRUE and fopen(str,"r") error

I call the CFileDialog constructor in the following method:
CFileDialog FileDlg(TRUE, ".txt", NULL, 0, strFilter);
according to the parameters in the CFileDialog constructor, the first parameter should be BOOL, but my compiler thinks it's int instead of BOOL. Can you tell me why?
Besides, in the code, when I use fopen(str,"r"), the error is no conversion function from CSring to const char*. Appreciate your discussion.
The code is:
void OnFileOpen()
{
CClientDC dc(this);
CString str;
CRect rc;
FILE *ifp;
char strFilter[] = { "TXT Files (*.txt)|*.txt|All Files(*.*)|*.*||" };
CFileDialog FileDlg(TRUE, ".txt", NULL, 0, strFilter);
if (FileDlg.DoModal() == IDOK)
{
str = FileDlg.GetFileName();
ifp = fopen(str,"r");
dc.TextOutW(350, 50, "File Opened: " + str);
for (int i = 1; i < n; i++)
{
fscanf(ifp, "%d %d", &pt[i].x, &pt[i].y);
rc = CRect(pt[i].x - 30, pt[i].y - 30, pt[i].x + 30, pt[i].y + 30);
dc.Ellipse(rc);
rc = CRect(pt[i].x - 1, pt[i].y - 1, pt[i].x + 1, pt[i].y + 1);
dc.Rectangle(rc);
}
fclose(ifp);
}
}

https://api.twitter.com/oauth/request_token Fails in Blackberry Native SDK

I am trying to connect to Twitter though oAuth.I am making a POST request to the API https://api.twitter.com/oauth/request_token.
Here is is example of my Base signature string
POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Fapi.ec2.phunware.com%252Fapi%252Ftwitter%26oauth_consumer_key%3D6jq5dNZcccoPbApAJ0sOaA%26oauth_nonce%3DN2ZiMjViYzhlMDUxNDIyZWIwYjQ4NmU0ZjM1MDg4NTY%3D%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1362843354%26oauth_version%3D1.0
I used the tool http://quonos.nl/oauthTester/ to verify my base signature.
Here is the corresponding header
OAuth oauth_callback="http%3A%2F%2Fapi.ec2.phunware.com%2Fapi%2Ftwitter",oauth_consumer_key="6jq5dNZcccoPbApAJ0sOaA",oauth_nonce="N2ZiMjViYzhlMDUxNDIyZWIwYjQ4NmU0ZjM1MDg4NTY=",oauth_signature_method="HMAC-SHA1",oauth_signature="7ney2RxElbHUl2t1Jnz57pQpmFs%3D",oauth_timestamp="1362843354",oauth_version="1.0"
I tried the following command in my MAC terminal
curl --request 'POST' 'https://api.twitter.com/oauth/request_token' --header 'Authorization: OAuth oauth_callback="http%3A%2F%2Fapi.ec2.phunware.com%2Fapi%2Ftwitter",oauth_consumer_key="6jq5dNZcccoPbApAJ0sOaA",oauth_nonce="N2ZiMjViYzhlMDUxNDIyZWIwYjQ4NmU0ZjM1MDg4NTY=",oauth_signature_method="HMAC-SHA1",oauth_signature="7ney2RxElbHUl2t1Jnz57pQpmFs%3D",oauth_timestamp="1362843354",oauth_version="1.0"' --verbose
And i get 401 unauthorized error. I tried to set the oauth_callback ="oob" but I still get the same error.
Please help. I am using Blackberry Native SDK to code. I am pasting the code here. I get 204 error when I try via Blackberry 10.1 Simulator.
QByteArray Twitter::generateTimeStamp()
{
QDateTime current = QDateTime::currentDateTime();
uint seconds = current.toTime_t();
return QString::number(seconds,10).toUtf8();
}
QByteArray Twitter::generateNonce()
{
QString nonce = QUuid::createUuid().toString();
nonce.remove(QRegExp("[^a-zA-Z\\d\\s]"));
qDebug()<< nonce.toUtf8();
return nonce.toUtf8().toBase64();
}
QByteArray Twitter::generateSignatureBase(const QUrl& url, HttpMethod method, const QByteArray& timestamp, const QByteArray& nonce,bool addCallbackURL)
{
QList<QPair<QByteArray, QByteArray> > urlParameters = url.encodedQueryItems();
QList<QByteArray> normParameters;
QListIterator<QPair<QByteArray, QByteArray> > i(urlParameters);
while(i.hasNext()){
QPair<QByteArray, QByteArray> queryItem = i.next();
QByteArray normItem = queryItem.first + '=' + queryItem.second;
normParameters.append(normItem);
}
//consumer key
normParameters.append(QByteArray("oauth_consumer_key=") + consumer->consumerKey());
//token
if(accessToken != NULL){
normParameters.append(QByteArray("oauth_token=") + accessToken->oauthToken());
}
//signature method, only HMAC_SHA1
normParameters.append(QByteArray("oauth_signature_method=HMAC-SHA1"));
//time stamp
normParameters.append(QByteArray("oauth_timestamp=") + timestamp);
//nonce
normParameters.append(QByteArray("oauth_nonce=") + nonce);
//version
normParameters.append(QByteArray("oauth_version=1.0"));
//callback url
if(addCallbackURL)
normParameters.append(QByteArray("oauth_callback=") + QByteArray(CALLBACK_URL).toPercentEncoding());
//OAuth spec. 9.1.1.1
qSort(normParameters);
qDebug()<<normParameters;
QByteArray normString;
QListIterator<QByteArray> j(normParameters);
while (j.hasNext()) {
normString += j.next().toPercentEncoding();
normString += "%26";
}
normString.chop(3);
qDebug()<<normString;
//OAuth spec. 9.1.2
QString urlScheme = url.scheme();
QString urlPath = url.path();
QString urlHost = url.host();
QByteArray normUrl = urlScheme.toUtf8() + "://" + urlHost.toUtf8() + urlPath.toUtf8();
QByteArray httpm;
switch (method)
{
case GET:
httpm = "GET";
break;
case POST:
httpm = "POST";
break;
case DELETE:
httpm = "DELETE";
break;
case PUT:
httpm = "PUT";
break;
}
qDebug()<<"signature base="<<httpm + '&' + normUrl.toPercentEncoding() + '&' + normString;
//OAuth spec. 9.1.3
return httpm + '&' + normUrl.toPercentEncoding() + '&' + normString;
}
QByteArray Twitter::generateAuthorizationHeader( const QUrl& url, HttpMethod method,bool addCallbackURL )
{
QByteArray timeStamp = generateTimeStamp();
QByteArray nonce = generateNonce();
QByteArray baseString = generateSignatureBase(url, method, timeStamp, nonce,addCallbackURL);
QByteArray key = consumer->consumerSecret() + '&';
if(accessToken != NULL)
key = key + accessToken->oauthTokenSecret();
QByteArray signature = HMACSH1::hmacSha1(key,baseString).toPercentEncoding();
QByteArray header;
header += "OAuth ";
if(addCallbackURL)
header += "oauth_callback=\"" + QByteArray(CALLBACK_URL).toPercentEncoding() + "\",";
header += "oauth_consumer_key=\"" + consumer->consumerKey() + "\",";
header += "oauth_nonce=\"" + nonce + "\",";
header += "oauth_signature_method=\"HMAC-SHA1\",";
header += "oauth_signature=\"" + signature + "\",";
header += "oauth_timestamp=\"" + timeStamp + "\",";
if(accessToken != NULL)
header += "oauth_token=\"" + accessToken->oauthToken() + "\",";
header += "oauth_version=\"1.0\"";
qDebug()<<"header =" <<header;
return header;
}
void Twitter::requestForToken()
{
QUrl url(TWITTER_REQUEST_TOKEN_URL);
QByteArray oauthHeader = generateAuthorizationHeader(url, POST,true);
QNetworkRequest req(url);
req.setRawHeader("Authorization", oauthHeader);
req.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
req.setHeader(QNetworkRequest::ContentLengthHeader,"0");
QNetworkReply *reply = networkAccessManager->post(req, QByteArray());
connect(networkAccessManager, SIGNAL(finished ( QNetworkReply*)), this, SLOT(tokenFetchSuccessfull(QNetworkReply*)));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(tokenFetchFailed(QNetworkReply::NetworkError)));
qDebug()<<"Request For Token";
}
You mentioned you are using the Native SDK, are you also using Cascades? If so, you may have better luck using the bb-cascades-oauth library from GitHub. It has built in support for OAuth1 and OAuth2.
Also, it seems that having incorrect timestamps can be a common problem, based on the tips found here, so make sure that your simulator has the correct date and time.
Another developer here found that the http://quonos.nl/oauthTester/ was requiring a double escaped header which was incorrect, and causing 401 errors when making an actual authentication request. I noticed you used the same tester, and also have the double escaping in your base signature string above, so you might want to try without the double escaping.

Binary File Download using socket connection in Java ME

I am trying to download a pdf file on my mobile (using Java ME) using SocketConnection Api. The idea is to send the server a HTTP GET request, and it replies back with the data for pdf file. However, the problem I am facing is that the server initially replies back with string data (the HTTP Headers), and then the binary data. I just want to store the binary data (the pdf file).
I have written this code so far, and it works perfectly fine as far as the server replies back with string data. However, when it replies back with binary data, this code still tries to store everything as string, correctly storing the initially returned HTTP Headers (not required) and then garbled bits corresponding to the binary data of my PDF file.
public void FileDownload() {
try {
sc = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
OutputStream os = sc.openOutputStream();
os.write(("GET " + link_to_file_to_be_downloaded + " HTTP/1.0\r\n").getBytes("UTF-8"));
os.write(("HOST: " + hostname + "\r\n").getBytes("UTF-8"));
os.write(("\r\n").getBytes("UTF-8"));
os.flush();
os.close();
String url = "file:///E:/Data/" + "binary_data.pdf";
FileConnection fconn = (FileConnection) Connector.open(url, Connector.READ_WRITE);
if (!fconn.exists()) {
fconn.create();
}
OutputStream ops = fconn.openOutputStream();
byte data = 0;
in = sc.openInputStream();
data = (byte) in.read();
while (data != -1) {
ops.write(data);
data = (byte) in.read();
}
ops.flush();
ops.close();
fconn.close();
} catch (IOException ex) {
parent_class.main_form.append("Exception occured while "
+ "downloading file: " + ex.toString() + "\n");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
parent_class.main_form.append("Exception occured while "
+ "downloading file: " + ex.toString() + "\n");
}
}
}
}
This is what gets stored in the file "binary_data.pdf" using this code -
HTTP/1.1 200 OK
Date: Sun, 25 Mar 2012 07:03:10 GMT
Server: Apache/2.2.14 (Ubuntu)
Last-Modified: Tue, 20 Mar 2012 22:00:45 GMT
ETag: "420050-12bad-4bbb3ce85fd21"
Accept-Ranges: bytes
Content-Length: 76717
Content-Type: application/pdf
Via: 1.0 www.XXX.XXX.org
Connection: close
%PDF-1.4
%????
3 0 obj <<
/Length 4077
/Filter /FlateDecode
>>
stream
x??ZYs?6~????9U.?#??Udg?M*qYJ???T-4?fq? #Z????<FT?}
lt7??n???_???4?s???????"
3????<???^?V?z??M?z??m?^????V???o??S'm6?????.??/Sx??Y?av?MB?*b^?f??/?IO??B??q??/?(??aT?a?##??,?%???Z8? ?]??-?\?]??????nw?2?;?????Z?;?[}??????&J=ml??-??V?|??:??"?(?Gf??D??~?QW?U?Z???cP?b???QX
(This operation might be simpler using the high level HttpConnection api, but I wish to understand how everything works at the most basic level, and hence I am using the SocketConnection api instead.)
In short, what I wish my app to do is simply interpret the data replied by the server correctly, either as string or binary, and then accordingly store the binary file (possibly discarding the string HTTP headers).
I found the solution. Below is the working code.
I am first storing the header response as a string. Headers are terminated by \r\n\r\n, (so, read in bytes upto these characters). Later am storing the (possibly) binary data in a file separately.
public String FileDownloadNonPersistently() {
String server_reply = new String();
try {
sc = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
os = sc.openOutputStream();
os.write(("GET " + link_to_file_to_be_downloaded +
" HTTP/1.0\r\n").getBytes("UTF-8"));
os.write(("HOST: " + hostname + "\r\n").getBytes("UTF-8"));
os.write(("\r\n").getBytes("UTF-8"));
os.flush();
os.close();
in = sc.openInputStream();
// 1. Read the response header from server separately beforehand.
byte data;
String temp_char = "";
while (!"\r\n\r\n".equals(temp_char)) {
data = (byte) in.read();
server_reply += String.valueOf((char) data);
if (((char) data) == '\r' || ((char) data) == '\n') {
temp_char += String.valueOf((char) data);
} else {
temp_char = "";
}
}
// 2. Recieving the actual data, be it text or binary
current = 0;
mybytearray = new byte[filesize];
bytesRead = in.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead = in.read(mybytearray, current,
(mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
// Store recieved data to file, if set true from options
if (tcp_save_downloaded_file == true) {
// decide an appropriate file name acc. to download link
String url = "file:///E:/Data/" + "tcp_downloaded_file.pdf";
FileConnection fconn = (FileConnection)
Connector.open(url, Connector.READ_WRITE);
if (!fconn.exists()) { // XXX. what if file already present? overwrite or append mode?
fconn.create();
}
OutputStream ops = fconn.openOutputStream();
ops.write(mybytearray, 0 , current);
ops.flush();
ops.close();
}
} catch (Exception ex) {
parent_class.main_form.append("Exception occured while "
+ "downloading file: " + ex.toString() + "\n\n");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
parent_class.main_form.append("Exception occured while "
+ "closing inputstream "
+ "after downloading file: " + ex.toString() + "\n\n");
}
}
// XXX. see if you need to close the OutputStreams and
// SocketConnection as well.
return server_reply;
}
}
The first 10 lines are the HTTP message headers. For more information on them please go to https://www.rfc-editor.org/rfc/rfc2616#page-31.
The blank line identifies where the body starts.
You can start saving the pdf content from line 12 onwards, but you should do it using a different read method.
Instead of
data = (byte) in.read();
while (data != -1) {
ops.write(data);
data = (byte) in.read();
}
please try
byte buff[] = new byte[1024];
int len = in.read(buff);
while (len > 0) {
ops.write(buff, 0, len);
len = in.read(buff);
}

LSP packet modify

anybody care to share some insights on how to use LSP for packet modifying ?
I am using the non IFS subtype and I can see how (pseudo?) packets first enter WSPRecv. But how do I modify them ? My inquiry is about one single HTTP response that causes WSPRecv to be called 3 times :((. I need to modify several parts of this response, but since it comes in 3 slices, it is pretty hard to modify it accordingly. And, maybe on other machines or under different conditions (such as high traffic) there would only be one sole WSPRecv call, or maybe 10 calls. What is the best way to work arround this (please no NDIS :D), and how to properly change the buffer (lpBuffers->buf) by increasing it ?
int WSPAPI
WSPRecv(
SOCKET s,
LPWSABUF lpBuffers,
DWORD dwBufferCount,
LPDWORD lpNumberOfBytesRecvd,
LPDWORD lpFlags,
LPWSAOVERLAPPED lpOverlapped,
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
LPWSATHREADID lpThreadId,
LPINT lpErrno
)
{
LPWSAOVERLAPPEDPLUS ProviderOverlapped = NULL;
SOCK_INFO *SocketContext = NULL;
int ret = SOCKET_ERROR;
*lpErrno = NO_ERROR;
//
// Find our provider socket corresponding to this one
//
SocketContext = FindAndRefSocketContext(s, lpErrno);
if ( NULL == SocketContext )
{
dbgprint( "WSPRecv: FindAndRefSocketContext failed!" );
goto cleanup;
}
//
// Check for overlapped I/O
//
if ( NULL != lpOverlapped )
{
/*bla bla .. not interesting in my case*/
}
else
{
ASSERT( SocketContext->Provider->NextProcTable.lpWSPRecv );
SetBlockingProvider(SocketContext->Provider);
ret = SocketContext->Provider->NextProcTable.lpWSPRecv(
SocketContext->ProviderSocket,
lpBuffers,
dwBufferCount,
lpNumberOfBytesRecvd,
lpFlags,
lpOverlapped,
lpCompletionRoutine,
lpThreadId,
lpErrno);
SetBlockingProvider(NULL);
//is this the place to modify packet length and contents ?
if (strstr(lpBuffers->buf, "var mapObj = null;"))
{
int nLen = strlen(lpBuffers->buf) + 200;
/*CHAR *szNewBuf = new CHAR[];
CHAR *pIndex;
pIndex = strstr(lpBuffers->buf, "var mapObj = null;");
nLen = strlen(strncpy(szNewBuf, lpBuffers->buf, (pIndex - lpBuffers->buf) * sizeof (CHAR)));
nLen = strlen(strncpy(szNewBuf + nLen * sizeof(CHAR), "var com = null;\r\n", 17 * sizeof(CHAR)));
pIndex += 18 * sizeof(CHAR);
nLen = strlen(strncpy(szNewBuf + nLen * sizeof(CHAR), pIndex, 1330 * sizeof (CHAR)));
nLen = strlen(strncpy(szNewBuf + nLen * sizeof(CHAR), "if (com == null)\r\n" \
"com = new ActiveXObject(\"InterCommJS.Gateway\");\r\n" \
"com.lat = latitude;\r\n" \
"com.lon = longitude;\r\n}", 111 * sizeof (CHAR)));
pIndex = strstr(szNewBuf, "Content-Length:");
pIndex += 16 * sizeof(CHAR);
strncpy(pIndex, "1465", 4 * sizeof(CHAR));
lpBuffers->buf = szNewBuf;
lpBuffers->len += 128;*/
}
if ( SOCKET_ERROR != ret )
{
SocketContext->BytesRecv += *lpNumberOfBytesRecvd;
}
}
cleanup:
if ( NULL != SocketContext )
DerefSocketContext( SocketContext, lpErrno );
return ret;
}
Thank you
my comment worked out. http response headers / request turned out to end in \r\n\r\n.