How to display images into another page using navigation query string in windows phone 7? - windows-phone-7

i'm not able to display the images to another page. The images are taken from json. So i'm trying to pass the image url of the selected item of a listbox into a navigagtion query string.The variable i'm trying to pass the data is showing as null.Plese provide me with solution. Thanks
Here the code of the first page:
private void ImageList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var lbi = (sender as ListBox).SelectedItem;
if (e.AddedItems.Count > 0)
{
Uri targetPage = new Uri("/DisplayPhoto.xaml?selectedItem="+ lbi.ToString(),UriKind.RelativeOrAbsolute);
NavigationService.Navigate(targetPage);
}
((ListBox)sender).SelectedIndex = -1;
}
Code of the second page:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
string selectedIndex = "";
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
{
Uri uri = new Uri(selectedIndex, UriKind.Absolute);
var img = new Image();
img.Source = new BitmapImage(uri);
img.Height = 400;
img.Width = 400;
listBox1.Items.Add(img);
}
base.OnNavigatedTo(e);
}

Try to escape your parameters with Uri.EscapeUriString
Uri targetPage = new Uri("/DisplayPhoto.xaml?selectedItem="+ Uri.EscapeUriString(lbi.ToString()),UriKind.RelativeOrAbsolute);
NavigationService.Navigate(targetPage);

I prefer sending data via some static property, preferably inside the App class. This way you can "send" complex objects from one page to another.

Related

How to upload images to facebook which is selected by using photoChooserTask in windows phone 8?

I am developing a Windows Phone app in which I have to post a photo to facebook. And that particular photo is choosen by using PhotoChooserTask or CameraChooserTask.
Normally, I can post a particular photo successfully, but I am facing problem to post the selected photo. I saw some link like
link
So please if anyone know about the issue please help me out.
Thanx in advance.
EDIT
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
//var parameters1 = new Dictionary<>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
parameters["ContentType"] = "image/png";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
string imageName = "ic_launcher.png";
StreamResourceInfo sri = null;
Uri jpegUri = new Uri(imageName, UriKind.Relative);
sri = Application.GetResourceStream(jpegUri);
try
{
byte[] imageData = new byte[sri.Stream.Length];
sri.Stream.Read(imageData, 0, System.Convert.ToInt32(sri.Stream.Length));
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = imageName,
ContentType = "image/jpg"
};
fbUpload.SetValue(imageData);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Tribute";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1 + "\n" + d + "\n" + memoType + "\n" + message1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
//client.PostTaskAsync("me/photos", parameters1);
}
On clicking on a button I am calling PostClicked class and it will directly go to facebook mainpage and it will ask for login information. Like this I am doing.
Please check it out
Now I can share a photo to facebook successfully by using photochoosertask or cameratask.
I am sharing my experience so that if anyone face the same issue can use it.
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
SaveImageToIsolatedStorage(image, tempJPEG);
this.image.Source = image;
}
public void SaveImageToIsolatedStorage(BitmapImage image, string fileName)
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
isolatedStorage.DeleteFile(fileName);
var fileStream = isolatedStorage.CreateFile(fileName);
if (image != null)
{
var wb = new WriteableBitmap(image);
wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
}
fileStream.Close();
}
}
With this you can able to save the selected image to IsolatedStorage.
And then at the time of posting the photo to facebook you have to select the image from IsolatedStorage.
private void PostClicked(object sender, RoutedEventArgs e)
{
//Client Parameters
var parameters = new Dictionary<string, object>();
parameters["client_id"] = FBApi;
parameters["redirect_uri"] = "https://www.facebook.com/connect/login_success.html";
parameters["response_type"] = "token";
parameters["display"] = "touch";
//The scope is what give us the access to the users data, in this case
//we just want to publish on his wall
parameters["scope"] = "publish_stream";
Browser.Visibility = System.Windows.Visibility.Visible;
Browser.Navigate(client.GetLoginUrl(parameters));
}
private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
FacebookOAuthResult oauthResult;
//Making sure that the url actually has the access token
if (!client.TryParseOAuthCallbackUrl(e.Uri, out oauthResult))
{
return;
}
//Checking that the user successfully accepted our app, otherwise just show the error
if (oauthResult.IsSuccess)
{
//Process result
client.AccessToken = oauthResult.AccessToken;
//Hide the browser
Browser.Visibility = System.Windows.Visibility.Collapsed;
PostToWall();
}
else
{
//Process Error
MessageBox.Show(oauthResult.ErrorDescription);
Browser.Visibility = System.Windows.Visibility.Collapsed;
}
}
private void PostToWall()
{
try
{
byte[] data;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read))
{
data = new byte[fileStream.Length];
fileStream.Read(data, 0, data.Length);
fileStream.Close();
}
}
//MemoryStream ms = new MemoryStream(data);
//BitmapImage bi = new BitmapImage();
//// Set bitmap source to memory stream
//bi.SetSource(ms);
//this.imageTribute.Source = bi;
FacebookMediaObject fbUpload = new FacebookMediaObject
{
FileName = tempJPEG,
ContentType = "image/jpg"
};
fbUpload.SetValue(data);
string name1 = eventname.Text;
string format = "yyyy-MM-dd";
string message1 = eventmessage.Text;
string date1 = datepicker.ValueString;
DateTime datevalue = DateTime.Parse(date1);
string d = datevalue.ToString(format);
string memoType = "Notice";
var parameters = new Dictionary<string, object>();
var parameters1 = new Dictionary<string, object>();
parameters["message"] = name1;
parameters["source"] = fbUpload;
webservice();
client.PostTaskAsync("me/photos", parameters);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
Thanx to all....
you can do that by two methods :
1) by using mediasharetask in which it will show u all sharing account to which your phone is synced like facebook,gmail,linkdin,twitter,etc : it can be used like like this.
ShareMediaTask shareMediaTask = new ShareMediaTask();
shareMediaTask.FilePath = path;
shareMediaTask.Show();
2) by using facebook sdk. you can get the package from nuget manager and then u can use it to share on facebook.
I hope this might help u.

