Google Drive: Xamarin - Android GetInputStream - can only be called once per Content Instance - xamarin

I have the Google drive opened and the files are selectable. After clicking the confirmation button, I will have a response and call the InputStream and start reading the file. This was my code which read the InputStream.
var pendingResult = driveFile.OpenAsync(GoogleApiClient, DriveFile.ModeReadOnly, this)
.ContinueWith((resultTask) =>
{
var driveContentResults = resultTask.Result;
var driveContent = driveContentResults.DriveContents;
if (_dialog != null && _dialog.IsShowing)
_dialog.Dismiss();
if (driveContentResults.Status.IsSuccess)
{
if (FileReadyCallback != null)
{
var length = driveContent.InputStream.Length;
//var data = new byte[length];
//driveContent.InputStream.Read(data, 0, data.Length);
//FileReadyCallback(this, data);
}
//var absolutePath = FileUtilities.SaveStreamToDownloadDirectory(driveContent.InputStream, Guid.NewGuid() + ".pdf");
//SendResultToCallingActivity(absolutePath);
}
});
When the application reached to driveContent.InputStream.Length, the breakpoint showed me that the InputStream can only be called once per Content Instance. In the code, that line is my first call of the input stream.

As the error says, instead of calling driveContent.InputStream every time, make a variable named input and assign driveContent.InputStream, then use input to read bytes, get length or other methods.
var input = driveContent.InputStream
and then replace with
var length = input.Length;
and
input.Read(data, 0, data.Length);

Related

Error message cites non-existent line and column in code for Google Apps Script

I get the following error message when running some code in Google Apps Script. I don't understand the Line/Column reference, Code:46:18. It appears to point to either a line with too few columns or a process with too few lines. I assume I am not interpreting the reference correctly.
TypeError: Cannot set property 'format' of undefined
at processInbox(processInbox Code:46:18)
Line 46 of all my code is this and certainly doesn't have 18 columns (and it closes a function that doesn't refer to format):
}
The process referred to by the error message, processInbox, is only 39 lines long.
The script is called by selecting "Run Script" in the menu, "CiviSchedule" in the related Google Sheet, which triggers the doTasks function. This menu and and trigger are created in the onOpen function.
How am I misinterpreting the error message? (Full code follows)
[screenshot of error]
[screenshot of lines 40-46]
The code for reference:
//General Info
//
// As detailed in Managing Scheduled Jobs URL method http://wiki.civicrm.org/confluence/display/CRMDOC/Managing+Scheduled+Jobs#ManagingScheduledJobs-URLmethod :
//
// a valid Username and Password (for a Drupal, Joomla or WordPress user who has adequate permissions
// for the job or jobs being run. The minimal permissions for that user are: “view all contacts”, “access
// CiviCRM”, “access CiviMail”). It also requires you to pass in the CIVICRM_SITE_KEY which is configured
// by editing your copy of civicrm.settings.php
//
// I’d recommend setting up a dedicated account for scheduling reports with only minimal permissions.
// Once you have a username/password setup open File > Project Properties and open the Script Properties
// tab. Click ‘Add row’ link and add your setup account name (username), pass (password), key (site key).
// Save the Script Properties and then in the script editor window enter the BASE_URL below of your Civi
// installation (in Drupal this looks like http://[SITEROOT]/sites/all/modules/civicrm/bin/cron.php?.
// File > Save your script
var BASE_URL = "https://www.fubar.org/sites/all/modules/civicrm/bin/cron.php?";
// To get this script to run automatically open Resources > Current project triggers
// and slect doTasks to run as a day timer (we set reports to run between 7-8am)
// If you want to run earlier or later also adjust the RERUN_HOUR below which sets the next run time
var RERUN_HOUR = 1;
var PS = PropertiesService.getScriptProperties();
var param = PS.getProperties();
param.job = "mail_report";
// helper so we know which value is in which column
var COL = {report_id: 0,
type: 1,
last_run: 2,
next_run: 3,
format: 4,
ss_id: 5,
ss_sht: 6,
total: 7};
function onOpen(){
var ui = SpreadsheetApp.getUi();
ui.createMenu('CiviSchedule')
.addItem('Run Script', 'doTasks')
.addToUi();
}
function doTasks() {
var doc = SpreadsheetApp.getActiveSpreadsheet(); // get spreadsheet
var sheet = doc.getSheetByName("Tasks"); // get sheet
var data = sheet.getRange(3, 1, sheet.getLastRow(), COL.total).getValues(); // get values
var now = new Date(); // time now
// for each row of the sheet interate accross
for (var i = 0; i < data.length; i++){
if (data[i][COL.report_id] != ""){ // if there is instance id do something
// collect row values
var report_id = data[i][COL.report_id]
var type = data[i][COL.type];
var next_run = data[i][COL.next_run] || 0;
// check if it's time to run the report again
if (next_run < now && type != "never"){
// if it is ping the report trigger
var new_next_run = callUrl(report_id, type, {format: data[i][COL.format], ss_id: data[i][COL.ss_id], ss_sht: data[i][COL.ss_sht]} );
// ..and record when to run again
sheet.getRange(parseInt(i)+3, 3, 1, 2).setValues([[now, new_next_run]]);
}
}
}
}
function callUrl(report_id, type, optParam){
// build the url to trigger the report
param.format = optParam.format || "print";
if (optParam.ss_id && optParam.ss_sht){
// if we have a sheet name and id force csv
param.format = 'csv';
// make a search string to find our report
optParam.search_str = 'report/instance/'+report_id+'?reset=1 has:attachment is:unread';
// store our search for later
PS.setProperty('search_str_'+report_id, JSON.stringify(optParam));
// set the script to read the email run 15min later
ScriptApp.newTrigger("processInbox")
.timeBased()
.after(1 * 60 * 1000)
.create();
}
// make url
var qs = BASE_URL
for(var key in param) {
if (key.substring(0, 10) != "search_str"){
var value = param[key];
qs += key + "=" + value + "&";
}
}
qs += "instanceId="+report_id;
try {
//gg var resp = UrlFetchApp.fetch(qs); // hit the url
// now calculate when to run again
var d = new Date();
d.setHours(RERUN_HOUR);
d.setMinutes(0);
switch (type){
case "daily":
d.setDate(d.getDate() + 1);
break;
case "weekly":
d.setDate(d.getDate() + 7);
break;
case "monthly":
// Get the first Monday in the month
d.setDate(1);
d.setMonth(d.getMonth() + 1);
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
break;
}
return d;
} catch(e) {
return e.message;
}
}
function processInbox(){
var PS = PropertiesService.getScriptProperties();
var data = PS.getProperties();
for (var key in data) {
try { if (key.substring(0, 10) == "search_str"){
var param_raw = data[key];
var param = JSON.parse(param_raw);
// get last 20 message threads using serach term
var threads = GmailApp.search(param.search_str, 0, 20);
// assume last thread has our latest data
var last_thread = threads.length-1;
if (last_thread > -1){
// get message in the last thread
var msg = threads[last_thread].getMessages()[0];
// get the attachments
var attachments = msg.getAttachments();
for (var k = 0; k < attachments.length; k++) {
// get the attachment as a string
var csv_str = attachments[k].getDataAsString();
// parse string as csv
var csv = Utilities.parseCsv(csv_str);
// create destination object
var doc = SpreadsheetApp.openById(param.ss_id);
var sheet = doc.getSheetByName(param.ss_sht);
// clear any old data
sheet.clear();
// write new data
sheet.getRange(1, 1, csv.length, csv[0].length).setValues(csv);
// mark message are read and archive (you could also label or delete)
threads[last_thread].moveToArchive().markRead();
PS.deleteProperty(key);
}
}
}
} catch(e) {
SpreadsheetApp.getUi().alert('problem: ${e}');
}
}
}
at processInbox(processInbox Code:46:18)
The syntax is
at ${FUNCTION}(${FILE}:${LINE}:${COLUMN})
This would suggest that the code causing the error is elsewhere.
At file
processInbox Code
within function
processInbox
And at line
46
and at column
18
You probably have a same function name processInbox at a different file named processInbox Code. In that file, at line 46, col 18, you'll have your error.
I think that you problem may be that this line:
var data = sheet.getRange(3, 1, sheet.getLastRow(), COL.total).getValues();
should be like this:
var data = sheet.getRange(3, 1, sheet.getLastRow() - 2, COL.total).getValues();

