xamarin.forms - Upload multiple images and files using multipart/form data - xamarin

In my xamarin.forms app. I am using Media.plugin to select images from gallery and camera.And also file picker plugin to select files like pdf,jpg etc from file manager.User can select multiple images and files and It will store in an observable collection.In this observable collection I have the path of images as well as files. Where I am stuck is I want to send these data to rest API by using multipart/form data.How can I send these multiple files to the server? Any help is appreciated.
My ObservableCollection
public ObservableCollection<SelectedDocumentModel> DataManager
{
get
{
return _selectedfile ?? (_selectedfile = new ObservableCollection<SelectedDocumentModel>());
}
}
My Data Model
public class SelectedDocumentModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public string FileName { get; set; }
public string Path { get; set; }
public ImageSource SelectedImage { get; set; }
public object Tasks { get; internal set; }
private bool isLoadingVisible = false;
public bool IsLoadingVisible
{
get
{
return isLoadingVisible;
}
set
{
if (value != null)
{
isLoadingVisible = value;
NotifyPropertyChanged("IsLoadingVisible");
}
}
}
}
Selecting image using media.plugin and allocating to my observable collection
var Filename = Path.GetFileName(file.Path);
var FilePath = file.Path;
var newList = new SelectedDocumentModel()
{
FileName = Filename,
SelectedImage = imageSource,
IsLoadingVisible = false,
Path = FilePath
};
DataManager.Add(newList);
Selecting file from file manager using filepicker plugin and assign to observablecollection
var FilePath = pickedFile.FilePath;
var newList = new SelectedDocumentModel()
{
FileName = filename,
SelectedImage = imageSource,
IsLoadingVisible = false,
Path= FilePath
};
DataManager.Add(newList);
EDIT
This is what I should do using httpclient.Currently these are written using RestSharp.
var client = new RestClient("{{api_url}}/MYData");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "bearer {{token}}");
request.AddHeader("Content-Type", "application/json");
request.AlwaysMultipartFormData = true;
request.AddParameter("ids", " [{\"id\":1,\"person_id\":5}]");
request.AddParameter("title", " Test");
request.AddParameter("description", " Test");
request.AddParameter("send_text_message", " true");
request.AddParameter("text_message", " Test");
request.AddParameter("notification_type"," global");
request.AddParameter("my_files", "[
{
\"name\": \"abc.jpg\",
\"key\": \"1583307983694\"
}
]");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
What I have done by the way suggested by Lucas Zhang - MSFT.
try {
MultipartFormDataContent multiContent = new MultipartFormDataContent();
foreach (SelectedDocumentModel model in SelectedFileData)
{
byte[] byteArray = Encoding.UTF8.GetBytes(model.Path);
MemoryStream stream = new MemoryStream(byteArray);
HttpContent fileStreamContent1 = new StreamContent(stream);
fileStreamContent1.Headers.ContentDisposition = new
System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
{
Name = model.FileName,
FileName = model.FileName
};
fileStreamContent1.Headers.ContentType = new
System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
multiContent.Add(fileStreamContent1);
}
multiContent.Add(new StringContent(notificationdetails[0]), "title");
multiContent.Add(new StringContent(notificationdetails[1]), "description");
multiContent.Add(new StringContent(notificationdetails[3]), "type");
multiContent.Add(new StringContent(notificationdetails[7]), "send_text_message");
multiContent.Add(new StringContent(notificationdetails[2]), "text_message");
multiContent.Add(new StringContent(notificationdetails[8]), "send_email");
multiContent.Add(new StringContent(notificationdetails[9]), "notification_type");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("bearer",Settings.AuthToken);
var response = await client.PostAsync(url, multiContent);
var responsestr = response.Content.ReadAsStringAsync().Result;
await DisplayAlert("Result", responsestr.ToString(), "ok");
}
catch (Exception ex)
{
await DisplayAlert("Result", ex.Message.ToString(), "ok");
}
unfortunately it not working.It not sending the data as I intend.
How can I upload each files as multipart/formdata on a button click.?Any help is appriciated.

