How to create WritebleBitmap from a resource image with C++ for Windows Metro app? - windows-8

I can easily create a BitmapImage from a resource JPG image file using the following code...
Windows::Foundation::Uri^ uri = ref new Windows::Foundation::Uri(L"ms-appx:///Hippo.JPG");
Imaging::BitmapImage^ image = ref new Imaging::BitmapImage(uri);
But WritableBitmap does not take an Uri. I see a SetSource method, but that needs a IRandomaccessStream and not an Uri. And I have no clue how to create one from a JPG file. I searched the net over and over again, but could not find a straight forward answer. Any help would be greatly appreciated.
I want something like this...
Windows::UI::Xaml::Media::Imaging::WriteableBitmap image = ref new Windows::UI::Xaml::Media::Imaging::WriteableBitmap();
image->SetSource(somehowGetRandomAccessStreamFromUri);
But, how do I get the IRandomaccessStream instance from a uri? I started working on C++ Metro app only today, so might be wrong, but I find it to be overly complicated with too much of onion peeling.

In C# you would do something like
var storageFile = await Package.Current.InstalledLocation.GetFileAsync(relativePath.Replace('/', '\\'));
var stream = await storageFile.OpenReadAsync();
var wb = new WriteableBitmap(1, 1);
wb.SetSource(stream);
I think in C++/CX you would do something like this:
#include <ppl.h>
#include <ppltasks.h>
...
Concurrency::task<Windows::Storage::StorageFile^> getFileTask
(Package::Current->InstalledLocation->GetFileAsync(L"Assets\\MyImage.jpg"));
auto getStreamTask = getFileTask.then(
[] (Windows::Storage::StorageFile ^storageFile)
{
return storageFile->OpenReadAsync();
});
getStreamTask.then(
[] (Windows::Storage::Streams::IRandomAccessStreamWithContentType^ stream)
{
auto wb = ref new Windows::UI::Xaml::Media::Imaging::WriteableBitmap(1, 1);
wb->SetSource(stream);
});

Related

With Kotlin write to SD-card on Android

I have read a lot of questions and answers, but are not really satisfied and successful
My Problem: write with Kotlin to a sdcard to a specific directory
Working is
var filenamex = "export.csv"
var patt = getExternalFilesDirs(null)
var path = patt[1]
//create fileOut object
var fileOut = File(path, filenamex)
//create a new file
fileOut.createNewFile()
with getExternalFIlesDirs() I get the external storage and the sdcard. With path = patt[1] i get the adress of my sd-card.
this is
"/storage/105E-XXXX/Android/data/com.example.myApp/files"
This works to write data in this directory.
But I would like to write into an other directory, for example
"/sdcard/myApp"
A lot of examples say, this should work, bit it does not.
So I tried to take
"/storage/105E-XXXX/myApp"
Why doesn't it work? Ist the same beginning of storage /storage/105E-XXXX/, so it is MY sd-card.?
As I mentioned, it works on the sd-card, so it is not a problem of write-permission to the sdcard?
Any idea?
(I also failed with FileOutputStream and other things)
Try Out this..
var filenamex = "export.csv"
var path = getExternalStorageDirectory() + "//your desired folder"
var fileOut = File(path, filenamex)
fileOut.createNewFile()

Power App - generate PDF

I got an assignment to see if I can make power app that will generate some PDF file for end user to see.
After through research on this topic I found out that this is not an easy to achieve :)
In order to make power app generate and download/show generated pdf I made these steps:
Created power app with just one button :) to call Azure function from step 2
Created Azure function that will generate and return pdf as StreamContent
Due to power app limitations (or I just could not find the way) there was no way for me to get pdf from response inside power app.
After this, I changed my Azure function to create new blob entry but know I have problem to get URL for that new entry inside Azure function in order to return this to power app and then use inside power app Download function
My Azure function code is below
using System;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using Aspose.Words;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log, Stream outputBlob)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
var dataDir = #"D:/home";
var docFile = $"{dataDir}/word-templates/WordAutomationTest.docx";
var uid = Guid.NewGuid().ToString().Replace("-", "");
var pdfFile = $"{dataDir}/pdf-export/WordAutomationTest_{uid}.pdf";
var doc = new Document(docFile);
doc.Save(pdfFile);
var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(pdfFile, FileMode.Open);
stream.CopyTo(outputBlob);
// result.Content = new StreamContent(stream);
// result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
// result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(pdfFile);
// result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
// result.Content.Headers.ContentLength = stream.Length;
return result;
}
I left old code (the one that streams pdf back under comments just as reference of what I tried)
Is there any way to get download URL for newly generated blob entry inside Azure function?
Is there any better way to make power app generate and download/show generated PDF?
P.S. I tried to use PDFViewer control inside power app, but this control is completely useless cause U can not set Document value via function
EDIT: Response from #mathewc helped me a lot to finally wrap this up. All details are below.
New Azure function that works as expected
#r "Microsoft.WindowsAzure.Storage"
using System;
using System.Net;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using Aspose.Words;
using Microsoft.WindowsAzure.Storage.Blob;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log, CloudBlockBlob outputBlob)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
var dataDir = #"D:/home";
var docFile = $"{dataDir}/word-templates/WordAutomationTest.docx";
var uid = Guid.NewGuid().ToString().Replace("-", "");
var pdfFile = $"{dataDir}/pdf-export/WordAutomationTest_{uid}.pdf";
var doc = new Document(docFile);
doc.Save(pdfFile);
var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(pdfFile, FileMode.Open);
outputBlob.UploadFromStream(stream);
return req.CreateResponse(HttpStatusCode.OK, outputBlob.Uri);
}
REMARKS:
Wee need to add "WindowsAzure.Storage" : "7.2.1" inside project.json. This package MUST be the same version as one with same name that is in %USERPROFILE%\AppData\Local\Azure.Functions.Cli
If you change your blob output binding type from Stream to CloudBlockBlob you will have access to CloudBlockBlob.Uri which is the blob path you require (documentation here). You can then return that Uri back to your Power App. You can use CloudBlockBlob.UploadFromStreamAsync to upload your PDF Stream to the blob.

