get URI of image stored in isolatedstorage - windows-phone-8

i have saved a file named 'logo.jpg' in the isolatedstorage using this code...
private void step2_Click(object sender, RoutedEventArgs e)
{
// Create a filename for JPEG file in isolated storage.
String tempJPEG = "logo.jpg";
// Create virtual store and file stream. Check for duplicate tempJPEG files.
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(tempJPEG))
{
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
try
{
WriteableBitmap wb = new WriteableBitmap(img);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
}
catch { }
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
NavigationService.Navigate(new Uri("/Stage2.xaml?num="+Contact_number.Text+"&name="+contact_name.Text, UriKind.Relative));
}
and creating tile using this function..
private StandardTileData GetSecondaryTileData()
{
string filePath = System.IO.Path.Combine(#"/Shared/ShellContent", "logo.jpg");
StandardTileData tileData = new StandardTileData
{
Title = name,
BackgroundImage = new Uri(#"isostore:" + filePath, UriKind.Absolute),
Count = 0,
BackTitle = "app",
BackBackgroundImage = new Uri("", UriKind.Absolute),
BackContent = "content"
};
but it is throwing an exception
"An exception of type 'System.UriFormatException' occurred in System.ni.dll but was not handled in user code
Additional information: Invalid URI: The URI is empty."

the problem was that image was not in the shared/shellcontent/ and also
BackBackgroundImage = new Uri("", UriKind.Absolute),
this is incorrect. it should be relative if the tile has to be kept blank... took so many hours. huff

use this
MediaLibraryExtension.GetPath(p);
here p is the object of Class Picture(that is the picture for which it will return the path)

Related

Windows Phone: How to load html in webview from a local file

I have a html string and it has local css,js paths. But Html is not working with these local paths. We searced but in every example, they have loaded html with writing inline. But I have to work disconnect and there is so much css,js assests. If i write inline, i am worried about it will load slow and i think it so senseless. Then i decided to change a local html file and load html from that file.
How can i load html from a local file?
This is my example code:
StorageFolder localFolder =
Windows.Storage.ApplicationData.Current.LocalFolder;
string desiredName = "mobile.html";
StorageFile newFile =
await localFolder.CreateFileAsync(desiredName,CreationCollisionOption.OpenIfExists);
using (var stream = await newFile.OpenStreamForWriteAsync())
{
stream.Write(fileBytes, 0, fileBytes.Length);
}
webViewFormResponse.Source = new Uri(newFile.Path);
newFile.Path like this: C:\Data\Users\DefApps\APPDATA\Local\Packages\9f4082ad-ad69-4cb8-8749-751ee4c5e46d_x2xndhe6jjw20\LocalState\mobile.html
You can use the NavigateToLocalStreamUri method of the WebView
e.g.
In WebView Loaded event
private void WebView_Loaded(object sender, RoutedEventArgs e)
{
Uri uri = MyWebView.BuildLocalStreamUri("LocalData", "mobile.html");
LocalUriResolver resolver = new LocalUriResolver();
MyWebView.NavigateToLocalStreamUri(uri, resolver);
}
And the Uri resolver class
public sealed class LocalUriResolver : IUriToStreamResolver
{
public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
if (uri == null)
{
throw new Exception();
}
string path = uri.AbsolutePath;
return GetContent(path).AsAsyncOperation();
}
private async Task<IInputStream> GetContent(string uriPath)
{
try
{
Uri localUri = new Uri("ms-appdata:///local" + uriPath);
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(localUri);
IRandomAccessStream stream = await file.OpenReadAsync();
return stream.GetInputStreamAt(0);
}
catch (Exception)
{
throw new Exception("Invalid path");
}
}
}

Cannot create spreadsheet in google drive

I tried to create a spreadsheet in Android. It sent a success message but it wasn't created.
I used the following code to create it:
MetadataChangeSet metadataChangeSet = new MetadataChangeSet.Builder()
.setMimeType("application/vnd.google-apps.spreadsheet").setTitle("MonthExpense").build();
IntentSender intentSender = Drive.DriveApi
.newCreateFileActivityBuilder()
.setInitialMetadata(metadataChangeSet)
.setInitialDriveContents(result.getDriveContents())
.build(appobject.mGoogleApiClient);
try {
activity.startIntentSenderForResult(intentSender, 56, null, 0, 0, 0);
}
If I use any other mimetype it works correctly can anyone please guide me in the right way.
Edit
If i try any other mime type it works with out problem, So i guess the problem related with "application/vnd.google-apps.spreadsheet"
Try to change application/vnd.google-apps.spreadsheet to application/vnd.ms-excel
Create a WorkBook. This is the end of my working code
final private ResultCallback<DriveContentsResult> driveContentsCallback = new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(final DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create new file contents");
return;
}
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
#Override
public void run() {
//CREATE YOUR WORKBOOK HERE
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
wb.write(bos);
byte[] bytes = bos.toByteArray();
outputStream.write(bytes);
//WORKBOOK FILENAME
writer.write(fileName);
wb.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(fileName)
.setMimeType("application/vnd.ms-excel")
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi
.getRootFolder(getGoogleApiClient())
.createFile(getGoogleApiClient(), changeSet,
driveContents)
.setResultCallback(fileCallback);

Windows Phone 8 append to JSON file

I'm working on a Windows Phone 8 app.
I'm having issue appending to my JSON file.
It works fine if I keep the app open but once I close it and come back in it starts back writing from the beginning of the file.
Relevant code:
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
// Create a entry and intialize some values from textbox...
GasInfoEntries _entry = null;
_entry = new GasInfoEntries();
_entry.Gallons = TxtBoxGas.Text;
_entry.Price = TxtBoxPrice.Text;
_GasList.Add(_entry);
//TxtBlockPricePerGallon.Text = (double.Parse(TxtBoxGas.Text) / double.Parse(TxtBoxPrice.Text)).ToString();
// Serialize our Product class into a string
string jsonContents = JsonConvert.SerializeObject(_GasList);
// Get the app data folder and create or open the file we are storing the JSON in.
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile textfile = await localFolder.CreateFileAsync("gasinfo.json", CreationCollisionOption.OpenIfExists); //if get await operator error add async to class (btnsave)
//open file
using (IRandomAccessStream textstream = await textfile.OpenAsync(FileAccessMode.ReadWrite))
{
//write JSON string
using (DataWriter textwriter = new DataWriter(textstream))
//using (DataWriter textwriter = new DataWriter(textstream))
{
textwriter.WriteString(jsonContents);
await textwriter.StoreAsync(); //writes buffer to store
}
}
}
private async void btnShow_Click(object sender, RoutedEventArgs e)
{
StorageFolder localfolder = ApplicationData.Current.LocalFolder;
try
{
// Getting JSON from file if it exists, or file not found exception if it does not
StorageFile textfile = await localfolder.GetFileAsync("gasinfo.json");
using (IRandomAccessStream textstream = await textfile.OpenReadAsync())
{
//read text stream
using (DataReader textreader = new DataReader(textstream))
{
//get size ...not sure what for think check the file size (lenght) then based on next 2 commands waits until its all read
uint textlength = (uint)textstream.Size;
await textreader.LoadAsync(textlength);
//read it
string jsonContents = textreader.ReadString(textlength);
// deserialize back to gas info
_GasList = JsonConvert.DeserializeObject<List<GasInfoEntries>>(jsonContents) as List<GasInfoEntries>;
displayGasInfoEntries();
}
}
}
catch
{
txtShow.Text = "something went wrong";
}
}
private void displayGasInfoEntries()
{
txtShow.Text = "";
StringBuilder GasString = new StringBuilder();
foreach (GasInfoEntries _entry in _GasList)
{
GasString.AppendFormat("Gallons: {0} \r\n Price: ${1} \r\n", _entry.Gallons, _entry.Price); // i think /r/n means Return and New line...{0} and {1} calls "variables" in json file
}
txtShow.Text = GasString.ToString();
}
Thanks
Do you call the btnShow_Click each time you've started the app? Because otherwise the _GasList will be empty; if you now call the btnSave_Click all previous made changes will be lost.
So please make sure, that you restore the previously saved json data before you add items to the _GasList.

Downloading multiple images from the net

I am developing a app in which i download the images from the net and store them into the Isolated Storage. Here is my Code.
private void LoadImage(List<ProductImageList> item)
{
BitmapImage bi = new BitmapImage();
foreach (var product in item)
{
string a = product.ImageUrl;
string b = a.Substring(1, a.Length - 2);
Uri uri = new Uri(b, UriKind.RelativeOrAbsolute);
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
//load image from Isolated Storage if it already exist
name = System.IO.Path.GetFileName(b);
if (myIsolatedStorage.FileExists(name))
{
}
else
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += new OpenReadCompletedEventHandler(DownloadCompleted);
wc.OpenReadAsync(uri, wc);
}
}
}
}
private void DownloadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(name);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.Result);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
}
catch (Exception ex)
{
//Exception handle appropriately for your app
}
}
The item contains the ImageId,ImageUrl.The code only download last image of my list all time.Please suggest me how can i download All images..
You should use HttpRequest instead of WebClient here is the example
private void LoadImage(List<ProductImageList> item)
{
BitmapImage bi = new BitmapImage();
foreach (var product in item)
{
string a = product.ImageUrl;
string b = a.Substring(1, a.Length - 2);
Uri uri = new Uri(b, UriKind.RelativeOrAbsolute);
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
//load image from Isolated Storage if it already exist
name = System.IO.Path.GetFileName(b);
if (myIsolatedStorage.FileExists(name))
{
}
else
{
HttpWebRequest imageRequest = HttpWebRequest.CreateHttp();
imageRequest.Headers["ImageName"] = name;
imageRequest.BeginGetResponse(Imageresponse, imageRequest);
}
}
}
}
private void Imageresponse(IAsyncResult asyncResult)
{
try
{
string name = string.Empty;
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
using (Stream data = response.GetResponseStream())
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
name = request.Headers["ImageName"];
if (!string.IsNullorEmpty(name))
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(name))
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(data);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
}
}
}
}
}
catch (Exception ex)
{
}
}