You could use MultipartFormDataContent to add multiple images,and use ContentDispositionHeaderValue.Parameters to add the values of your Data.
Usage
var fileStream = pickedFile.GetStream();
var newList = new SelectedDocumentModel()
{
FileName = filename,
SelectedImage = imageSource,
IsLoadingVisible = false,
Path= FilePath,
Data = fileStream ,
};
MultipartFormDataContent multiContent = new MultipartFormDataContent();
foreach(var SelectedDocumentModel model in DataManager)
{
HttpContent fileStreamContent1 = new StreamContent(model.Data);
fileStreamContent1.Headers.ContentDisposition = new
System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
{
Name = "File",
FileName = "xxx.jpg"
};
fileStreamContent1.Headers.ContentType = new
System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
multiContent.Add(fileStreamContent1);
multiContent.Add(new StringContent(model.Title), "model.Title");
multiContent.Add(new StringContent(model.Description), "model.Description");
multiContent.Add(new StringContent(model.Detail), "model.Detail");
}
// Send (url = url of api) ,use httpclient
var response = await client.PostAsync(url, multiContent);

Related

JSON input for Upload function in WebApi C#

I have an upload function in my WebApi C# code, which works fine with Query string parameters. I will be passing the file in Rest client using multi-Form data and it works completely fine.
Now I have to change the parameters to JSON format, doing so the request is not hitting the controller. Can anyone please help me here.
public ReturnMsg UploadDocument(string fileName, string fileSize, string ApplNo, string DocId, string DocSize,string resumeId,string DependId)
{
ReturnMsg objReturnMsg = new ReturnMsg ();
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
Stream stream = null;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = string.Empty;
stream = postedFile.InputStream;
}
objReturnMsg = Bll.UploadFiles(fileName, fileSize, DocId, DocSize,DependId,stream);
}
else
{
objReturnMsg.Status = "F";
objReturnMsg.ReturnMessage = "Please Upload a Valid Form";
}
return objReturnMsg;
}
I want it in
public ReturnMsg UploadDocument(DocDetails docDet)
{
ReturnMsg objReturnMsg = new ReturnMsg ();
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
Stream stream = null;
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = string.Empty;
stream = postedFile.InputStream;
}
objReturnMsg = Bll.UploadFiles(docDet.fileName, docDet.fileSize, docDet.DocId, docDet.DocSize,docDet.DependId,stream);
}
else
{
objReturnMsg.Status = "F";
objReturnMsg.ReturnMessage = "Please Upload a Valid Form";
}
return objReturnMsg;
}

How to use RESTful service in Xamarin.Forms to fetch JSON data

