Share Media Task - windows-phone-8

I'm developing app for Windows Phone 8, and i'm trying to share image via ShareMediaTask.
The procedure? that i use for it is as follows :
private static Microsoft.Phone.Tasks.ShareMediaTask shareMediaTask;
public static void shareCurrentCroppedImage ()
{
shareMediaTask = new Microsoft.Phone.Tasks.ShareMediaTask();
GC.Collect();
Debug.WriteLine("file path : {0}", currentFileName);
shareMediaTask.FilePath = currentFileName;
shareMediaTask.Show();
}
The path from console looks like this:
file path : C:\Data\Users\Public\Pictures\Saved Pictures\Lo_1.jpg
Unfortunately, when i call this proc ( from button click event ) the app shuts down, a black screen shows, but then suddenly workflow returns back to my app without any sharing UI. How can i fix this issue? Any help would be appreciated!

This is the code which worked for me..
I had created a PhotoChooserTask to capture an image or open an existing image from library and then when this PhotoChooserTask completes, I create a ShareMediaTask and set its Filepath property to The "OriginalFileName" filed from the parameter photoresult e.
The issue with your code, i think, might be this path of image.
private void OnShareMediaTaskClicked(object sender, RoutedEventArgs e)
{
var photoChooserTask = new PhotoChooserTask { ShowCamera = true };
photoChooserTask.Completed += OnPhotoChooserTaskCompleted;
photoChooserTask.Show();
}
void OnPhotoChooserTaskCompleted(object sender, PhotoResult e)
{
var photoChooserTask = (PhotoChooserTask)sender;
photoChooserTask.Completed -= OnPhotoChooserTaskCompleted;
var shareMediaTask = new ShareMediaTask ();
shareMediaTask.FilePath = e.OriginalFileName;
shareMediaTask.Show();
}
I have set the OnShareMEdiaClicked as ahandler of an onClick event for a button. and the rest flow is clear.
Hope this helps.

Related

Update text block from downloaded text file = RPC_E_WRONG_THREAD WP8.1

I am learning Windows Phone 8.1 development, I have probably done something utterly incorrectly programming wise
The need: I want to download a text file from the web using HttpClient() and display it in the TextBlock1
From variety of tutorials I have found the following:
public async void DownloadDataAsync()
{
string data = "some link to Textfile.txt";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(data);
HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();
UpdateTextBlock1(result);
}
Then the other functions.
public void UpdateTextBlock1(string result)
{
TextBlock1.Text = result;
}
private void BtnDownloadData_Click(object sender, RoutedEventArgs e)
{
Task t = new Task(DownloadDataAsync);
t.Start();
}
The code starts well enough - on button pressed, I receive RPC_E_WRONG_THREAD.
Is it that I'm trying to call the method when all threads haven't finished? How can I code that efficently so the TextBlock1 is updated with txt data?
Thanks for understanding, baby steps here in programming, and I couldn't find a relevant answer over google. (Maybe I don't yet know how to ask?)
You need to update the textblock on the UI thread like so:
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
TextBlock1.Text = result;
});
There are many posts on this subject.

Windows Phone navigation to other page

I'm trying to navigate to another page. I'm using the MVVM pattern. So my button is binded to a command:
private ICommand inscriptionPage;
public ICommand InscriptionPage
{
get
{
if (this.inscriptionPage == null)
this.inscriptionPage = new MyCommand(() => callInscriptionFunction());
return this.inscriptionPage;
}
}
public void callInscriptionFunction()
{
PhoneApplicationPage nav = new PhoneApplicationPage();
nav.NavigationService.Navigate(new Uri("Views/Registration/Registration.xaml", UriKind.Relative));
}
I have this Exception at the last line:
object reference not set to an instance of an object
I check on the web, tried different option, but this error is still there.
Edit: I tried to change the command to put it directly in the code behind. But I have a Debugger.break error.
private void Button_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("Views/Registration/Registration.xaml", UriKind.Relative));
}
Thanks.
First, your Uri should begin with a slash, so change new Uri("Views/Registration/Registration.xaml", UriKind.Relative) to new Uri("/Views/Registration/Registration.xaml", UriKind.Relative). This should make your code behind work.
Second, creating a PhoneApplicationPage is a really strange and wrong idea. If you are not using a MVVM framework that provides navigation service, usu this
App.RootFrame.Navigate(new Uri("/Views/Registration/Registration.xaml", UriKind.Relative))

FirstRun info in JSON (WP)