How to handle list picker in Wp7

I have a list picker which is displayed in my phone application page.I have created list picker in starting of class,and i am adding the list picker in the phoneApplicationPage_loaded() method.When the page is launched the first time, ,the scenario works perfectly and its navigates further to second page.When i navigate back to previous page(containing list picker),it shows Invalid Operation Exception occured stating "Element is already the child of another element."
I want to know how to handle these scenarios?
Code is below
namespace My.Design
{
public partial class myclass : PhoneApplicationPage
{
String[] values = null;
ListPicker picker = new ListPicker();
StackPanel sp;
StackPanel mainFrame;
String statementInfo = "";
public myclass()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
Debug.WriteLine("Phone Application Page Loaded_>>>>>>");
List<String> source = new List<String>();
displayUI();
}
public void displayUI()
{
Debug.WriteLine("About to display UI in miniStatement");
Debug.WriteLine("<-------------Data--------->");
Debug.WriteLine(statementInfo);
Debug.WriteLine("<-------------Data--------->");
int count = VisualTreeHelper.GetChildrenCount(this);
if (count > 0)
{
for (int i = 0; i < count; i++)
{
UIElement child = (UIElement)VisualTreeHelper.GetChild(this, i);
string childTypeName = child.GetType().ToString();
Debug.WriteLine("Elements in this Child" + childTypeName);
}
}
List<String> source = new List<String>();
String[] allParams = ItemString.Split('#');
source.Add("PleaseSelect");
for (int i = 0; i < allParams.Length; i++)
{
Debug.WriteLine("All Params Length" + allParams[i]);
if (!(allParams[i].Equals("") && (!allParams[i].Equals(null))))
{
if (values != null)
{
Debug.WriteLine("Values length" + values.Length);
values[values.Length] = allParams[i];
}
else
{
Debug.WriteLine("Allparams Length" + allParams[i]);
source.Add(allParams[i]);
}
}
}
//picker = new ListPicker();
this.picker.ItemsSource = source;
mainFrame = new StackPanel();
TextBlock box = new TextBlock();
box.Text = "> DEmoClass";
box.FontSize = 40;
mainFrame.Children.Add(box);
Canvas canvas = new Canvas();
StackPanel sp = new StackPanel();
TextBlock box1 = new TextBlock();
box1.Text = "Number";
box1.HorizontalAlignment = HorizontalAlignment.Center;
box1.FontSize = 40;
SolidColorBrush scb1 = new SolidColorBrush(Colors.Black);
box1.Foreground = scb1;
sp.Children.Add(box1);
picker.Width = 400;
picker.Height = 150;
sp.Children.Add(picker);
Canvas.SetTop(sp, 150);
canvas.Children.Add(sp);
mainFrame.Children.Add(canvas);
this.ContentPanel1.Children.Add(mainFrame);
}
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
/*
Debug.WriteLine("OnNavigatingFrom>>>.>>MainPage");
if (sp != null)
{
sp.Children.Remove(picker);
}*/
base.OnNavigatingFrom(e);
}
}
}
If you are not intending to update the listpicker after navigating back from the second page add the following line in your Loaded event handler
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
this.Loaded -= PhoneApplicationPage_Loaded;
Debug.WriteLine("Phone Application Page Loaded_>>>>>>");
List<String> source = new List<String>();
displayUI();
}
i don't know why you can not use that case when app resume from tombstoned.
error happened because when you back to your page , loaded event runs again.
by the way,
Application_Activated 's argument can tell you app resumes from tombstoned or not--.
if (e.IsApplicationInstancePreserved)
{
IsTombstoning = false;
}
else
{
IsTombstoning = true;
}
I'm curious why you're creating it in code and not leaving it in XAML? Also the error is coming from the fact that you're attempting to add it twice into a location that can probably only have a single content element. What's the higher level problem you're trying to solve?

