Download and save .pdf file in Documents/Download Folder - WP8 Silverlight - silverlight

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!

Related

How to send file with http

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

iTextSharp image stretching not proportional

I am using Telerik RadRadialGauge and I need to export it to pdf like a picture.
On my GUI the control looks normal
When I try to export it to pdf it is resized not proportionally.
All other elements look good.
using (var ms = new MemoryStream())
{
var document = new Document(PageSize.LETTER, 0, 0, 0, 0);
PdfWriter.GetInstance(document, new FileStream(pdfFile, FileMode.Create));
PdfWriter.GetInstance(document, ms).SetFullCompression();
document.Open();
FileStream fs = new FileStream(imageFile1, FileMode.Open);
var image = iTextSharp.text.Image.GetInstance(fs);
image.ScalePercent(80);
// image.ScaleToFit(document.PageSize.Width , document.PageSize.Height);
// image.ScaleAbsolute(document.PageSize.Width , document.PageSize.Height));
document.Add(image);
}
Here the code to save all the data from GUI as png file.
private void SaveAsPng(RenderTargetBitmap src, string targetFile)
{
try
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(src));
using (var stm = File.Create(targetFile))
{
encoder.Save(stm);
}
}
catch (Exception)
{
... }
}

How to Open Files from MemoryStream in C#?

I have saved the files to database. These files may be of type Doc, PDF or Image. Now I'm trying to open these files from a DataGridView Cell_Click event using this code.
private void dgvDocuments_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == dgvDocuments.Columns[0].Index)
{
int id =Convert.ToInt32(dgvDocuments.Rows[e.RowIndex].Cells[1].Value);
string query = "SELECT Photo FROM [dbo].[tblHR_Emloyee_Documents] WHERE ID = " + id;
Utility.Generate_Window_Control.databaseFileRead(query);
}
}
public static MemoryStream databaseFileRead(string query)
{
MemoryStream memoryStream = new MemoryStream();
using (var varConnection = new SqlConnection(Utility.Global_Connection.conn))
using (var sqlQuery = new SqlCommand(query, varConnection))
{
varConnection.Open();
using (var sqlQueryResult = sqlQuery.ExecuteReader())
if (sqlQueryResult != null)
{
sqlQueryResult.Read();
var blob = new Byte[(sqlQueryResult.GetBytes(0, 0, null, 0, int.MaxValue))];
sqlQueryResult.GetBytes(0, 0, blob, 0, blob.Length);
//using (var fs = new MemoryStream(memoryStream, FileMode.Create, FileAccess.Write)) {
memoryStream.Write(blob, 0, blob.Length);
//}
}
}
return memoryStream;
}
During debug it shows me no error. Values are correct. But It is not opening the files. Kindly guide me how can I do this?

how to map StreamResourceinfo to a absolute URL

I am using the below snipped to save an audio file in the isolated storage. but the exception occurs when streamresourceinfo mapped to a absoluteUri. The uri accepts only the relative uri. Please guide me how to save the audio file using absolute Uri.
private void SaveMp3()
{
string FileName = "Audios/Deer short.mp3";
FileName = "http://www.ugunaflutes.co.uk/Deer short.mp3";
StreamResourceInfo streamResourceInfo = Application.GetResourceStream(new Uri(FileName, UriKind.RelativeOrAbsolute));
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(FileName))
{
myIsolatedStorage.DeleteFile(FileName);
}
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("Audio.png", FileMode.Create, myIsolatedStorage))
{
using (BinaryWriter writer = new BinaryWriter(fileStream))
{
Stream resourceStream = streamResourceInfo.Stream;
long length = resourceStream.Length;
byte[] buffer = new byte[32];
int readCount = 0;
using (BinaryReader reader = new BinaryReader(streamResourceInfo.Stream))
{
// read file in chunks in order to reduce memory consumption and increase performance
while (readCount < length)
{
int actual = reader.Read(buffer, 0, buffer.Length);
readCount += actual;
writer.Write(buffer, 0, actual);
}
}
}
}
}
}
Thanks in advance.
You can't use Application.GetResourceStream to load an external resource, because URI must to be relative to the application package http://msdn.microsoft.com/en-us/library/ms596994(v=vs.95).aspx.
You need to use WebClient.OpenReadAsync to download your mp3 file and after save it locally to IsolatedStorage, peace of example:
var webClient = new WebClient();
webClient.OpenReadCompleted += (sender, args) =>
{
if (args.Error != null)
{
//save file here
}
};
webClient.OpenReadAsync(new Uri("http://www.ugunaflutes.co.uk/Deer short.mp3"));

Unable to send Stream but able to send string to Restful service from Windows Phone 7?

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

Resources