Since I am new to Xamarin, I would really appreciate if someone could explain me how to consume RESTful service (returning JSON data) using Xamarin Forms with the simplest example.
You can use JSON.net and HTTP request, here is a quick example of how to use the movie database which is a free movie database GET and POST examples, hope this helps:
const string _baseUrl = "http://api.themoviedb.org/3/";
const string _pageString = "&page=";
//GET Example
public static async Task<ObservableCollection<Movie>> GetTopRatedMoviesAsync(int page = 1)
{
HttpClient client = new HttpClient();
//_apiKey = themoviedb api key, page = page size 1 = first 20 movies;
string topRatedUrl = _baseUrl + "movie/top_rated?" + _apiKey + _pageString + page;
HttpResponseMessage result = await client.GetAsync (topRatedUrl, CancellationToken.None);
if (result.IsSuccessStatusCode) {
try{
string content = await result.Content.ReadAsStringAsync ();
ObservableCollection<Movie> MovieList = GetJsonData(content);
//return a ObservableCollection to fill a list of top rated movies
return MovieList;
}catch(Exception ex){
//Model Error
Console.WriteLine (ex);
return null;
}
}
//Server Error or no internet connection.
return null;
}
static ObservableCollection<Movie> GetJsonData(string content){
JObject jresponse = JObject.Parse (content);
var jarray = jresponse ["results"];
ObservableCollection<Movie> movieList = new ObservableCollection<Movie> ();
foreach (var jObj in jarray) {
Movie newMovie = new Movie();
newMovie.Title = (string)jObj["title"];
newMovie.PosterPath = _baseImgUrl + (string)jObj["poster_path"];
newMovie.HighResPosterPath = _baseImgUrl + (string)jObj["poster_path"];
newMovie.Id = (int)jObj["id"];
newMovie.Overview = (string)jObj["overview"];
newMovie.VoteCount = (double)jObj["vote_count"];
newMovie.ReleaseDate = (DateTime)jObj["release_date"];
newMovie.VoteAverage = (float)jObj["vote_average"];
movieList.Add(newMovie);
}
return movieList;
}
//POST Example:
public static async Task<bool> PostFavoriteMovieAsync(Movie movie)
{
try
{
HttpClient client = new HttpClient();
//_sessionId = string with the movie database session.
string tokenUrl = _baseUrl + "account/id/favorite?" + _apiKey + _sessionId;
string postBody = JsonConvert.SerializeObject(new Favorite{
favorite = !movie.Favorite,
media_id = movie.Id,
});
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.PostAsync (tokenUrl,
new StringContent (postBody, Encoding.UTF8, "application/json"));
if(response.IsSuccessStatusCode)
return true;
else
return false;
}
catch(Exception ex){
Console.WriteLine (ex.Message);
return false;
}
}

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;
}
}

How to upload images to facebook which is selected by using photoChooserTask in windows phone 8?

I am developing a Windows Phone app in which I have to post a photo to facebook. And that particular photo is choosen by using PhotoChooserTask or CameraChooserTask.
Normally, I can post a particular photo successfully, but I am facing problem to post the selected photo. I saw some link like
link
So please if anyone know about the issue please help me out.
Thanx in advance.
EDIT
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
//var parameters1 = new Dictionary<>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
parameters["ContentType"] = "image/png";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
string imageName = "ic_launcher.png";
StreamResourceInfo sri = null;
Uri jpegUri = new Uri(imageName, UriKind.Relative);
sri = Application.GetResourceStream(jpegUri);
try
{
byte[] imageData = new byte[sri.Stream.Length];
sri.Stream.Read(imageData, 0, System.Convert.ToInt32(sri.Stream.Length));
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = imageName,
ContentType = "image/jpg"
};
fbUpload.SetValue(imageData);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Tribute";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1 + "\n" + d + "\n" + memoType + "\n" + message1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
//client.PostTaskAsync("me/photos", parameters1);
}
On clicking on a button I am calling PostClicked class and it will directly go to facebook mainpage and it will ask for login information. Like this I am doing.
Please check it out
Now I can share a photo to facebook successfully by using photochoosertask or cameratask.
I am sharing my experience so that if anyone face the same issue can use it.
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
SaveImageToIsolatedStorage(image, tempJPEG);
this.image.Source = image;
}
public void SaveImageToIsolatedStorage(BitmapImage image, string fileName)
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
isolatedStorage.DeleteFile(fileName);
var fileStream = isolatedStorage.CreateFile(fileName);
if (image != null)
{
var wb = new WriteableBitmap(image);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
}
fileStream.Close();
}
}
With this you can able to save the selected image to IsolatedStorage.
And then at the time of posting the photo to facebook you have to select the image from IsolatedStorage.
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
try
{
byte[] data;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read))
{
data = new byte[fileStream.Length];
fileStream.Read(data, 0, data.Length);
fileStream.Close();
}
}
//MemoryStream ms = new MemoryStream(data);
//BitmapImage bi = new BitmapImage();
//// Set bitmap source to memory stream
//bi.SetSource(ms);
//this.imageTribute.Source = bi;
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = tempJPEG,
ContentType = "image/jpg"
};
fbUpload.SetValue(data);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Notice";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
Thanx to all....
you can do that by two methods :
1) by using mediasharetask in which it will show u all sharing account to which your phone is synced like facebook,gmail,linkdin,twitter,etc : it can be used like like this.
ShareMediaTask shareMediaTask = new ShareMediaTask();
shareMediaTask.FilePath = path;
shareMediaTask.Show();
2) by using facebook sdk. you can get the package from nuget manager and then u can use it to share on facebook.
I hope this might help u.