Rename a recorded file every time I save a record in xamarin

I am saving my records using this code:
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
public string fileName { get; set; }
fileName = Path.Combine(path, "sample.wav");
if (!recorder.IsRecording)
{
recorder.StopRecordingOnSilence = TimeoutSwitch.IsToggled;
//Start recording
var audioRecordTask = await recorder.StartRecording();
BtnDoneRec.IsEnabled = false;
await audioRecordTask;
RecEditor.IsEnabled = true;
BtnDoneRec.IsEnabled = false;
PlayButton.IsEnabled = true;
var filePath = recorder.GetAudioFilePath();
if (filePath != null)
{
var stream = recorder.GetAudioFileStream();
using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
}
}
}
else
{
//stop recording ...
await recorder.StopRecording();
}
I want my record to have a specific name which is labeled with my RecEditor
using (var streamReader = new StreamReader(fileName))
{
File.Move("sample.wav", RecEditor.Text + ".wav");
}
So it will rename "sample.wav" to "RecEditor text.wav" every time I click my save button.
But when I click save, it gives me this record
System.IO.FileNotFoundException: 'Could not find file '/sample.wav'.'
The record is stored in /storage/emulated/0/sample.wav
The sample.wav is created in my device but I don't know why it give me 'Could not find file '/sample.wav'.' error. What am i doing wrong here?
I believe that what you're looking is something like this:
if(File.Exists(fileName))
{
var newFileName = Path.Combine(path, $"{RecEditor.Text}.wav");
File.Move(fileName, newFileName);
}
You don't need to open a new Stream as you are doing. Also, you need to put the full file path not only the file name.
You might want to validate that RecEditor.Text is not empty before using its value for the newfileName
Hope this helps.-

Android post image to Facebook comment