save the image in storage file in windows phone 8

I'm making a windows phone 8 app of an app I made for windows store, and I am using PhotoChooser task to let the user upload a profile picture.
In the store version i used streams and FileOpenPicker, but i don't know how to use streams with PhotoChooser task.
This is how i did it in windows store, and its perfect:
StorageFile image;
public bunForm()
{
image = null;
this.InitializeComponent();
}
private async void choosePic(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
openPicker.FileTypeFilter.Clear();
openPicker.FileTypeFilter.Add(".bmp");
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".jpg");
// Open a stream for the selected file
var file = await openPicker.PickSingleFileAsync();
if (file != null)
{
image = file;
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
bunPic.Visibility = Visibility.Visible;
// Ensure a file was selected
if (file != null)
{
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);// bitmapImage.UriSource.ToString();
bunPic.Source = bitmapImage;
}
}
}
}
And here is how i'm trying it at windows Phone 8:
But (openPicker.PickSingleFileAsync();) line gives me error.
public BunForm()
{
InitializeComponent();
image = null;
this.photoChooserTask = new PhotoChooserTask();
this.photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
}
StorageFile image;
private void choosePic(object sender, RoutedEventArgs e)
{
photoChooserTask.Show();
}
private async void photoChooserTask_Completed(object sender, PhotoResult e)
{
//this is the only line that gives me error
var file = await openPicker.PickSingleFileAsync();
///
if (file != null)
{
image = file;
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
if (file != null)
{
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
myImage.Source = bmp;
}
}
}
Debug.WriteLine("pic done");
}
I was wondering how i can save the image in storage file in windows phone 8?
As noted on MSDN pages - OpenFilePicker cannot be used in C# WP8 apps, but you can use the PhotoChooserTask with ease for uploadng the profile picture:
// first invoke the task somewhere
PhotoChooserTask task = new PhotoChooserTask();
task.Completed += task_Completed;
task.Show();
// handle the result
async void task_Completed(object sender, PhotoResult e)
{
// no photo selected
if (e.ChosenPhoto == null) return;
// get the file stream and file name
Stream photoStream = e.ChosenPhoto;
string fileName = Path.GetFileName(e.OriginalFileName);
// persist data into isolated storage
StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream current = await file.OpenStreamForWriteAsync())
{
await photoStream.CopyToAsync(current);
}
...
// how to read the data later
StorageFile file2 = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
Stream imageStream = await file2.OpenStreamForReadAsync();
// display the file as image
BitmapImage bi = new BitmapImage();
bi.SetSource(imageStream);
// assign the bitmap to Image in XAML: <Image x:Name="img"/>
img.Source = bi;
}
Accoriding to this
Windows Phone 8
This API is supported in native apps only.
You can't use FileOpenPicker class.
There are already answers to the problem OpenFilePicker not working