Winrt StreamWriter & StorageFile does not completely Overwrite File

Quick search here yielded nothing. So, I have started using some rather roundabout ways to use StreamWriter in my WinRT Application. Reading works well, writing works differently. What' I'm seeing is that when I select my file to write, if I choose a new file then no problem. The file is created as I expect. If I choose to overwrite a file, then the file is overwritten to a point, but the point where the stream stops writing, if the original file was large, then the old contents exist past where my new stream writes.
The code is as such:
public async void WriteFile(StorageFile selectedFileToSave)
{
// At this point, selectedFileToSave is from the Save File picker so can be a enw or existing file
StreamWriter writeStream;
Encoding enc = new UTF8Encoding();
Stream dotNetStream;
dotNetStream = await selectedFileToSave.OpenStreamForWriteAsync();
StreamWriter writeStream = new StreamWriter(dotNetStream, enc);
// Do writing here
// Close
writeStream.Write(Environment.NewLine);
await writeStream.FlushAsync();
await dotNetStream.FlushAsync();
}
Can anyone offer clues on what I could be missing? There are lots of functions missing in WinRT, so not really following ways to get around this
Alternatively you can set length of the stream to 0 with SetLength method before using StreamWriter:
var stream = await file.OpenStreamForWriteAsync();
stream.SetLength(0);
using (var writer = new StreamWriter(stream))
{
writer.Write(text);
}
Why not just use the helper methods in FileIO class? You could call:
FileIO.WriteTextAsync(selectedFileToSave, newTextContents);
If you really need a StreamWriter, first truncate the file by calling
FileIO.WriteBytesAsync(selectedFileToSave, new byte[0]);
And then continue with your existing code.

Do I need to call CachedFileManager.DeferUpdates in Windows 8 app

In the file picker Windows 8 sample a file is saved like this:
CachedFileManager.DeferUpdates(file);
await FileIO.WriteTextAsync(file, stringContent);
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
I'm serialising an object as XML so doing it slightly differently:
// CachedFileManager.DeferUpdates(file);
var ras = await file.OpenAsync(FileAccessMode.ReadWrite);
var outStream = ras.GetOutputStreamAt(0);
var serializer = new XMLSerializer();
serializer.Write(myObject, outStream);
// FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
It works with or without the CachedFileManager (commented out above).
So, should I include the CachedFileManager and if I do use it am I saving the file in the right way.
This code works and saves the file fine, but I don't like including code that I don't understand.
Yes, this code will work without CachedFileManager. But, when you use CachedFileManager, you inform the file provider that the file is in process of change. If your file is located on SkyDrive it is faster to create a file and upload it at once instead of update it multiple times.
You can have the full story there : http://www.jonathanantoine.com/2013/03/25/win8-the-cached-file-updater-contract-or-how-to-make-more-useful-the-file-save-picker-contract/
It simply tells the "repository" app to upload the file.

How to give the option to change the Textbloack foreground-color,size in Windowsphone7

I am completely new in Windowsphone7.i have develop sample application in that i want give the option to change the font-color,Size,style(Italic/Bold) as Dynamically(like RadEditor) .please help me how to resolve this option.
If you Develop your Application MVVM style then it is not so hard to do this. You just need a property for every setting you want to set dynamically and then bind to this properties. And you create a Settings View where you can set the properties and if you change them you use INotifyPropertyChanged to broadcast that your properties value changed and so every control which is bound to that property will change and redraw.
GalaSoft MVVM
MVVM Codeplex
Easy MVVM sample Application for Windows Phone 7
The link you found to save an image looks ok, but i did it a bit different, actually from the CameraCaptureTask you already get a WritableBitmap Image and you can save it like this.
To save the Image:
private void SaveToIsolatedStorage(WriteableBitmap image, string fileName)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(fileName))
{
myIsolatedStorage.DeleteFile(fileName);
}
using (var stream = myIsolatedStorage.OpenFile(fileName, FileMode.Create))
{
Extensions.SaveJpeg(image, stream, image.PixelWidth, image.PixelHeight,0, 100);
}
}
}
To read the Image:
private WritableBitmap ReadFromIsolatedStorage(string fileName)
{
WriteableBitmap bitmap = new WriteableBitmap(200,200);
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists(fileName))
{
using (var stream = store.OpenFile(fileName,FileMode.Open))
{
bitmap.SetSource(stream);
}}
}
return bitmap;
}
I hope this will work because i wrote it from scratch. :)
And in your ViewModel you should have a WritableBitmap Property which is bound to your Image Control on your View.
To use a lot of images and work with them you should read a bit more about this, because somehow SL Images use a lot of memory so you will need to address this problem somehow in the future.