backendError 500 (Bug in nextPageToken) - google-drive-api

For some of the users iterating through the list of files started producing error 500 (backendError). Very few cases, but still.
Close investigation showed that sometimes after requesting a list of files strange nextPageToken was returned. Here is an example:
!!|~EAIaggELEgA6egpg96K5Moz_____f_8AAP__AAD_7qNsfh7Iy8rJyMnDy8bLytHI0bDOy6W4rZ6wvqmc_wAA__8A_v_-f_8A_wDuo2x-HsjLysnIyc7LxsvK0cjRsM7LpbitnrC-qZz_AP_-EJzHASFVhA7Kvoa7STkAAAAAc81GXUgBDEAAIgsJ4YZTXBEABAAgBg
This part right here "!!|~" (start of the string) was causing the errors. Removing it fixed the issue.
There were not so many cases. But still, can this be a bug?
UPDATE 1.
Here is a code sample using Google APIs Client Library for PHP. But the error reproduced only for few users. So there are not a lot of chances of reproducing it.
$client = new Google_Client( );
// ... setup client
$driveService = new Google_DriveService( $client );
$parameters = array();
try{
do{
$files = $driveService->files->listFiles( $parameters );
$parameters['pageToken'] = $files->nextPageToken;
// ...
} while( $parameters['pageToken'] );
}
catch( Google_ServiceException $exception ) {
// ... handle exception
}
}

Related

How to do a while loop for a MySQL query in Node.js?

I am currently trying to transform a php code into Node.js using Typescript & Express.
In a script, I am generating a random 6-digit code before querying the database to verify that the code doesn't exist, otherwise I generate a new one.
Here's the original PHP code :
$code = generate_random_int(); // Generate a random code
$existing_codes = exec_sql($db,"SELECT code FROM codes WHERE code = $code;"); // Check if the generated code already exists in the database
while(!empty($existing_codes)){ // While there is (at least) 1 occurence in the DB for the generated code
$code = generate_random_int(); // Generate a new random code
$existing_codes = exec_sql($db,"SELECT code FROM codes WHERE code = $code;"); // Update the check for the newly generated code.
// If an occurence is found, the while loop will be reiterated. Otherwise, the while loop will end with the last generated code.
}
However, Node.js MySQL library only allows callbacks, because the function is asynchronous, which prevent the behavior I've illustrated above.
I have looked here and there on the internet and haven't found any way to reproduce this behavior in Node.js, so that's why I'm writing here :)
I thought about using for loops with db.query calls in them with no success, same with while syntaxes and an updated boolean.
Here's my latest (unsuccessful) attempt :
let code = generateRandomInt()
// query is a simplified function for db.query() from MySQL
query(`SELECT code FROM codes WHERE code = ${code};`, result => {
if (result === []) {
res.send(String(code))
return
} else {
code = generateRandomInt()
// While loop creating a new SQL statement for the new code and regenerating it until the response is []
}
})
res.send(String(code))
Thanks a lot by advance for your help :)
PS : I'm a newbie to Express and I am not that used to post on StackOverflow, so please don't hesitate to tell me if I did something wrong or if you need any complementary information
Here is another approach. Once you have an array of existing codes, use a loop to find an unused one:
...
const go = async () => {
const existingCodes = await getExistingCodes(); // your function that returns a list
// of existing codes; return a Promise
// find an unused code
let code = generateRandomInt();
while (existingCodes.indexOf(code) !== -1) {
code = generateRandomInt();
}
// use your new code
console.log(`new code is: ${code}`);
};
go();

How to send parameter with try catch exception in yii2?