i have a problem with the info of a JSON in Windows Phone.
I want to show if the app is running for the first time, and if not, don't show anything.
This is my function to show info on the JSON:
async void NavigationService_Navigated(object sender, NavigationEventArgs e)
{
if (e.IsNavigationInitiator
|| !e.IsNavigationInitiator && e.NavigationMode != NavigationMode.Back)
{
var navigationInfo = new
{
Mode = e.NavigationMode.ToString(),
From = this.BackStack.Any() ? this.BackStack.Last().Source.ToString() : string.Empty,
Current = e.Uri.ToString(),
};
var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(navigationInfo);
await this.currentApplication.Client.PageView(jsonData);
}
}
I want to add one more thing where is Mode, From and Current. I want to add IsFirstRun that give as True if it's the first time i open the app.
I've seen this for firstRun function, but i don't know how to put it in my code.
public static bool IsFirstRun()
{
if (!settings.Contains(FIRST_RUN_FLAG)) //First time running
{
settings.Add(FIRST_RUN_FLAG, false);
return true;
}
return false;
}
I need help... thanks!
It is pretty simple if you want to create a flag for First Run,
In App.xaml.cs
Look for a function named
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
}
What we want to do is create a flag inside this function and only set it to true if it doesn't exist. Like so.
using System.IO.IsolatedStorage; // include this namespace in App.xaml.cs
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
if (!IsolatedStorageSettings.ApplicationSettings.Contains("first_run"))
{
IsolatedStorageSettings.ApplicationSettings.Add("first_run", true);
}
else
{
// set the flag to flase
IsolatedStorageSettings.ApplicationSettings["first_run"] = false;
}
// save
IsolatedStorageSettings.ApplicationSettings.Save();
}
Now if you want to do something on first run all you have to do is check the settings again like so:
bool first_run = (bool) IsolatedStorageSettings.ApplicationSettings["first_run"];
For debugging cases you will probably want to remove the flag so it will hit first_run again by doing this
// remove the flag and save
IsolatedStorageSettings.ApplicationSettings.Remove("first_run");
IsolatedStorageSettings.ApplicationSettings.Save();

How (and when) properly initialize camera in Windows Phone 8.1 (RT)

I'm writing simple WP app, that can work with images stored in a device or image taken by a camera right in my app. I'm maybe confused with navigation and camera initializing. There is a MainPage in the app where are buttons to select camera or library. Camera button just navigates to the CameraPage like this:
private void CameraButton_Click(object sender, RoutedEventArgs e)
{
...
this.Frame.Navigate(typeof(CameraPage));
}
And then I initialize camera in CameraPage OnNavigatedTo:
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
...
cameraCapture = new CameraCapture();
PreviewElement.Source = await cameraCapture.Initialize(Dispatcher);
await cameraCapture.StartPreview();
...
}
And CameraCapture initialization:
public async Task<MediaCapture> Initialize(CoreDispatcher dispatcher)
{
var cameraID = await GetCameraID(Windows.Devices.Enumeration.Panel.Back);
// Create MediaCapture and init
mediaCapture = new MediaCapture();
await mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
{
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.VideoPreview,
AudioDeviceId = string.Empty,
VideoDeviceId = cameraID.Id
});
mediaCapture.VideoDeviceController.PrimaryUse = Windows.Media.Devices.CaptureUse.Video;
this.dispatcher = dispatcher;
var maxResolution = mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo).Aggregate((i1, i2) => (i1 as VideoEncodingProperties).Width > (i2 as VideoEncodingProperties).Width ? i1 : i2);
await mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, maxResolution);
imgEncodingProperties = ImageEncodingProperties.CreateJpeg();
return mediaCapture;
}
The problem is - when I tap on the CameraButton on my MainPage, the app freezes on the MainPage until camera isn't initialized and then is the CameraPage loaded. What is the best approach to deal with this? Should I just move content from CameraPage to MainPage (so initialize camera on the MainPage and take a photo here)? Or there is a better way - like some event on the CameraPage? Tapping another button on the CameraPage to initialize camera would be so annoying for both me and user :)

Navigate to the same View. Why Loaded and OnNavigatedTo events aren't called?

Im doing a cloud App(like Skydrive) in Windows Phone 8 , each time I navigate to a different folder I need to reload the FolderView.xaml page to display the content of this folder and I need to add the view to the back stack then I will be able to back to the previous path...
From now when I try to reload the FolderView from the FolderView.xaml.cs page, none event is called...
I don't understand why ? And if you have a solution you are welcome ...
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
if (App.ElementSelected != null)
{
BdeskElement FolderChoosen = new BdeskElement();
FolderChoosen = App.ElementSelected;
Gridentete.DataContext = FolderChoosen;
GetFiles(FolderChoosen);
}
}
private async void llsElements_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LongListSelector llselement = null;
listElementCollection.Clear();
if (sender != null)
llselement =(LongListSelector)sender;
if(llselement.SelectedItem!=null)
{
BdeskElement bdelement=(BdeskElement)llselement.SelectedItem;
if (bdelement.TypeElement==BdeskElement.BdeskTypeElement.Folder)
{
App.DocLibSelected = null;
App.ElementSelected = bdelement;
// I navigate to the same view here but nothing happens
NavigationService.Navigate(new Uri("/Views/BDocs/FolderView.xaml", UriKind.RelativeOrAbsolute));
}
}
}
To navigate to the same page with a new instance, you must change the Uri. For example:
NavigationService.Navigate(new Uri(String.Format("/Views/BDocs/FolderView.xaml?id={0}", Guid.NewGuid().ToString()), UriKind.Relative));
You can discard that parameter if you don't want/use it.