"The request has already been submitted.” while working with Skydrive API in WP8 - windows-phone-7

I am trying to use the SkyDrive API to upload a file. I tried using the below code.GEtAccountInformaiton and GetQuotaInformaiton methods are successfully executed But it always sets this error "The request has already been submitted.” at the end (in UploadISOFileToSkyDriveAsync() method for the field lblMessageBar.Text ).
private async void GetAccountInformations()
{
try
{
LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me");
var jsonResult = operationResult.Result as dynamic;
string firstName = jsonResult.first_name ?? string.Empty;
string lastName = jsonResult.last_name ?? string.Empty;
lblMessageBar.Text = "Welcome " + firstName + " " + lastName;
GetQuotaInformations();
}
catch (Exception e)
{
lblMessageBar.Text = e.ToString();
}
}
private async void GetQuotaInformations()
{
try
{
LiveOperationResult operationResult = await App.liveConnectClient.GetAsync("me/skydrive/quota");
var jsonResult = operationResult.Result as dynamic;
quota = jsonResult.quota ?? string.Empty;
available = jsonResult.available ?? string.Empty;
lblMessageBar.Text = "Available space in bytes: " + ConvertBytesToGigabytes(available).ToString("#.####") + "GB " + "out of bytes " + ConvertBytesToGigabytes(quota).ToString("#.####") + "GB";
UploadISOFileToSkyDriveAsync();
}
catch (Exception e)
{
lblMessageBar.Text = e.ToString();
}
}
public async void UploadISOFileToSkyDriveAsync()
{
try
{
//http://developer.nokia.com/Community/Wiki/SkyDrive_-_How_to_upload_content_on_Windows_Phone
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.Append, fileStorage));
//get the data from local database and write to the isolated file and then use the path of this file to saved it to skydrive..
ObservableCollection<SavedLocationsTableEntity> SavedLocations = SavedLocationsTableEntity.GetSavedLocations();
foreach (SavedLocationsTableEntity item in SavedLocations)
{
Writer.WriteLine(UtilityLib.GetGoogleURL(new System.Device.Location.GeoCoordinate(item.SavedLocationLatitude, item.SavedLocationLongitude, item.SavedLocationAltitude)));
}
Writer.Close();
using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication())
{
fileStream = store.OpenFile("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, FileMode.OpenOrCreate, FileAccess.Read);
//strEncryptedFileStream = Encoding.Unicode.GetBytes(fileStream.ToString()).ToString();
if (fileStream.Length == 0)
{
lblMessageBar.Text = "No data to upload to SkyDrive..";
return;
}
fileStream.Close();
}
//remove previous calls
var reqList = BackgroundTransferService.Requests.ToList();
foreach (var req in reqList)
{
if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore, UriKind.Relative)))
BackgroundTransferService.Remove(BackgroundTransferService.Find(req.RequestId));
}
//Make a new call to upload
LiveOperationResult res = await App.liveConnectClient.BackgroundUploadAsync("me/skydrive", new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative), OverwriteOption.Overwrite);
lblMessageBar.Text = "File " + Constants.SkyDriveSavedLocationsFileName + " uploaded.";
return;
}
catch (Exception ex)
{
lblMessageBar.Text = "Cannot upload to SkyDrive.. " + ex.Message;
return;
}
}