I have problem in sending email, looks like our server connection to mail server is unstable, sometimes it successfully sent, but sometimes it's not, it say ssl time out.
So my idea is catch timed out exception and insert in database then I can send later.
But I need to send few parameter with catch exception so I can insert database correctly.
So far what I want is something like this
try{
$message = Yii::$app->mail->compose();
if (Yii::$app->user->isGuest) {
$message->setFrom('from#domain.com');
} else {
$message->setFrom(Yii::$app->user->identity->email);
}
$message->setTo(Yii::$app->params['adminEmail'])
->setFrom(Yii::$app->params['adminEmail'])
->setTo("mymail#gmail.com")
->setSubject('Title 1')
->setHtmlBody("Hi, this is my content to check if registration email successfully sent")
->send();
$mail_from = "no-reply#myweb.com";
$mail_to = "customer#someweb.com";
$content = "here is content of email"
$other = "this other variable";
return 1;
}catch(\Swift_TransportException $e, $mail_from, $mail_to, $content, $other){
//if connection time out or something
$queue = new Queue;
$queue->mail_from = $mail_from;
$queue->mail_to = $mail_to;
$queue->content = $content;
$queue->other = $other;
$queue->fail_reason = $e->getMessage();
$queue->save()
}
but it give me undefined variable $mail_from, $mail_to, and etc
How I can fix my problem?
Thanks in advance.
To fix the undefined variable $mail_from, $mail_to, and etc error it's better to declare the variables outside the try block. Because you're declaring the variables at the end of the try, it fails before these variables are ever initialised.
$mail_from = "no-reply#myweb.com";
$mail_to = "customer#someweb.com";
$content = "here is content of email"
$other = "this other variable";
try {
$message = Yii::$app->mail->compose();
if (Yii::$app->user->isGuest) {
$message->setFrom('from#domain.com');
} else {
$message->setFrom(Yii::$app->user->identity->email);
}
$message->setTo(Yii::$app->params['adminEmail'])
->setFrom(Yii::$app->params['adminEmail'])
->setTo("mymail#gmail.com")
->setSubject('Title 1')
->setHtmlBody("Hi, this is my content to check if registration email successfully sent")
->send();
return 1;
} catch(\Swift_TransportException $e) {
//if connection time out or something
$queue = new Queue;
$queue->mail_from = $mail_from;
$queue->mail_to = $mail_to;
$queue->content = $content;
$queue->other = $other;
$queue->fail_reason = $e->getMessage();
$queue->save()
}
But there are more problems with this code. You're setting the from and to part multiple times. In the if/else you're calling setFrom and then again a few lines later. The same goes for setTo. The last call to the function will overrule the previous set value. So make sure you only call these functions once.

Reading a project text file windows phone 8

I'm having trouble accessing a text file that is packaged with my Windows Phone 8 app.
Here is the code:
var ResrouceStream = Application.GetResourceStream(new Uri("Data-Test.docx", UriKind.Relative));
if (ResrouceStream != null)
{
Stream myFileStream = ResrouceStream.Stream;
if (myFileStream.CanRead)
{
// logiic here
retrun "Hi";
}
}
else
{
return "hello";
}
Seems simple but the app always returns "hello". i have placed the file in root and also in assets, changed it to content - copy and do not copy, resource copy and do not copy but always it returns "hello".
Spent several hours on this and all solutions I can find show the solution or very similar above!
What am I doing wrong?
EDIT: Returns "hello" when I deploy to phone or emulator.
also tried "/Data-Test...", #"\Data-Text..., #/"Data-Test...!
UPDATE 1:
string aReturn = "";
var asm = Assembly.GetExecutingAssembly();
//Use this to verify the namespacing of the "Embedded Resource".
//asm.GetManifestResourceNames()
// .ToList()
// .ForEach(name => Debug.WriteLine(name));
var ResourceStream = asm.GetManifestResourceStream("ContosoSocial.Assets.QuizQuestions.QuizQuestions-Test1.docx");
if (ResourceStream != null) // <--CHECKED AND DOES NOT EQUAL NULL
{
Stream myFileStream = ResourceStream;
if (myFileStream.CanRead) // <-- CHEACKED AND CAN READ
{
StreamReader myStreamReader = new StreamReader(myFileStream);
LOGIC & EXCEPTION HERE...?
string myLine = myStreamReader.ReadLine();
}
else
{
aReturn = "myFileStream.CanRead = true";
}
}
else
{
aReturn = "stream equals null";
}
Debug.WriteLine(aReturn);
}
The assignment of myFileStream to a StreamReader object is throwing the exception null pointer. I thought I would wrap myFileStream to a StreamReader so I can read a line at a time..? This is my first c# project and I'm unfamiliar with it's syntax and classes.
UPDATE 2:
OK I added...
Debug.WriteLine(aReturn);
...following...
string myLine = myStreamReader.ReadLine();
...and noticed it was retrieving only the 2 characters 'PK' !
So saved the .docx file as .txt and reinserted adn changed build copy to embedded - do not copy...Happy days it now pulls off the first line in the file.
Thanks to OmegaMan for your help with this one :-)
Change file type in the project to Embedded Resource
Extract the resource by working the namespace to its location. Here is an example code where I pull in an XSD:
Code:
var asm = Assembly.GetExecutingAssembly();
// Use this to verify the namespacing of the "Embedded Resource".
// asm.GetManifestResourceNames()
// .ToList()
// .ForEach(name => Debug.WriteLine(name));
var f1 = asm.GetManifestResourceStream("UnitTests.Resources.NexusResponse.xsd");
Note this is not tested on WP8, but GetExecutingAssembly is stated to work within .Net. If you get the namespace wrong, uncomment out the code and display or debug to determine the resources and their namespace.

PHP-EWS No Data Received Message

