I write a Datetime string in a file and after that try to read it back, but string returns interlaced with zero characters. WP Power tools show string intact "18.02.2015 12:08:17". But after reading it looks like:
"1\08\0.\00\02\0.\02\00\01\05\0 \01\02\0:\00\08\0:\01\07\0"
await FileExtensions.WriteDataToFileAsync("scheduleDateTime.txt", scheduleTime);
var contents = await FileExtensions.ReadFileContentsAsync("scheduleDateTime.txt");
public static async Task<String> ReadFileContentsAsync(string fileName)
{
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
if (local != null)
{
var file = await local.OpenStreamForReadAsync(fileName);
using (StreamReader streamReader = new StreamReader(file))
{
return streamReader.ReadToEnd();
}
}
else
{
return String.Empty;
}
}
public static async Task WriteDataToFileAsync(string fileName, string content)
{
byte[] data = Encoding.Unicode.GetBytes(content);
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (var s = await file.OpenStreamForWriteAsync())
{
await s.WriteAsync(data, 0, data.Length);
}
}
You're saving the file by using UTF-16 encoding, but reading it back using the default encoding (that is, UTF-8). You need to use the same encoding for both case.
Usually, the recommandation is to use UTF-8 to read and write in files, so you need to change your WriteDataToFileAsync method:
public static async Task WriteDataToFileAsync(string fileName, string content)
{
byte[] data = Encoding.UTF8.GetBytes(content);
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (var s = await file.OpenStreamForWriteAsync())
{
await s.WriteAsync(data, 0, data.Length);
}
}
Related
I am trying from a .net client to download a file via a .net server (file is located on server machine ) using the StreamContent.However when launching the request i am getting the exception:
Exception
Stream does not support reading.
Client
class Program {
static async Task Main(string[] args) {
HttpClient client = new HttpClient();
using (FileStream stream = new FileStream("txt.path", FileMode.OpenOrCreate, FileAccess.Write)) {
var content = new StreamContent(stream);
var response = await client.PostAsync("http://localhost:5300/get", content);
}
}
}
Server
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
string fname = "dld.txt";
app.Run(async (context) => {
if (!(context.Request.Path == "get")) {
return;
}
File.WriteAllText(fname, "data is:" + DateTime.Now.ToString());
FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
using (Stream stream = context.Response.Body) {
await fs.CopyToAsync(stream);
}
});
}
Hi you can use like this:
HttpContent stringContent = new StringContent(paramString); //if you want to use string
HttpContent fileStreamContent = new StreamContent(paramFileStream); //if you want to use file stream
HttpContent bytesContent = new ByteArrayContent(paramFileBytes);// if you want to use aray of bytes
using (var client = new HttpClient())
{
using (var formData = new MultipartFormDataContent())
{
formData.Add(stringContent, "param", "param");
formData.Add(fileStreamContent, "file", "file");
formData.Add(bytesContent, "file", "file");
var response = await client.PostAsync("some URL", formData);
if (!response.IsSuccessStatusCode)
{
return null;
}
return await response.Content.ReadAsStreamAsync();
}
}
I was having trouble getting the file because i wanted to use the Request.Body stream as a sink.I wanted the server to write the data on this stream (i thought the Request stream can be used both ways).
I have solved it by using the Response stream instead:
Client
static async Task Main(string[] args) {
HttpClient client = new HttpClient();
using (FileStream stream = new FileStream("data.txt", FileMode.OpenOrCreate, FileAccess.Write)) {
var content = new StringContent("not important");
var response = await client.PostAsync("http://localhost:5300/get",content);
await response.Content.CopyToAsync(stream);
}
}
I need to capture an image from my camera using xamarin.forms portable, and obtain access to the image byte[] data for image processing purposes.
How can this be done?
I have the working code that captures the image and simply shows it, using xlabs
public async Task<MediaFile> TakePicture()
{
Setup ();
ImageSource = null;
return await _Mediapicker.TakePhotoAsync (new CameraMediaStorageOptions {
DefaultCamera = CameraDevice.Front, MaxPixelDimension = 400
}).ContinueWith (t => {
if (t.IsFaulted)
{
Status = t.Exception.InnerException.ToString();
}
else if (t.IsCanceled)
{
Status = "Canceled";
}
else
{
MediaFile mediaFile = t.Result;
ImageSource = ImageSource.FromStream(() => mediaFile.Source);
return mediaFile;
}
return null;
}, _scheduler);
}
and
private async void buttonTakePicture_Clicked() {
await cameraViewModel.TakePicture();
imageView.Source = cameraViewModel.ImageSource;
}
clicking the button launches cameraViewModel.TakePicture() which in turn uses xlabs to actually take the picture on the device.
How can I alter the code to also give me the image raw data (or use a different code altogether)?
Thanks
You can take mediaFile.Path and pass it as a parameter for a DependencyService:
//For Android
public byte[] ByteArrayFromStream(string path)
{
var bitmap = BitmapFactory.DecodeFile(path);
byte[] bitmapData;
using(stream = new MemoryStream())
{
bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
bitmapData = stream.ToArray();
}
return bitmapData;
}
//For iOS
public byte[] ByteArrayFromStream(string path)
{
UIImage originalImage = UIImage.FromFile(path);
return originalImage.AsPNG().ToArray();
}
To learn more about DependencyService you can access the documentation at:
https://developer.xamarin.com/guides/xamarin-forms/dependency-service/
This will help you to get byte[ ] in PCL :
public async Task<MediaFile> TakePicture()
{
Setup ();
ImageSource = null;
return await _Mediapicker.TakePhotoAsync (new CameraMediaStorageOptions {
DefaultCamera = CameraDevice.Front, MaxPixelDimension = 400
}).ContinueWith (t => {
if (t.IsFaulted)
{
Status = t.Exception.InnerException.ToString();
}
else if (t.IsCanceled)
{
Status = "Canceled";
}
else
{
MediaFile mediaFile = t.Result;
using (MemoryStream ms = new MemoryStream())
{
mediaFile.Source.CopyTo(ms);
byte[] attchmentbytes = ms.ToArray();
}
ImageSource = ImageSource.FromStream(() => mediaFile.Source);
return mediaFile;
}
return null;
}, _scheduler);
}
Direct to the point: I want to download and save a .pdf file so that the user can see it later in the Media Library.
I'm looking for a way to achieve this in Windows Phone 8 Silverlight.
Here is the code I'm using right now:
private void DownloadPDF(string url)
{
var client = new WebClient();
client.OpenReadCompleted += client_OpenReadCompleted;
this.FileName = Path.GetFileName(url);
client.OpenReadAsync(new Uri(url));
}
async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
// Save file:
var buffer = new byte[e.Result.Length];
await e.Result.ReadAsync(buffer, 0, buffer.Length);
using (var storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = storageFile.OpenFile(this.FileName, FileMode.Create))
{
await stream.WriteAsync(buffer, 0, buffer.Length);
}
}
// Open file:
var local = ApplicationData.Current.LocalFolder;
var pdffile = await local.GetFileAsync(this.FileName);
Windows.System.Launcher.LaunchFileAsync(pdffile);
var progressIndicator = new ProgressIndicator()
{
IsVisible = false
};
SystemTray.SetProgressIndicator(this, progressIndicator);
}
Thank you very much!
I have been trying to send a image to restful service and some data with it. But i can send data (Name and Description of image) and also i created sql database to store data and data is added on it but i can't send image to the server.
the code for service:
[WebInvoke(UriTemplate = "UploadPhoto/{fileName}/{description}", Method = "POST")]
public void UploadPhoto(string fileName, string description, Stream fileContents)
{
byte[] buffer = new byte[32768];
MemoryStream ms = new MemoryStream();
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileContents.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
ms.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
// Save the photo on database.
using (DataAcess data = new DataAcess())
{
var photo = new Photo() { Name = fileName, Description = description, Data = ms.ToArray(), DateTime = DateTime.UtcNow, };
data.InsertPhoto(photo);
}
ms.Close();
Console.WriteLine("Uploaded file {0} with {1} bytes", fileName, totalBytesRead);
}
And this is my code on client side. I am doing it on windows phone 7.
void btnNewPhoto_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("http://localhost:2557/photos");
string requestUrl = string.Format("{0}/UploadPhoto/{1}/{2}", uri, System.IO.Path.GetFileName(txtFileName.Text), txtDescription.Text);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.BeginGetRequestStream
(result =>
{
// Sending the request.
using (var requestStream = request.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
BinaryReader reader = new BinaryReader(requestStream);
string s = imgPhoto.ToString();
byte[] byteArray = Encoding.UTF8.GetBytes(s.ToString());
requestStream.Write(byteArray, 0, byteArray.Length);
requestStream.Close();
requestStream.Dispose();
//writer.Write(requestUrl);
//writer.Flush();
}
}
// Getting the response.
request.BeginGetResponse(responseResult =>
{
var webResponse = request.EndGetResponse(responseResult);
using (var responseStream = webResponse.GetResponseStream())
{
using (var streamReader = new StreamReader(responseStream))
{
string srresult = streamReader.ReadToEnd();
}
}
}, null);
}, null);
}
I have a utility that allows the user to take a camera photo and upload it, in addition to another option to upload a file. I've got most of it working, except for the part where I have to convert the webcam image to a jpg prior to upload. The code below has no error but produces invalid image data:
void CaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
{
busyIndicator.IsBusy = true;
stopCapture();
capturedImage.ImageSource = e.Result;
ImageTools.ExtendedImage eimg = e.Result.ToImage();
var encoder = new ImageTools.IO.Jpeg.JpegEncoder();
Stream stream = eimg.ToStreamByExtension("jpg");
//DO THIS LATER
//if (stream.Length > 512000)
//{
// eimg = ExtendedImage.Resize(eimg, 240, new NearestNeighborResizer());
// stream = eimg.ToStreamByExtension("jpg");
//}
encoder.Encode(eimg, stream);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(stream);
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
// picture file a class object to be used by uploader
pictureFile.PictureName = "webcam.jpg"; // name will be changed later
pictureFile.PictureStream = bytes;
HtmlPage.Window.Invoke("gotDetails_WebCam", ""); // post page, then come back and do upload
}
Here is what PictureFile looks like:
[DataContract]
public class PictureFile
{
[DataMember]
public string PictureName { get; set; }
[DataMember]
public byte[] PictureStream { get; set; }
}
Can anyone figure out what I'm doing wrong to produce the bytes needed for a jpeg?
good to see that you solved,
here is my running code,
I use png format,there is also file size check.
Maybe it helps s.one else.
dSrvPR is my Domain Service Class instance
photo is an entity object in my EF.
_captureSource.CaptureImageCompleted += ((s, args) =>
{
if (dSrvPR.PR_PATIENTPHOTOs.Count > 0 && photo != null)
{
dSrvPR.PR_PATIENTPHOTOs.Remove(photo);
}
dSrvPR.PR_PATIENTPHOTOs.Clear();
photo = new PR_PATIENTPHOTO();
ImageTools.ExtendedImage eimg=args.Result.ToImage();
var encoder=new ImageTools.IO.Png.PngEncoder();
Stream stream= eimg.ToStreamByExtension("png");
if (stream.Length > 512000)
{
eimg= ExtendedImage.Resize(eimg, 240, new NearestNeighborResizer());
stream = eimg.ToStreamByExtension("png");
}
if (stream.Length <= 512001)
{
BinaryReader binary = new BinaryReader(stream);
//Read bytes from the BinaryReader and put them into a byte array.
Byte[] file = binary.ReadBytes((int)stream.Length);
photo.ID = Guid.NewGuid();
photo.PHOTO = file;
photo.PHOTODATE = DateTime.Now;
photo.ISACTIVE = true;
//some more unrelated fields
dSrvPR.PR_PATIENTPHOTOs.Add(photo);
dSrvPR.SubmitChanges();
//Msg succedded
}
else
{
Util.alert(...,"file size exceeded! :)";
}
});
My mistake. It seems I had some extra code in there (unnecessarily converting stream to bitmap). Here is what I got working:
void CaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
{
busyIndicator.IsBusy = true;
stopCapture();
capturedImage.ImageSource = e.Result;
ImageTools.ExtendedImage eimg = e.Result.ToImage();
var encoder = new ImageTools.IO.Jpeg.JpegEncoder();
Stream stream = eimg.ToStreamByExtension("jpg");
byte[] bytes = new byte[stream.Length];
stream.Read(bytes, 0, (int)stream.Length);
// picture file a class object to be used by uploader
pictureFile.PictureName = "webcam.jpg"; // name will be changed later
pictureFile.PictureStream = bytes;
HtmlPage.Window.Invoke("gotDetails_WebCam", ""); // post page, then come back and do upload
}