Get a uri from a LocalStorage in Windows Phone - windows-phone-8

I write the following code to save some images from internet:
public static async Task SaveImage(string name, string uri)
{
var localfolder = ApplicationData.Current.LocalFolder;
var client = new HttpClient();
var imageStream = await client.GetStreamAsync(uri); //Secuencia de bytes
var storageFile = await localfolder.CreateFileAsync(name, CreationCollisionOption.ReplaceExisting);
using (Stream outputStream = await storageFile.OpenStreamForWriteAsync())
{
await imageStream.CopyToAsync(outputStream);
}
}
My problem is when I try to set these images store in the Local Storage to a CycleTile because this class needs the Uri's, and I don't know how to provide the uri here. This is what I have:
CycleTileData cycleicon = new CycleTileData();
cycleicon.Title = "Fotopantalla";
cycleicon.Count = 0;
cycleicon.SmallBackgroundImage = new Uri("/Assets/Tiles/FlipCycleTileSmall.png", UriKind.RelativeOrAbsolute);
List<Uri> images = new List<Uri>();
for (int i = 0; i < 9; i++)
{
/// tries...
string path1 = "ms-appdata:///local/image" + i + ".jpg";
string path2 = "isostore:/Shared/ShellContent/image" + i + ".jpg";
string path3 = "ms-appdata:///Local/Shared/ShellContent/image" + i + ".jpg";
///
Uri uri = new Uri(path2, UriKind.RelativeOrAbsolute);
images.Add(uri);
}
cycleicon.CycleImages = images;
What am I wrong or what am I missing?

For any ShellTileData related data structures you have to use path2:
"isostore:/Shared/ShellContent/*" if the images are not in the (read only) InstalledLocation folder.
For more details see: http://blogs.msdn.com/b/andy_wigley/archive/2013/04/10/live-apps-creating-custom-tile-and-lock-screen-images.aspx
I have something similar in my code:
var store = IsolatedStorageFile.GetUserStoreForApplication();
if (!store.DirectoryExists("Shared/ShellContent"))
{
store.CreateDirectory("Shared/ShellContent");
}
StorageFolder shellContent = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("Shared", CreationCollisionOption.OpenIfExists);
shellContent = await shellContent.CreateFolderAsync("ShellContent", CreationCollisionOption.OpenIfExists);
Stream imgin = picture.GetImage();
//Picture read stream from Media Library or other input stream
StorageFile new_img = await shellContent.CreateFileAsync(newPictureName);
Stream imgout = await new_img.OpenStreamForWriteAsync();
imgin.CopyTo(imgout);
imgout.Close(); // <- necessary in your code or not?
imgin.Close(); // <-
I'm not sure, whether you really need the Isostore thing at the beginning, but it works, if I haven't done some stupid mistake while shortening the code. ;-)
Also have a look at "StandardTileData.BackgroundImage Property", "Data for Windows Phone" and "How to use the Isolated Storage Explorer tool for Windows Phone" from Microsoft's Dev Center. (The last one is about how to have a look at the saved image file on your device.)

Related

getUserMedia and mediarecorder in html