It looks like MyFilePathInIsoStore here:
if (req.UploadLocation.Equals(new Uri(MyFilePathInIsoStore
is not equals "/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName here:
new Uri("/shared/transfers/" + Constants.SkyDriveSavedLocationsFileName, UriKind.Relative)

Related

Bot Framework with LUIS - Issue with opening Form one after another

My bot is supposed to help delete appointment.
A prompt for user's nric will be done (in RetrieveAppt.cs)
Subsequently, if there is such user in my database, it should go on to prompt user to enter the apptId which he/she wants to delete (as there may be multiple appointments made by same person) (in DeleteAppt.cs)
Issue Description
Exception thrown: 'Microsoft.Bot.Builder.Internals.Fibers.InvalidNeedException' in Microsoft.Bot.Builder.dll
Code Example
RetrieveAppt.cs
using Microsoft.Bot.Builder.FormFlow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Bot.Models
{
[Serializable]
public class RetrieveAppt
{
[Prompt("Please provide your NRIC:")]
public string Nric { get; set; }
public override string ToString()
{
var builder = new StringBuilder();
builder.AppendFormat(Nric);
return builder.ToString();
}
}
}
DeleteAppt.cs
using Microsoft.Bot.Builder.FormFlow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace Bot.Models
{
[Serializable]
public class DeleteAppt
{
[Prompt("Please enter the appointment id that you wish to delete/cancel :")]
public string apptId { get; set; }
public override string ToString()
{
var builder = new StringBuilder();
builder.AppendFormat(apptId);
return builder.ToString();
}
}
}
ApptLuisDialog.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Luis;
using Microsoft.Bot.Builder.Luis.Models;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.FormFlow;
using Microsoft.Bot.Connector;
using Bot.Models;
using System.Data.SqlClient;
using System.Globalization;
namespace Bot.Dialogs
{
[LuisModel("I have my own key", "I have my own key")]
[Serializable]
class ApptLuisDialog : LuisDialog<ApptLuisDialog>
{
String sql = #"Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=Temp.DB; User Id = (insert your username here); Password = (insert your password here); Integrated Security=true;MultipleActiveResultSets = true";
private static IForm<RetrieveAppt> BuildRetrieveForm()
{
var builder = new FormBuilder<RetrieveAppt>();
return builder.AddRemainingFields().Build();
}
private static IForm<DeleteAppt> BuildDeleteForm()
{
var builder = new FormBuilder<DeleteAppt>();
return builder.AddRemainingFields().Build();
}
[LuisIntent("")]
[LuisIntent("None")]
public async Task None(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: B");
await context.PostAsync("I'm sorry I don't understand you. However, I can help you to: \n\n" + "1) Retrieve Appointment \n\n" + "2) Create Appointment \n\n" + "3) Delete Appointment \n\n" + "4) Edit Appointment");
context.Wait(MessageReceived);
}
[LuisIntent("RetrieveAppointment")]
public async Task RetrieveAppointment(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: C");
var form = new RetrieveAppt();
var entities = new List<EntityRecommendation>(result.Entities);
var retrieveAppt = new FormDialog<RetrieveAppt>(form, BuildRetrieveForm, FormOptions.PromptInStart);
context.Call(retrieveAppt, RetrieveComplete);
}
private async Task RetrieveComplete(IDialogContext context, IAwaitable<RetrieveAppt> result)
{
RetrieveAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You cancelled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String nric = appt.Nric.ToString();
List<string> apptInfo = new List<string>();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command
SqlCommand cmd = new SqlCommand("SELECT * FROM Appointment a WHERE a.Nric ='" + nric + "'", con);
//Open sql connection
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String date = dr["AptDate"].ToString();
String[] temp = date.Split(null);
apptInfo.Add("Appointment ID: " + dr["ApptId"].ToString() + "\n\n"
+ "Nric: " + dr["Nric"].ToString() + "\n\n"
+ "Date: " + temp[0] + "\n\n"
+ "Time: " + dr["AptStartTime"].ToString() + "\n\n"
+ "Location: " + dr["Location"].ToString() + "\n\n"
+ "Purpose: " + dr["Purpose"].ToString());
}
//Close sql connection
dr.Close();
con.Close();
if (apptInfo.Count == 0)
{
await context.PostAsync("You do not have an appointment/no such NRIC");
}
else
{
for (int i = 0; i < apptInfo.Count(); i++)
{
await context.PostAsync("Your Appointment Info is: " + "\n\n" + apptInfo[i]);
}
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
[LuisIntent("DeleteAppointment")]
public async Task DeleteAppointment(IDialogContext context, LuisResult result)
{
System.Diagnostics.Debug.WriteLine("Entered here: A");
var form = new RetrieveAppt();
var retrieveAppt = new FormDialog<RetrieveAppt>(form, BuildRetrieveForm, FormOptions.PromptInStart);
context.Call(retrieveAppt, Delete);
}
private async Task Delete(IDialogContext context, IAwaitable<RetrieveAppt> result)
{
RetrieveAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You cancelled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String nric = appt.Nric.ToString().ToUpper();
List<string> apptInfo = new List<string>();
//SqlAdapter for inserting new records
SqlDataAdapter sda = new SqlDataAdapter();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command to check existing patient
SqlCommand cmd = new SqlCommand("SELECT * FROM Appointment a WHERE a.Nric ='" + nric + "'", con);
//Open sql connection
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
String date = dr["AptDate"].ToString();
String[] temp = date.Split(null);
apptInfo.Add("Appointment ID: " + dr["ApptId"].ToString() + "\n\n"
+ "Nric: " + dr["Nric"].ToString() + "\n\n"
+ "Date: " + temp[0] + "\n\n"
+ "Time: " + dr["AptStartTime"].ToString() + "\n\n"
+ "Location: " + dr["Location"].ToString() + "\n\n"
+ "Purpose: " + dr["Purpose"].ToString());
}
if (apptInfo.Count != 0)
{
**//this is the part that has error, i can't prompt for the appointment id that user wants to delete**
System.Diagnostics.Debug.WriteLine("Entered here: AA");
var form = new DeleteAppt();
var deleteAppt = new FormDialog<DeleteAppt>(form, BuildDeleteForm, FormOptions.PromptInStart);
context.Call(deleteAppt, DeleteComplete);
}
else
{
//Close sql connection
dr.Close();
con.Close();
await context.PostAsync("Invalid NRIC/No current appointment");
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
private async Task DeleteComplete(IDialogContext context, IAwaitable<DeleteAppt> result)
{
DeleteAppt appt = null;
try
{
appt = await result;
}
catch (OperationCanceledException)
{
await context.PostAsync("You canceled the form!");
return;
}
if (appt != null)
{
//getting user's input value
String apptId = appt.apptId.ToString();
List<string> newApptInfo = new List<string>();
//SqlAdapter for inserting new records
SqlDataAdapter sda = new SqlDataAdapter();
//Create connection
SqlConnection con = new SqlConnection(sql);
//SQL Command to check existing patient
String cmd = "DELETE FROM Appointment a WHERE a.ApptId ='" + apptId + "'";
//Open sql connection
con.Open();
try
{
sda.InsertCommand = new SqlCommand(cmd, con);
sda.InsertCommand.ExecuteNonQuery();
//Close sql connection
con.Close();
await context.PostAsync("Appointment " + apptId + " cancelled successfully.");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception caught: " + ex);
}
}
else
{
await context.PostAsync("Form returned empty response!");
}
context.Wait(MessageReceived);
}
}
}
Expected Behavior
For example, after bot prompts user to input NRIC, user inputs "123456". So let's say, there are 3 appointments linked to NRIC "123456". So it will show all 3 appointments (with the following details: apptId, apptDate, apptTime, locatoin) first.
Next, I want the bot to prompt the user for the appointment that he/she wants to delete base on the apptId. (But this prompt is not showing)
Actual Results
Exception thrown: 'Microsoft.Bot.Builder.Internals.Fibers.InvalidNeedException' in Microsoft.Bot.Builder.dll
Help needed here definitely
adding a "return" statement would solve it.
When making the call to context.Call(deleteAppt, DeleteComplete); there should not follow a call to context.Wait(MessageReceived). So add a return statement after context.Call(deleteAppt, DeleteComplete);
if (apptInfo.Count != 0)
{
//this is the part that has error, i can't prompt for the appointment id that user wants to delete
System.Diagnostics.Debug.WriteLine("Entered here: AA");
var form = new DeleteAppt();
var deleteAppt = new FormDialog<DeleteAppt>(form, BuildDeleteForm, FormOptions.PromptInStart);
context.Call(deleteAppt, DeleteComplete);
return;
}

The specified string is not in the form required for an e-mail address.i am getting Emails from Database

this is method
#region StuDetailsMail
public List StuDetailsMail(string Stu_Name, string Stu_Email, string Stu_Mobile)
{
List data = new List();
SqlParameter[] sqlprm = new SqlParameter[3];
SqlDataReader dr = null;
try {
sqlprm[0] = new SqlParameter(DBProcedures.sqlparam_Name, Stu_Name);
sqlprm[1] = new SqlParameter(DBProcedures.sqlpram_Email, Stu_Email);
sqlprm[2] = new SqlParameter(DBProcedures.sqlpram_Mobile_Num, Stu_Mobile);
dr = objDAL.ExecuteReader(DBProcedures.Usp_StuEmail, ref sqlprm, false);
while (dr.Read())
{
InstEmails list1 = new InstEmails()
{
Emaillist = dr["email"].ToString(),
};
data.Add(list1);
};
foreach (var emailId in data)
{
string MessageBody = "studentname" + Stu_Name + " is Intersted" + "studentmail is" + Stu_Email;
string MailSubject = "this is from Traininghubs";
obj.SendEmailToInstitute(emailId.ToString(), MessageBody, MailSubject);
}
}
catch(Exception e)
{
}
return data;
}
#endregion

Download and Save PDF for viewing

Im trying to download a PDF document from my app and display it in IBooks or at least make it available to read some how when its completed downloading.
I followed the download example from Xamarin which allows me download the PDF and save it locally. Its being save in the wrong encoding also.
This is what I've tried so far.
private void PdfClickHandler()
{
var webClient = new WebClient();
webClient.DownloadStringCompleted += (s, e) => {
var text = e.Result; // get the downloaded text
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = $"{_blueways}.pdf";
// writes to local storage
File.WriteAllText(Path.Combine(documentsPath, localFilename), text);
InvokeOnMainThread(() => {
new UIAlertView("Done", "File downloaded and saved", null, "OK", null).Show();
});
};
var url = new Uri(_blueway.PDF);
webClient.Encoding = Encoding.UTF8;
webClient.DownloadStringAsync(url);
}
Do not use DownloadStringAsync for "binary" data, use DownloadDataAsync:
Downloads the resource as a Byte array from the URI specified as an asynchronous operation.
private void PdfClickHandler ()
{
var webClient = new WebClient ();
webClient.DownloadDataCompleted += (s, e) => {
var data = e.Result;
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = $"{_blueways}.pdf";
File.WriteAllBytes (Path.Combine (documentsPath, localFilename), data);
InvokeOnMainThread (() => {
new UIAlertView ("Done", "File downloaded and saved", null, "OK", null).Show ();
});
};
var url = new Uri ("_blueway.PDF");
webClient.DownloadDataAsync (url);
}
// Retrieving the URL
var pdfUrl = new Uri("url.pdf"); //enter your PDF path here
// Open PDF URL with device browser to download
Device.OpenUri(pdfUrl);
//First Create Model Class FileDownload
public class FileDownload
{
public string FileUrl { get; set; }
public string FileName { get; set; }
}
//Create a view in xaml file for button on which we need to perform download functionality
<ImageButton BackgroundColor="Transparent" Clicked="DownloadFile_Clicked" x:Name="ImgFileReportDownload_ViewResult" IsVisible="False">
<ImageButton.Source>
<FontImageSource Glyph=""
Color="#1CBB8C"
Size="30"
FontFamily="{StaticResource FontAwesomeSolid}">
</FontImageSource>
</ImageButton.Source>
</ImageButton>
//Created a method in xaml.cs to download File on the click of button
private async void DownloadFile_Clicked(object sender, EventArgs e)
{
var status = await Permissions.CheckStatusAsync<Permissions.StorageWrite>();
if (status == PermissionStatus.Granted)
{
Uri uri = new Uri(fileReportNameViewResult);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
FileDownload fileDownload = new FileDownload();
fileDownload.FileName = filename;
fileDownload.FileUrl = fileReportNameViewResult;
MessagingCenter.Send<FileDownload>(fileDownload, "Download");
}
else
{
status = await Permissions.RequestAsync<Permissions.StorageWrite>();
if (status != PermissionStatus.Granted)
{
await DisplayAlert("Permission Denied!", "\nPlease go to your app settings and enable permissions.", "Ok");
return;
}
}
}
//In MainActivity.cs , create a method
private void MessagingCenter()
{
Xamarin.Forms.MessagingCenter.Subscribe<FileDownload>(this, "Download", (s) =>
{
NotificationID += 4;
var intent = new Intent(this, typeof(Service.DownloadManager));
intent.PutExtra("url", s.FileUrl);
intent.PutExtra("name", s.FileName);
_layout.SetMinimumHeight(3000);
_layout.Bottom = 350; ;
Snackbar.Make(_layout, "Document is Downloading.", Snackbar.LengthShort)
.Show();
StartService(intent);
});
}
//Create a class DownloadManager.cs in Service folder , copy all the below code and paste , just change the Namespace
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace App.Droid.Service
{
[Service]
public class DownloadManager : Android.App.Service
{
AndroidNotificationManager NotificationManager = new AndroidNotificationManager();
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnCreate()
{
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Task.Run(() =>
{
int messageId = ++MainActivity.NotificationID;
string url = intent.GetStringExtra("url");
string filename = intent.GetStringExtra("name");
string extension = url.Substring(url.LastIndexOf('.'));
if (!filename.EndsWith(extension))
{
filename += extension;
}
NotificationManager.ScheduleNotification(filename, "", messageId);
String TempFileName = "";
try
{
HttpWebRequest Http = (HttpWebRequest)WebRequest.Create(url);
WebResponse Response = Http.GetResponse();
long length = Response.ContentLength;
var stream = Response.GetResponseStream();
string baseDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
//string baseDir = Android.App.Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
//string baseDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
//string baseDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
baseDir = Path.Combine(baseDir, filename.Substring(filename.LastIndexOf('/') + 1).Replace(' ', '_'));
Directory.CreateDirectory(baseDir);
//string filePath = Path.Combine(documentsPath, name);
if (filename.Length > 18)
{
TempFileName = filename.Substring(0, 18) + "...";
}
else
{
TempFileName = filename;
}
FileInfo fi = new FileInfo(Path.Combine(baseDir, filename.Substring(filename.LastIndexOf('/') + 1).Replace(' ', '_')));
var fis = fi.OpenWrite();
long count = 0;
int begpoint = 0;
bool iscancelled = false;
MessagingCenter.Subscribe<CancelNotificationModel>(this, "Cancel", sender =>
{
if (messageId == sender.ID)
{
iscancelled = true;
}
});
while (true)
{
try
{
if (iscancelled == true)
{
break;
}
// Read file
int bytesRead = 0;
byte[] b = new byte[1024 * 1024];
bytesRead = stream.Read(b, begpoint, b.Length);
if (bytesRead == 0)
break;
fis.Write(b, 0, bytesRead);
fis.Flush();
count += bytesRead;
System.Diagnostics.Debug.WriteLine(count + "-" + length);
if (count >= length)
break;
NotificationManager.ChangeProgress(TempFileName, (int)((count * 100) / length), messageId);
}
catch (Exception ex)
{
Http = (HttpWebRequest)WebRequest.Create(url);
WebHeaderCollection myWebHeaderCollection = Http.Headers;
Http.AddRange(count, length - 1);
Response = Http.GetResponse();
stream = Response.GetResponseStream();
}
}
fis.Close();
NotificationManager.RemoveNotification(messageId);
if (iscancelled == false)
{
new AndroidNotificationManager().DownloadCompleted(filename, "Download Completed", Path.Combine(baseDir, filename), ++messageId);
}
}
catch (Exception ex)
{
NotificationManager.RemoveNotification(messageId);
NotificationManager.FileCancelled(filename, "Download Cancelled, Please try again", ++messageId);
}
});
return StartCommandResult.NotSticky;
}
public override void OnDestroy()
{
}
}
public class CancelNotificationModel
{
public int ID { get; set; }
}
}
//Create a class AndroidNotificationManager.cs in Service folder
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using AndroidX.Core.App;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Essentials;
using AndroidApp = Android.App.Application;
namespace App.Droid.Service
{
public class AndroidNotificationManager
{
const string channelId = "default";
const string channelName = "Default";
const string channelDescription = "The default channel for notifications.";
const int pendingIntentId = 0;
public const string TitleKey = "title";
public const string MessageKey = "message";
bool channelInitialized = false;
NotificationManager manager;
NotificationCompat.Builder builder;
public event EventHandler NotificationReceived;
public void Initialize()
{
CreateNotificationChannel();
}
public void RemoveNotification(int messageid)
{
manager.Cancel(messageid);
}
public int ScheduleNotification(string title, string message, int messageId, bool isInfinite = false)
{
if (!channelInitialized)
{
CreateNotificationChannel();
}
Intent intent = new Intent(AndroidApp.Context, typeof(MainActivity));
intent.PutExtra(TitleKey, title);
intent.PutExtra(MessageKey, message);
PendingIntent pendingIntent = PendingIntent.GetActivity(AndroidApp.Context, pendingIntentId, intent, PendingIntentFlags.OneShot);
builder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
.SetContentTitle(title)
.SetContentText(message)
.SetPriority(NotificationCompat.PriorityLow)
.SetVibrate(new long[] { 0L })
.SetProgress(100, 0, isInfinite)
.SetSmallIcon(Resource.Drawable.checkcircle);
var notification = builder.Build();
manager.Notify(messageId, notification);
return messageId;
}
public void ChangeProgress(string filename, int progress, int messageId)
{
try
{
var actionIntent1 = new Intent();
actionIntent1.SetAction("Cancel");
actionIntent1.PutExtra("NotificationIdKey", messageId);
var pIntent1 = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, actionIntent1, PendingIntentFlags.CancelCurrent);
var ProgressBuilder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
.SetSmallIcon(Resource.Drawable.checkcircle)
.SetContentTitle(filename)
.SetVibrate(new long[] { 0L })
.AddAction(Resource.Drawable.checkcircle, "Cancel", pIntent1)
.SetPriority(NotificationCompat.PriorityLow)
.SetProgress(100, progress, false)
.SetContentText(progress + "%")
.SetAutoCancel(false);
System.Diagnostics.Debug.WriteLine(progress);
manager.Notify(messageId, ProgressBuilder.Build());
}
catch
{
}
}
public void DownloadCompleted(string filenametitle, string Message, string filepath, int messageId)
{
try
{
if (!channelInitialized)
{
CreateNotificationChannel();
}
var CompletedBuilder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
.SetContentTitle(filenametitle)
.SetContentText(Message)
.SetAutoCancel(true)
.SetSmallIcon(Resource.Drawable.checkcircle);
Intent it = OpenFile(filepath, filenametitle);
if (it != null)
{
PendingIntent contentIntent =
PendingIntent.GetActivity(AndroidApp.Context,
pendingIntentId,
it,
PendingIntentFlags.OneShot
);
CompletedBuilder.SetContentIntent(contentIntent);
}
var notification = CompletedBuilder.Build();
manager.Notify(messageId, notification);
}
catch (Exception ex)
{
}
}
public void FileCancelled(string filenametitle, string Message, int messageId)
{
if (!channelInitialized)
{
CreateNotificationChannel();
}
var CompletedBuilder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
.SetContentTitle(filenametitle)
.SetContentText(Message)
.SetAutoCancel(true)
.SetSmallIcon(Resource.Drawable.checkcircle)
.SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate);
var notification = CompletedBuilder.Build();
manager.Notify(messageId, notification);
}
public void ReceiveNotification(string title, string message)
{
}
void CreateNotificationChannel()
{
manager = (NotificationManager)AndroidApp.Context.GetSystemService(AndroidApp.NotificationService);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var channelNameJava = new Java.Lang.String(channelName);
var channel = new NotificationChannel(channelId, channelNameJava, NotificationImportance.Low)
{
Description = channelDescription
};
manager.CreateNotificationChannel(channel);
}
channelInitialized = true;
}
public Intent OpenFile(string filePath, string fileName)
{
try
{
string application = "";
string extension = fileName.Substring(fileName.IndexOf('.'));
switch (extension.ToLower())
{
case ".doc":
case ".docx":
application = "application/msword";
break;
case ".pdf":
application = "application/pdf";
break;
case ".xls":
case ".xlsx":
application = "application/vnd.ms-excel";
break;
case ".jpg":
case ".jpeg":
case ".png":
application = "image/jpeg";
break;
case ".mp4":
application = "video/mp4";
break;
default:
application = "*/*";
break;
}
Java.IO.File file = new Java.IO.File(filePath);
bool isreadable =
file.SetReadable(true);
string ApplicationPackageName = AppInfo.PackageName;
var context = Android.App.Application.Context;
var component = new Android.Content.ComponentName(context, Java.Lang.Class.FromType(typeof(AndroidX.Core.Content.FileProvider)));
var info = context.PackageManager.GetProviderInfo(component, Android.Content.PM.PackageInfoFlags.MetaData);
var authority = info.Authority;
Android.Net.Uri uri = AndroidX.Core.Content.FileProvider.GetUriForFile(Android.App.Application.Context, authority, file);
Intent intent = new Intent(Intent.ActionView);
System.IO.File.AppendAllText((filePath + "backdebug.txt"), System.Environment.NewLine + "Point 3 uri done ");
intent.SetDataAndType(uri, application);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
intent.AddFlags(ActivityFlags.NoHistory);
intent.AddFlags(ActivityFlags.NewTask);
System.IO.File.AppendAllText((filePath + "backdebug.txt"), System.Environment.NewLine + "Point 4open file last ");
return intent;
}
catch (Exception ex)
{
Intent it = new Intent();
it.PutExtra("ex", ex.Message);
System.IO.File.AppendAllText((filePath + "backdebug.txt"), System.Environment.NewLine + "Point 4 uri done " + ex.Message);
return it;
}
}
}
}
Here is the sample code to download file in PCL Xamarin from remote server.
I have used PCLStorage library package which is available in Nuget. You just need download and install in your project.
public async void Downloadfile(string Url)
{
try
{
Uri url = new Uri(Url);
var client = new HttpClient();
IFolder rootfolder = FileSystem.Current.LocalStorage;
IFolder appfolder = await rootfolder.CreateFolderAsync("Download", CreationCollisionOption.OpenIfExists);
IFolder dbfolder = await appfolder.CreateFolderAsync("foldername", CreationCollisionOption.OpenIfExists);
IFile file = await dbfolder.CreateFileAsync(strReport_name, CreationCollisionOption.ReplaceExisting);
using (var fileHandler = await file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
{
var httpResponse = await client.GetAsync(url);
byte[] dataBuffer = await httpResponse.Content.ReadAsByteArrayAsync();
await fileHandler.WriteAsync(dataBuffer, 0, dataBuffer.Length);
}
}
catch (Exception ex)
{
throw ex;
}
}

Receive assets on Handheld

I'm sending files from wear to handheld side. I'm sending 4 or 5 files (2 of them are bigger) but everytime the handheld side only receives ONE of the bigger ones...
wear:
public void sendFile(String filename){
//BLE files
fileToArray("BLEdata/" + filename + "_RightDevice.txt", "/BLEdata/");
//send log file
fileToArray(filename + "_LOG.txt", "/LOGdata/");
//send GPS file
fileToArray("GPSdata/" + filename + "_GPS.txt", "/GPSdata/");
//send Report files
fileToArray("Report/" + filename + "_Report.txt", "/REPORTdata/");
//BLE files
fileToArray("BLEdata/" + filename + "_LeftDevice.txt", "/BLEdata/");
}
public void fileToArray(String filename, String path)
{
FileInputStream fileInputStream = null;
File file = new File(Environment.getExternalStorageDirectory() + "/TuneWear/" + filename);
System.out.println("PATH: " + file.getPath());
if(file.exists()){
byte[] bFile = new byte[(int) file.length()];
try {
//convert file into array of bytes
fileInputStream = new FileInputStream(file);
fileInputStream.read(bFile);
fileInputStream.close();
WearResultsActivity main = (WearResultsActivity) getActivity();
long time = main.getInitTime();
if(filename.contains("_RightDevice")){
new SendToDataLayerThread(path + time, bFile, 2).start();
}else if (filename.contains("_LeftDevice")){
new SendToDataLayerThread(path + time, bFile, 1).start();
} else
new SendToDataLayerThread(path + time, bFile).start();
}catch(Exception e){
e.printStackTrace();
}
} else System.out.println("Doesn't exist:\n" + file.getPath());
}
class SendToDataLayerThread extends Thread {
String path;
byte[] bFile;
int footSide;
// Constructor for sending data objects to the data layer
SendToDataLayerThread(String p, byte[] bytes, int footside) {
path = p;
bFile = bytes;
footSide = footside;
}
SendToDataLayerThread(String p, byte[] bytes) {
path = p;
bFile = bytes;
}
public void run() {
WearResultsActivity main = (WearResultsActivity) getActivity();
GoogleApiClient googleClient = main.getGoogleClient();
Asset asset = Asset.createFromBytes(bFile);
System.out.println(asset.toString());
PutDataMapRequest dataMap = PutDataMapRequest.create(path);
dataMap.getDataMap().putLong("timestamp", Calendar.getInstance().getTimeInMillis());
dataMap.getDataMap().putLong("/InitialTime", ((WearResultsActivity) getActivity()).getInitTime());
dataMap.getDataMap().putAsset("asset", asset);
if(footSide == 1) {
dataMap.getDataMap().putInt("footside", footSide);
System.out.println("DATAMAP COM LEFT " + footSide);
}else if (footSide == 2) {
dataMap.getDataMap().putInt("footside", footSide);
System.out.println("DATAMAP COM RIGHT " + footSide);
}
PutDataRequest request = dataMap.asPutDataRequest();
PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(googleClient, request);
pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
#Override
public void onResult(DataApi.DataItemResult dataItemResult) {
System.out.println("RESULT");
}
});
//Wearable.DataApi.putDataItem(googleClient, request);
}
}
Handheld:
#Override
public void onDataChanged(DataEventBuffer dataEvents) {
System.out.println("COUNT " + dataEvents.getCount());
for (DataEvent event : dataEvents) {
DataItem item = event.getDataItem();
if (event.getType() == DataEvent.TYPE_CHANGED) {
// DataItem changed
if (item.getUri().getPath().contains(LOGdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = new File(myDir, "Run_" + fileName + "_LOG.txt");
System.out.println("FILE: " + file.getPath());
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
} catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
} else if (item.getUri().getPath().contains(GPSdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/GPSdata/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = new File(myDir, "Run_" + fileName + "_GPS.txt");
System.out.println("FILE: " + file.getPath());
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
} catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
} else if (item.getUri().getPath().contains(REPORTdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/Report/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = new File(myDir, "Run_" + fileName + "_Report.txt");
System.out.println("FILE: " + file.getPath());
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
} catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
} else if (item.getUri().getPath().contains(BLEdata)) {
final DataMapItem dataMapItem = DataMapItem.fromDataItem(item);
Asset asset = dataMapItem.getDataMap().getAsset("asset");
//TODO here
Wearable.DataApi.getFdForAsset(googleClient, asset).setResultCallback(
new ResultCallback<DataApi.GetFdForAssetResult>() {
#Override
public void onResult(DataApi.GetFdForAssetResult getFdForAssetResult) {
InputStream assetInputStream = getFdForAssetResult.getInputStream();
long initialTime = dataMapItem.getDataMap().getLong(KEY_INITIALTIME);
String fileName = new SimpleDateFormat("HH'h'mm'm'ss's'_dd-MM-yyyy").format(initialTime);
String dataPath = Environment.getExternalStorageDirectory().toString() + "/TuneWear/BLEdata/";
File myDir = new File(dataPath);
myDir.mkdirs();
File file = null;
System.out.println("FOOT SIIIIIIDE: " + dataMapItem.getDataMap().getInt("footside"));
if(dataMapItem.getDataMap().getInt("footside") == 1){
file = new File(myDir, "Run_" + fileName + "_LeftDevice.txt");
System.out.println("FILE: " + file.getPath());
} else if(dataMapItem.getDataMap().getInt("footside") == 2){
file = new File(myDir, "Run_" + fileName + "_RightDevice.txt");
System.out.println("FILE: " + file.getPath());
}
try {
FileOutputStream fOut = new FileOutputStream(file);
int nRead;
byte[] data = new byte[16384];
while ((nRead = assetInputStream.read(data, 0, data.length)) != -1) {
fOut.write(data, 0, nRead);
}
fOut.flush();
fOut.close();
}
catch (IOException e) {
System.out.println("ERROR File write failed: " + e.toString());
}
}
}
);
}
} else if (event.getType() == DataEvent.TYPE_DELETED) {
// DataItem deleted
System.out.println("DataItem deleted: " + event.getDataItem().getUri());
}
//Wearable.DataApi.deleteDataItems(googleClient, event.getDataItem().getUri(), DataApi.FILTER_PREFIX);
}
}
I only receive the GPS, Report and LOG data every time. The other 2 files I only receive ONE... Im sending them exactly the same way, but I'm receiving only one of them.
Does anyone detects the error on my code???
EDIT
I just discovered that if the smartwatch is connected to the handheld at the time that the files are sent, they are all received. If they are not connected, one of the files (RightDevice.txt or LeftDevice.txt) are not received when they connect...
I solved it!
It was the most basic error of all.... I was sending the same path for the two files (RightDevice and LeftDevice) so only one of the objects was updated on the googleapiclient.

Error "Operation not permitted on IsolatedStorageFileStream." wp7

I am trying to read a text file from IsolatedStorage and check it contains a string. If not, the string is added to the end of the file. But When I am trying to write the string into file I got an error: "Operation not permitted on IsolatedStorageFileStream.". My code shown below. How can I overcome this problem?
public void AddToDownloadList()
{
IsolatedStorageFile downloadFile=IsolatedStorageFile.GetUserStoreForApplication();
try
{
string downloads = string.Empty;
if (!downloadFile.DirectoryExists("DownloadedFiles"))
downloadFile.CreateDirectory( "DownloadedFiles" );
if(downloadFile.FileExists("DownloadedFiles\\DownloadList.txt"))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile("DownloadedFiles\\DownloadList.txt",FileMode.Open, FileAccess.Read );
using ( StreamReader reader = new StreamReader( downloadStream ) )
{
downloads = reader.ReadToEnd();
reader.Close();
}
downloadFile.DeleteFile( "DownloadedFiles\\DownloadList.txt" );
}
downloadFile.CreateFile( "DownloadedFiles\\DownloadList.txt" );
string currentFile = FileName;
if ( !downloads.Contains( currentFile ) )
{
downloads += currentFile;
using ( StreamWriter writeFile = new StreamWriter( new IsolatedStorageFileStream( "DownloadedFiles\\DownloadList.txt", FileMode.Create, FileAccess.Write, downloadFile ) ) )
{
writeFile.Write( currentFile + "," );
writeFile.Close();
}
}
}
catch ( Exception ex )
{
string message = ex.Message;
}
}
I think the problem you were having has to do with the line where you create the StreamWriter by newing up the IsolatedStorageFileStream - when you already should have the right one from the return of the downloadFile.CreateFile() call.
Try this code, I think it does what you want to do:
public static void AddToDownloadList()
{
try
{
AddToDownloadList("DownloadedFiles", "this file name", "DownloadedFiles\\DownloadList.txt");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
}
}
public static void AddToDownloadList(string directory, string fileName, string filePath)
{
string downloads = string.Empty;
using (IsolatedStorageFile downloadFile = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!downloadFile.DirectoryExists(directory))
downloadFile.CreateDirectory(directory);
if (downloadFile.FileExists(filePath))
{
IsolatedStorageFileStream downloadStream = downloadFile.OpenFile(filePath, FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(downloadStream))
{
downloads = reader.ReadToEnd();
reader.Close();
}
}
string currentFile = fileName;
if (!downloads.Contains(currentFile))
{
downloadFile.DeleteFile(filePath);
using (IsolatedStorageFileStream stream = downloadFile.CreateFile(filePath))
{
downloads += currentFile;
using (StreamWriter writeFile = new StreamWriter(stream))
{
writeFile.Write(currentFile + ",");
writeFile.Close();
}
}
}
}
}

Resources