How can I populate more than one Silverlight Image from Bing Maps asynchronous calls?

I have the following code, which works fine if you just want to populate one Image with a response from Bing Maps. But if I try to do two then the variable _currentImage always ends up being "image1" because the calls are asynchronous. How can I pass the image variable along to the ImageryServiceGetMapUriCompleted method?
using System;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using BasicBingMapsImagerySvc.ImageryService;
namespace BasicBingMapsImagerySvc
{
public partial class MainPage : UserControl
{
private const string BingMapsKey = "my key";
private Image _currentImage;
public MainPage()
{
InitializeComponent();
GetMap(42.573377, -101.032251, image0, MapStyle.AerialWithLabels);
GetMap(42.573377, -101.032251, image1, MapStyle.Road_v1);
}
private void GetMap(double lat, double lon, Image image, MapStyle mapStyle)
{
var mapUriRequest = new MapUriRequest();
// Set credentials using a valid Bing Maps key
mapUriRequest.Credentials = new Credentials();
mapUriRequest.Credentials.ApplicationId = BingMapsKey;
// Set the location of the requested image
mapUriRequest.Center = new Location();
mapUriRequest.Center.Latitude = lat;
mapUriRequest.Center.Longitude = lon;
// Set the map style and zoom level
var mapUriOptions = new MapUriOptions();
mapUriOptions.Style = mapStyle;
mapUriOptions.ZoomLevel = 13;
// Set the size of the requested image to match the size of the image control
mapUriOptions.ImageSize = new SizeOfint();
mapUriOptions.ImageSize.Height = 256;
mapUriOptions.ImageSize.Width = 256;
mapUriRequest.Options = mapUriOptions;
var imageryService = new ImageryServiceClient("BasicHttpBinding_IImageryService");
imageryService.GetMapUriCompleted += ImageryServiceGetMapUriCompleted;
_currentImage = image;
imageryService.GetMapUriAsync(mapUriRequest);
}
private void ImageryServiceGetMapUriCompleted(object sender, GetMapUriCompletedEventArgs e)
{
// The result is an MapUriResponse Object
MapUriResponse mapUriResponse = e.Result;
var bmpImg = new BitmapImage(new Uri(mapUriResponse.Uri));
_currentImage.Source = bmpImg;
}
}
}
You could use a lambda expression / delegate for your event handler, which allows you to 'capture' the reference to the image:
var imageryService = new ImageryServiceClient("BasicHttpBinding_IImageryService");
imageryService.GetMapUriCompleted += (s,e) =>
{
// The result is an MapUriResponse Object
MapUriResponse mapUriResponse = e.Result;
var bmpImg = new BitmapImage(new Uri(mapUriResponse.Uri));
// set the image source
image.Source = bmpImg;
};

Download image from server