I record audio via getUserMedia and mediarecorder:
...
navigator.mediaDevices.getUserMedia(constraints).then(mediaStream => {
try {
const mediaRecorder = new MediaRecorder(mediaStream);
mediaRecorder.ondataavailable = vm.mediaDataAvailable;
mediaRecorder.start(1000);
...
When I receive the chucks in the callback, I send them to a web api via websockets, which simply writes the parts one after another to a file:
mediaDataAvailable(e) {
if (!event.data || event.data.size === 0)
{
return;
}
vm.websocket.SendBlob(e.data);
...
The file, which is created on the webserver side in the webapi (lets call it "server.webm"), does not work correct. More exactly: It plays the first n seconds (n is the time I chose for the start command), the it stops. This means, the first chunk is transferred correctly, but it seams that adding the 2nd, 3rd, ... chuck together to a file does not work. If I push the chuncks in the web page on an array and the to a file, the resulting file (lets call it "client.webm") is working the whole recording duration.
Creating file on web client side:
mediaDataAvailable(e) {
if (!event.data || event.data.size === 0)
{
return;
}
vm.chuncks.push(e.data);
...
stopCapturing() {
var blob = new Blob(this.chuncks, {type: 'audio/webm'});
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = 'client.webm';
document.body.appendChild(a);
a.click();
I compared the files client.webm and server.webm. They are quite similar, but there are certain parts in the server.webm which are not in the client.webm.
Anybody any ideas? Server code looks like the following:
private async Task Echo( HttpContext con, WebSocket webSocket)
{
System.IO.BinaryWriter Writer = new System.IO.BinaryWriter(System.IO.File.OpenWrite(#"server.webm"));
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
Writer.Write(buffer);
Writer.Flush();
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
Writer.Close();
}
resolved, I write all bytes of the reserved byte array to file in server code, not the count of received bytes.

Download Azure Blob image to memorystream in Windows Phone 8.1

The code below will copy an image file from Azure blob storage, and create a new image file locally. This local image will then be added to a List for further databinding to the XAML UI.
string accountName = "testacc";
string accountKey = "123abc";
string container = "textcontainer";
List<Mydata> items = new List<Mydata>();
BitmapImage bitmapToShow = new BitmapImage();
StorageCredentials creds = new StorageCredentials(accountName, accountKey);
CloudStorageAccount acc = new CloudStorageAccount(creds, useHttps: true);
CloudBlobClient cli = acc.CreateCloudBlobClient();
CloudBlobContainer sampleContainer = cli.GetContainerReference(container);
CloudBlockBlob blob = sampleContainer.GetBlockBlobReference("xbox.jpg");
// Here I need to copy the data stream directely to the BitmapImage instead of creating a file first
StorageFile photoFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("temp_image.jpg", CreationCollisionOption.ReplaceExisting);
await blob.DownloadToFileAsync(photoFile);
bitmapToShow = new BitmapImage(new Uri(photoFile.Path));
items.Add(new Mydata() { image = bitmapToShow });
DataBinding.ItemsSource = items;
The code below will copy an image file from Azure blob storage, and create a new image file locally. This local image will then be added to a List for further databinding to the XAML UI.
Hovewer - in order to get more efficient, I am looking for a way to avoid creating the image file locally first. I am looking for a way where the image file in the Azure blob storage are copied to a MemoryStream and then passed directely into a BitmapImage.
I have not fiugred out to code that myself, and the code snippets I have not found, do not work for Windows Phone 8.1. I am programming in C# for Windows Phone 8.1 Universal App (not Silverlight).
Can someone help me with the code needed to get that functionality?
Would this work?
Stream photoStream = await blob.DownloadToStreamAsync(photoFile)
bitmapToShow = new BitmapImage(photoStream);
Hope it helps,
Drew
I found that this Works. It might not be perfect, but it Works. Comments or corrections are welcome.
string accountName = "testacc";
string accountKey = "123abc";
string container = "textcontainer";
List<Mydata> items = new List<Mydata>();
BitmapImage bitmapToShow = new BitmapImage();
InMemoryRandomAccessStream memstream = new InMemoryRandomAccessStream();
StorageCredentials creds = new StorageCredentials(accountName, accountKey);
CloudStorageAccount acc = new CloudStorageAccount(creds, useHttps: true);
CloudBlobClient cli = acc.CreateCloudBlobClient();
CloudBlobContainer sampleContainer = cli.GetContainerReference(container);
CloudBlockBlob blob = sampleContainer.GetBlockBlobReference("xbox.jpg");
await blob.DownloadToStreamAsync(memstream.CloneStream());
bitmapToShow.SetSource(memstream);
items.Add(new Mydata() { image = bitmapToShow });
DataBinding.ItemsSource = items;

How to POST a string and an image in one request using HttpClient?

I have a string and an image I need to POST to a web server using the HttpClient in the Windows Runtime.
How can I post two things in one request using the HttpClient?
Easy! Try this:
using Windows.Web.Http;
using Windows.Web.Http.Headers;
private async void Foo()
{
// the image
var fileStream = await file.OpenReadAsync();
var streamContent = new HttpStreamContent(fileStream);
var filename = "myImage.png";
// the text
var text = "oompa loompas";
var stringContent = new HttpStringContent(text);
// Putting all together.
var formDataContent = new HttpMultipartFormDataContent();
formDataContent.Add(streamContent, "myImage", fileName);
formDataContent.Add(stringContent, "myString");
// Send it to the server.
var response = await (new HttpClient()).PostAsync(uri, formDataContent);
}
For posting a string
HttpClient client = new HttpClient();
HttpContent content = new StringContent(contentstring);
client.PostAsync(url, content);
For posting an image convert Image to stream and stream to string and the then httpcontent.

QrCode Open Source Library for WinRT

I need to generate the Qr Code for my Windows 8 Store App.Is there any Open Source Qr Code Library which is based on Win Rt.
I have made use of zxing library which is available on codeplex.
The method I wrote is as follows:
I'm making use of the DecodeQRcode with storage file from the camera's CaptureFileAsync method which returns the storage file of the qrImgage.
public async void DecodeQRCode(StorageFile file)
{
// load a jpeg, be sure to have the Pictures Library capability in your manifest
var data = await FileIO.ReadBufferAsync(file);
// create a stream from the file
var ms = new InMemoryRandomAccessStream();
var dw = new Windows.Storage.Streams.DataWriter(ms);
dw.WriteBuffer(data);
await dw.StoreAsync();
ms.Seek(0);
// find out how big the image is, don't need this if you already know
var bm = new BitmapImage();
await bm.SetSourceAsync(ms);
// create a writable bitmap of the right size
var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
ms.Seek(0);
// load the writable bitpamp from the stream
await wb.SetSourceAsync(ms);
var lsource = new BitmapLuminanceSource(wb);
var binarizer = new HybridBinarizer(lsource);
var bbmp = new BinaryBitmap(binarizer);
var c = new QRCodeReader();
Result res= c.decode(bbmp);
}
While taking the image of the QR code you must make sure that you crop the image properly or else you won't get the expected result.
I have not used this, but ZXing.Net is....
A library which supports decoding and generating of barcodes (like QR
Code, PDF 417, EAN, UPC, Aztec, Data Matrix, Codabar) within images.
and has assembles available for WindowsRT (as well as phone)
You can use the ZXing.NET: https://zxingnet.codeplex.com/
Code for load image to get QR Code result:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".bmp");
StorageFile file = await openPicker.PickSingleFileAsync();
if (null != file)
{
try
{
BitmapImage bitmap = new BitmapImage();
using (IRandomAccessStream fileStream1 = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
bitmap.SetSource(fileStream1);
}
using (IRandomAccessStream fileStream2 = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);
writeableBitmap.SetSource(fileStream2); IBarcodeReader reader = new BarcodeReader();
var result = reader.Decode(writeableBitmap);
txt1.Text = result.ToString();
}
}
catch (Exception exception)
{
//
}
}
Code for get QR from camera (use the MSDN demo: http://code.msdn.microsoft.com/windowsapps/CameraCaptureUI-Sample-845a53ac and customized):
private async void CapturePhoto_Click(object sender, RoutedEventArgs e)
{
try
{
rootPage.NotifyUser("", NotifyType.StatusMessage);
// Using Windows.Media.Capture.CameraCaptureUI API to capture a photo
CameraCaptureUI dialog = new CameraCaptureUI();
Size aspectRatio = new Size(1, 1);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream1 = await file.OpenAsync(FileAccessMode.Read))
{
bitmapImage.SetSource(fileStream1);
}
CapturedPhoto.Source = bitmapImage;
ResetButton.Visibility = Visibility.Visible;
ZXing.BarcodeReader br = new ZXing.BarcodeReader();
WriteableBitmap wrb = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
BitmapImage img = new BitmapImage();
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
using (IRandomAccessStream fileStream2 = await file.OpenAsync(FileAccessMode.Read))
{
wrb.SetSource(fileStream2);
}
var res = br.Decode(wrb);
rootPage.NotifyUser(res.ToString(), NotifyType.ErrorMessage);
}
else
{
rootPage.NotifyUser("No photo captured.", NotifyType.StatusMessage);
}
}
catch (Exception ex)
{
rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
}
}

VersionConflictException when downloading document

I sometimes get a VersionConflictException when trying to download a file from Google Docs. I'm guessing this is harmless but why does this happen?
I'm using gdata-media-1.0-1.41.3.jar
com.google.gdata.util.VersionConflictException: Conflict
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:612)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:552)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:530)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535)
at com.google.gdata.client.media.MediaService.getMediaResource(MediaService.java:234)
at com.google.gdata.client.media.MediaService.getMedia(MediaService.java:276)
at com.google.gdata.client.media.MediaService.getMedia(MediaService.java:302)
The code we are using is as follows:
DocumentListEntry entry = ... // from the feed of changed documents
MediaContent documentContent = (com.google.gdata.data.MediaContent) entry.getContent();
String uri = documentContent.getUri();
MediaContent downloadContent = new MediaContent();
downloadContent.setUri(uri);
MediaSource mediaSource = docsService.getMedia(downloadContent);
InputStream inputStream = mediaSource.getInputStream();
File file = // some file
OutputStream output = new FileOutputStream(file);
try {
IOUtils.copy(inputStream, output);
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(inputStream);
}