Get stream from absolute Uri

I'm working with Windows Phone 7 and I have a very difficult problem. Please help me !
I want to get a stream form an absolute uri (from web) of a png image. But GetResourceStream method work only with relative uri. Then I found imagetool form http://imagetools.codeplex.com/ but to now my problem is not still solved.
Could anyone give me a solution ?
How about using HttpWebRequest and HttpWebResponse?
var uri = new Uri("http://chriskoenig.net/wp-content/uploads/2011/04/givecamp_125125_ad.jpg", UriKind.Absolute);
HttpWebRequest request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.BeginGetResponse((ar) =>
{
var response = request.EndGetResponse(ar);
Dispatcher.BeginInvoke(() =>
{
using (var stream = response.GetResponseStream())
{
var image = new BitmapImage();
image.SetSource(stream);
MyImage.Source = image;
}
});
}, null);
Try this simple Code Image stream from Absolute url and store to isolated storage
namespace eQuadrigaWP7
{
public class ItemViewModel : INotifyPropertyChanged
{
private string _imgURL;
public string imgURL
{
get
{
return _imgURL;
}
set
{
if (value != _imgURL)
{
_imgURL = value;
}
}
}
private BitmapImage _Image;
public BitmapImage Iimage
{
get
{
return _Image;
}
set
{
if (value != _Image)
{
_Image = value;
}
}
}
public void LoadIimage()
{
if (this.imgURL == null) throw new Exception("Error equadriga log");
HttpWebRequest downloadthumbnailrequest = (HttpWebRequest)WebRequest.Create(new Uri(this._imgURL)); ///this is main
DownloadThumbNailState thumbnailState = new DownloadThumbNailState();
thumbnailState.AsyncRequest = downloadthumbnailrequest;
downloadthumbnailrequest.BeginGetResponse(new AsyncCallback(HandleThumNailDownLoadResponse),
thumbnailState);
}
private void HandleThumNailDownLoadResponse(IAsyncResult asyncResult)
{
DownloadThumbNailState thumbnailState = (DownloadThumbNailState)asyncResult.AsyncState;
HttpWebRequest downloadthumbnailrequest = (HttpWebRequest)thumbnailState.AsyncRequest;
thumbnailState.AsyncResponse = (HttpWebResponse)downloadthumbnailrequest.EndGetResponse(asyncResult);
Stream imageStream = thumbnailState.AsyncResponse.GetResponseStream();
byte[] b = new byte[imageStream.Length];
imageStream.Read(b,0,Convert.ToInt32(imageStream.Length));
imageStream.Close();
MemoryStream ms = new MemoryStream(b);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(ms);
String tempJPEG = "logo.jpg";
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(tempJPEG))
{
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
WriteableBitmap wb = new WriteableBitmap(bmp);
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
this.Iimage = bmp;
}
});
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
if (null != PropertyChanged)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class DownloadThumbNailState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}
}
}
ItemViewModel imageitem = new ItemViewModel();
imageitem.imgURL = "http://www.yoursite.in/bilder/9780199738663/titel.jpg";
imageitem.LoadIimage();
Try this one,
BitmaiImage bmp=new BitmaiImage();
Image image=new Image();
Uri url = new Uri("http://Ur url", UriKind.Absolute);
HttpWebRequest reqest = (HttpWebRequest)WebRequest.Create(url);
reqest.BeginGetResponse(DownloadImageCallback, reqest);
void DownloadImageCallback(IAsyncResult result)
{
HttpWebRequest req = (HttpWebRequest)result.AsyncState;
HttpWebResponse responce = (HttpWebResponse)req.EndGetResponse(result);
Stream s = responce.GetResponseStream();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
bmp.SetSource(s);
image.Source=bmp;
});
}

Resources