I've to download an image from the server on button click.
The code is:
private void Button_Click(object sender, RoutedEventArgs e)
{
(sender as Button).IsEnabled = false;
progressbar.IsIndeterminate = true;
WebClient w = new WebClient();
w.OpenReadAsync(new Uri("http://example.com/xxx/image.png"));
w.OpenReadCompleted += new OpenReadCompletedEventHandler(w_OpenReadCompleted);
}
void w_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
progressbar.IsIndeterminate = false;
BitmapImage b = new BitmapImage();
b.SetSource(e.Result);
Image img = new Image();
img.Source = b;
LayoutRoot.Children.Add(img);
}
The problem which I'm facing is that for the first time the data is being downloaded from the server and shown correctly. However, if I quit the application and again start it, it downloads the old image even if I have deleted the image from the server or changed the image. I think the image is getting cached somewhere but don't know how to solve this problem.
I think this will be the same as your issue:
How do you disable caching with WebClient and Windows Phone 7
I haven't noticed this behaviour when using the HttpWebRequest to get data. But I'am not sure about it.
Update: HttpWebRequest has by default the same behaviour but can be disabled. This blogpost is talking about the options you have:
http://www.nickharris.net/2010/10/windows-phone-7-httpwebrequest-returns-same-response-from-cache/
Finally managed to fix it.The only change that was made is:
w.OpenReadAsync(new Uri("http://example.com/xxx/image.png?q="+Guid.NewGuid()));
You could also use HttpWebRequest to download fresh data every request. Here is a simple class which sets up the asynchronous calls
Here is a simple http client which will download data from the given uri.
public static class HttpClient
{
public static void Execute(Uri uri, Action<HttpWebRequest> onrequest, Action<HttpWebResponse> onresponse)
{
var request = HttpWebRequest.CreateHttp(uri);
onrequest(request);
request.BeginGetResponse
(
result =>
{
try
{
if (request.HaveResponse)
onresponse((HttpWebResponse)request.EndGetResponse(result));
}
catch { }
},
null
);
}
}
Using the HttpClient with your button click event you get this
private void Button_Click(object sender, RoutedEventArgs e)
{
(sender as Button).IsEnabled = false;
progressbar.IsIndeterminate = true;
HttpClient.Execute
(
new Uri(http://example.com/xxx/image.png),
request =>
{
request.UserAgent = "Custom HTTP Client";
},
response =>
{
progressbar.IsIndeterminate = false;
BitmapImage b = new BitmapImage();
b.SetSource(response.GetResponseStream());
Image img = new Image();
img.Source = b;
LayoutRoot.Children.Add(img);
}
);
}

Camera Capture in WP7 Mango

I've recently upgraded my WP7 app to Mango and am having some problems with the camera. The code below used to work on 7.0, but on 7.1 the completed handler fires before the dialog is even shown, so I can't capture the result. After taking the photo, the phone displays "Resuming..." which it never used to do.
var dlg = new CameraCaptureTask();
dlg.Completed += (s, e) =>
{
if (e.TaskResult == TaskResult.OK) {
BitmapImage bmp = new BitmapImage();
bmp.SetSource(e.ChosenPhoto);
//var img = new Image();
//img.Source = bmp;
string caption = string.Empty;
var inputDialog = new InputPrompt()
{
Title = "Caption",
Message = "Enter caption/description for snapshot",
};
inputDialog.Completed += (ss, ee) =>
{
if (ee.PopUpResult == PopUpResult.Ok)
{
caption = ee.Result;
var snap = SnapshotBLL.AddSnapshot(recipeId, bmp, caption);
onComplete(null, new SnapshotEventArgs(snap));
}
};
inputDialog.Show();
}
};
dlg.Show();
The MSDN docs appear to show a variation of my code but I can no longer get the result of the camera capture task.
Assuming that your sample comes from a single method I wouldn't expect it to ahve worked pre Mango.
The CameraCaptureTask should be created and the callback assigned in the constructor of the page for it to work properly.
Something like:
public partial class MainPage : PhoneApplicationPage
{
private CameraCaptureTask cct = new CameraCaptureTask();
public MainPage()
{
InitializeComponent();
cct.Completed += new EventHandler<PhotoResult>(cct_Completed);
}
private void cct_Completed(object sender, PhotoResult e)
{
// Do whatever here
}
private void SomeEventHandler(object sender, RoutedEventArgs e)
{
cct.Show();
}
}
This works in both 7.0 & 7.1

Resources