This is a followup to my previous question: Xamarin.Forms App return data to calling App
That works perfectly and I can share images to anywhere, except to Facebook comments. When I click the camera on the content box the app can be selected, I can select the image, Set result and Finish are called, and the app closes and it sends data to Facebook, and then however I then get the error : The image could not be uploaded, try again?
I can't find any fundamental differences between posting to a status or a comment, so I'm guessing it's subtle. Any thoughts on how I can change my intent to post properly?
Adding for completeness:
Bitmap b = null;
string url;
if (!string.IsNullOrEmpty(this.saleItems[i].ImageUrl))
{
url = this.saleItems[i].ImageUrl;
}
else
{
url = await FileHelper.GetLocalFilePathAsync(this.saleItems[i].Id);
}
//download
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
b = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
//set local path
var tempFilename = "test.png";
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePath = System.IO.Path.Combine(sdCardPath, tempFilename);
using (var os = new FileStream(filePath, FileMode.Create))
{
b.Compress(Bitmap.CompressFormat.Png, 100, os);
}
b.Dispose();
var imageUri = Android.Net.Uri.Parse($"file://{sdCardPath}/{tempFilename}");
var sharingIntent = new Intent();
sharingIntent.SetAction(Intent.ActionSend);
sharingIntent.SetType("image/*");
sharingIntent.PutExtra(Intent.ExtraText, "some txt content");
sharingIntent.PutExtra(Intent.ExtraStream, imageUri);
sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
//await SaleItemDataService.Instance.BuySaleItemAsync(this.saleItem);
SetResult(Result.Ok, sharingIntent);
Finish();
Use below:
Intent sharingIntent = new Intent();
string imageUri = "file://" + requestedUri;
sharingIntent.SetData(Android.Net.Uri.Parse(imageUri));

Windows 8.1 store xaml save InkManager in a string

I'm trying to save what i have drawn with the pencil as a string , and i do this by SaveAsync() method to put it in an IOutputStream then convert this IOutputStream to a stream using AsStreamForWrite() method from this point things should go fine, however i get a lot of problems after this part , if i use for example this code block:
using (var stream = new MemoryStream())
{
byte[] buffer = new byte[2048]; // read in chunks of 2KB
int bytesRead = (int)size;
while (bytesRead < 0)
{
stream.Write(buffer, 0, bytesRead);
}
byte[] result = stream.ToArray();
// TODO: do something with the result
}
i get this exception
"Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."
or if i try to convert the stream into an image using InMemoryRandomAccessStream like this:
InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
await s.CopyToAsync(ras.AsStreamForWrite());
my InMemoryRandomAccessStream variable is always zero in size.
also tried
StreamReader.ReadToEnd();
but it returns an empty string.
found the answer here :
http://social.msdn.microsoft.com/Forums/windowsapps/en-US/2359f360-832e-4ce5-8315-7f351f2edf6e/stream-inkmanager-strokes-to-string
private async void ReadInk(string base64)
{
if (!string.IsNullOrEmpty(base64))
{
var bytes = Convert.FromBase64String(base64);
using (var inMemoryRAS = new InMemoryRandomAccessStream())
{
await inMemoryRAS.WriteAsync(bytes.AsBuffer());
await inMemoryRAS.FlushAsync();
inMemoryRAS.Seek(0);
await m_InkManager.LoadAsync(inMemoryRAS);
if (m_InkManager.GetStrokes().Count > 0)
{
// You would do whatever you want with the strokes
// RenderStrokes();
}
}
}
}

Writing CSV to MemoryStream using LinqToCSV does not return any data

I've verified using System.Text.Encoding.ASCII.GetString(ms.ToArray)); that my memorystream has the expected data.
However using the LinqToCSV nuget library will not generate my csv file. I get no errors or exceptions thrown. I just get an empty file when I'm prompted to open the file.
Here is my Action Method
public FileStreamResult Export(){
var results = _service.GetProperties().Take(3);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.TextWriter txt = new System.IO.StreamWriter(ms);
CsvFileDescription inputFileDescription = new CsvFileDescription{
SeparatorChar =',',
FirstLineHasColumnNames = true
}
;
CsvContext csv = new CsvContext();
csv.Write(results,txt,inputFileDescription);
return File(ms , "application/x-excel");
}
I find it interesting, if I change the return type to contentResult, and the return method to Content() and pass it System.Text.Encoding.ASCII.GetString(ms.ToArray)); I do get a browser window showing my data.
Make sure you reset stream position to 0. Also make sure you flush your StreamWriter before that.
Calling the Web API method to return CVS file from JavaScript.
public HttpResponseMessage Bidreport([FromBody]int formData).....
Fill in your IEnumerable<YourObject>query = from LINQ query
....
This is how to return it:
using (var ms = new MemoryStream())
{
using (TextWriter txt = new StreamWriter(ms))
{
var cc = new CsvContext();
cc.Write(query, txt, outputFileDescription);
txt.Flush();
ms.Position = 0;
var fileData = Encoding.ASCII.GetString(ms.ToArray());
var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(fileData)};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-excel");
return result;
}
}

Resources