I just downloaded PHP-EWS, installed following the README instructions, and spun up a script to test out its functionalities. When I try running the script in my browser, I get the following message:
I get the same message when I supply a login I know is invalid. It seems I am connecting to my Exchange server, but it's not recognizing the credentials I provide.
Here is the script I am using
<?php
function __autoload($className)
{
$className = str_replace('_','/', $className);
$sFileName = $className . '.php';
if (file_exists($sFileName) && !class_exists($className))
{
require_once $sFileName;
}
// If the above if fails, you're program will terminate, there is no way to catch this.
}
include("ExchangeWebServices.php");
$host = "https://myexchange/EWS/Services.wsdl";
$username = "myusername#mydomain.com";
$password = "mypassword";
$ews = new ExchangeWebServices($host, $username, $password);
$request = new EWSType_FindItemType();
$request->ItemShape = new EWSType_ItemResponseShapeType();
$request->ItemShape->BaseShape = EWSType_DefaultShapeNamesType::DEFAULT_PROPERTIES;
$request->Traversal = EWSType_ItemQueryTraversalType::SHALLOW;
$request->ParentFolderIds = new EWSType_NonEmptyArrayOfBaseFolderIdsType();
$request->ParentFolderIds->DistinguishedFolderId = new EWSType_DistinguishedFolderIdType();
$request->ParentFolderIds->DistinguishedFolderId->Id = EWSType_DistinguishedFolderIdNameType::INBOX;
// sort order
$request->SortOrder = new EWSType_NonEmptyArrayOfFieldOrdersType();
$request->SortOrder->FieldOrder = array();
$order = new EWSType_FieldOrderType();
// sorts mails so that oldest appear first
// more field uri definitions can be found from types.xsd (look for UnindexedFieldURIType)
$order->FieldURI->FieldURI = 'item:DateTimeReceived';
$order->Order = 'Ascending';
$request->SortOrder->FieldOrder[] = $order;
$response = $ews->FindItem($request);
echo '<pre>'.print_r($response, true).'</pre>';
?>
Try testing your access by:
Hitting the server url directly: https://YOUREXCHANGESERVER/EWS/Services.wsdl
You should be prompted for credentials. After you enter your credentials you will be presented with the WSDL definition. If it does not present you a WSDL definition that looks like the example below then check with your administrator on credentials or if there are any firewall blocks put in place.
Example (Partial response):
<wsdl:definitions targetNamespace="http://schemas.microsoft.com/exchange/services /2006/messages"><wsdl:types><xs:schema><xs:import namespace="http://schemas.microsoft.com/exchange/services/2006/messages" schemaLocation="messages.xsd"/></xs:schema></wsdl:types>
A great tool I use in analyzing web services is: SOAP-UI by SmartBear

Occasional (and recurrent) problems with FacebookMobile.init()

Seems this API is broken and/or abandoned because in some days, this API call always fails during a few hours. Today is happening again, but it's taking more time than previous times.
I don't know what to do. I have 2 Air apps and they aren't working today.
Any solution on this?
Here is a simple piece of code:
FacebookMobile.init(APP_ID, onInit);
private function onInit(fbSession:Object, fail:Object):void
{
if (fbSession){
trace(fbSession.accessToken);
}
else{
traceV2(fail); // it's a "deep" trace
// other API methods related to login
}
}
In FacebookMobile.init(), we have to expect for an session object (containing FB acess token), or a "fail" object.
The fail object is returning this to me:
[Object]
| [error:Object]
| code = 190
| message = Malformed access token AAAEWSUA8XjUBAJo4JuO5hUMwSnKC95LNRr1nHHIU8rwPGzxvHIuhUcDziZA9ZC3xDf4ZBwYcqjVU1ir5wf5jlEsJ5zwyMhnnWGyWxXeKQZDZD,AAAEWSUA8XjUBAJo4JuO5hUMwSnKC95LNRr1nHHIU8rwPGzxvHIuhUcDziZA9ZC3xDf4ZBwYcqjVU1ir5wf5jlEsJ5zwyMhnnWGyWxXeKQZDZD
| type = OAuthException
Thanks in advance!
Problem fixed.
The solution to this specific problem is at at com.facebook.graph.FacebookMobile:560, inside the handleLogin() function.
protected function handleLogin(result:Object, fail:Object):void {
loginWindow.loginCallback = null;
if (fail) {
loginCallback(null, fail);
return;
}
// ---------------||--------------------//
// ---------------\/--------------------//
// This line below solves this problem
result.access_token = String(result.access_token).split(',')[0];
// ---------------/\-------------------//
// ---------------||-------------------//
session = new FacebookSession();
session.accessToken = result.access_token;
session.expireDate = (result.expires_in == 0) ? null : FacebookDataUtils.stringToDate(result.expires_in) ;
if (_manageSession) {
var so:SharedObject = SharedObject.getLocal(SO_NAME);
so.data.accessToken = session.accessToken;
so.data.expireDate = session.expireDate;
so.flush();
}
verifyAccessToken();
}
Seems like its a bug with Facebook returning the Access token as an Array:
http://developers.facebook.com/bugs/276418065796236?browse=search_5034a345a2cb15e92344737
I would try edit the String that is returned by removing the second access token value in it. (Everything after the comma) and signing that to your local sessions access token variable. It might resolve the issue