[Q][SOLVED] PhotoChooserTask Mango Exception - Windows Phone 7 Software Development

A simple photochooser task application throws a Nullrefference exception(Invalid pointer) and pixel height and width is 0 on mango, on nodo it worked alright.
Am I missing a cast? or this is a bug in mango, and will be fixed?
Here's the code:
Code:
private PhotoChooserTask photo;
// Constructor
public MainPage()
{
InitializeComponent();
photo = new PhotoChooserTask();
photo.Completed += new EventHandler<PhotoResult>(photo_Completed);
}
void photo_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BitmapImage bi = new BitmapImage();
bi.SetSource(e.ChosenPhoto);
//////////////////////////////////////////////////////////////////////////////////////
var wb = new WriteableBitmap(bi);//Exception here
/////////////////////////////////////////////////////////////////////////////////////
// bi.PixelHeight and bi.PixelWidth == 0;
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
photo.Show();
}
}
Hope someone can help.
Thanks in advance

This is because you need to set the CreateOptions property of the BitmapImage before you use it to construct the WriteableBitmap.
The default 'create' option on WP7 is DelayCreation (it may be BackgroundCreation in some of the 7.1 betas, but the mango RTM I think is DelayCreation) but either way the problem you're having is that your image has not been initialised yet at the point you use it in the WriteableBitmap's constructor (hence the null reference exception).
The options (depending what you set) let images be only initialised when needed, and downloaded on separate threads / asynchronously, which can help performance (or at least stop the phone blocking other things happening whilst images are loaded). Users also have the ability with the photo chooser to pick images from online ablums, so as you can imagine you also have to handle perhaps a second or two waiting for a download to complete, and of course downloads can also fail when connections drop etc. which you can handle too.
So in answer to your question (off the top of my head, not confirmed it with code) set the createoptions to none, and use the Bitmap's ImageOpened event to construct the WritableBitmap (you may also want to handle the Bitmap's ImageFailed event). Make sure you set up the ImageOpened event before you set the source, i.e.
BitmapImage bi = new BitmapImage();
bi.CreateOptions = BitmapCreateOptions.None;
bi.ImageOpened += new (some event name)
bi.ImageFailed += new (some event name)
bi.SetSource(e.ChosenPhoto);
Hope that helps,
Ian

Thank you very much
Problem solved

otherworld said:
This is because you need to set the CreateOptions property of the BitmapImage before you use it to construct the WriteableBitmap.
The default 'create' option on WP7 is DelayCreation (it may be BackgroundCreation in some of the 7.1 betas, but the mango RTM I think is DelayCreation) but either way the problem you're having is that your image has not been initialised yet at the point you use it in the WriteableBitmap's constructor (hence the null reference exception).
The options (depending what you set) let images be only initialised when needed, and downloaded on separate threads / asynchronously, which can help performance (or at least stop the phone blocking other things happening whilst images are loaded). Users also have the ability with the photo chooser to pick images from online ablums, so as you can imagine you also have to handle perhaps a second or two waiting for a download to complete, and of course downloads can also fail when connections drop etc. which you can handle too.
So in answer to your question (off the top of my head, not confirmed it with code) set the createoptions to none, and use the Bitmap's ImageOpened event to construct the WritableBitmap (you may also want to handle the Bitmap's ImageFailed event). Make sure you set up the ImageOpened event before you set the source, i.e.
BitmapImage bi = new BitmapImage();
bi.CreateOptions = BitmapCreateOptions.None;
bi.ImageOpened += new (some event name)
bi.ImageFailed += new (some event name)
bi.SetSource(e.ChosenPhoto);
Hope that helps,
Ian
Click to expand...
Click to collapse
Hello, I have the same problem (NullReferenceException) and have read you response, which from what I see it is the solution, but I have a problem; not where I have to go to do I change them that you propose. I would be so kind of explaining to me that I have to continue steps. It English me is very bad and I am using a translator.
I have HTC Trophy the v.th 7740.16 with chevrom and U2M7740 of Ansar.
Thank you in advance and greetings.

Hi,
If you upload your code / project I will take a look and see where the error is.
Si me muestras su código / proyecto, puedo ver por qué recibiras una excepción NullReference
Ian

otherworld said:
Hi,
If you upload your code / project I will take a look and see where the error is.
Si me muestras su código / proyecto, puedo ver por qué recibiras una excepción NullReference
Ian
Click to expand...
Click to collapse
Hello,
The question is that it is not any project, applications do not develop (although I would like). This type of errorr (nullreferenceexception) happens to me since I updated to Mango, so much in v.7720.68 as in v.7740.16 and happens in apps as Morfo, Fantasy Painter, and at the time of choosing fund in Touchxperience. Not if these apps are not conditioned to Mango or if, perhaps, from the record it might change some type of configuration or entering the Xaml of the app to be able to change some fact, end not...
For the little that, an error of the photochooser seems to be, the question is if it is possible to gain access to him and as doing it.
Anyhow thank you very much and a cordial greeting.

Hi,
If it is not a code issue then I do not know what it could be. Are you using a custom rom?
Good luck with it.
Ian

otherworld said:
Hi,
If it is not a code issue then I do not know what it could be. Are you using a custom rom?
Good luck with it.
Ian
Click to expand...
Click to collapse
Hello. Not, I am with official Mango the v.th 7740.16. I have already restored to factory and it continues the error. I believe that it is a question of the update, it must have a mistake in the pitcher of photos or some error with the librerie, do not know...
Thank you anyhow and greetings.

Hello, otherworld.
I continue with the same problem, 'nullreferenceexception' related with 'chooserphoto' in some application. The curious thing is that someone of them me work correctly, I gain access to me librery and it takes the photos, and in others not, as for example Morfo. I do not know if the problem is in the code source of these applications or phone is in me. Is this the code source of Morfo, is it possible to correct so that this does not happen?
Thank you in advance and greetings.

Related

Open ZIP file in Silverlight

Hi,
I'm working on my first application for Windows Phone. I got a ZIP file which contains a huge amount of XML files and which has to be
updated through the app. So I declared the 'Build Action' of the file to 'Content'. Now I'm stuck opening the file for reading and extracting
a stream for a specific XML file.
I tried File.OpenRead but Visual Studio Express crashes when trying to debug this.
Do I need to use Application.GetResourceStream? If yes, can someone post a working example with a content ZIP file (not resource).
Can anyone help me?
Thank you,
toolsche
Try http://senssoft.com/ZipTest.zip
I've created that example project for Freda's developer.
Hi,
Unfortunately that doesn't help me.
1) U did set the file as "Resource" => it will not be updateable because it's within the assembly. If I'm wrong, please tell me...
2) U used an external library (SharpZipLib) which I hope it wouldn't be necessary.
1) I've used an embedded file (actually, epub == zip) to simplify the solution. It's just an example. U may copy the resource file to IsolatedStorageFile / download it from web/ whatever you want. I can't teach you how to use Silverlight for WP7 - buy some good book...
2) SharpZipLib IS NECESSARY! Other "zippers" looks like not a 100% compatible with WinZip/linux zippers (see Freda corresponding topic). SharpZipLib did the job very well.
Of course it up to you: what you want to use. But I gave you a 100% working and tested solution.
Hi,
I'm not in doubt that your solution is working and I thank you for your suggestion.
Maybe I'm on the wrong path, but what I think I need is a solution for opening
a zip file that is NOT part of the assembly (which I think it is if you declare it as
embedded resource).
My intention is to load one or more zip files from a server which the application
should be able parse/remove/replace if outdated. I tried to find a solution but had
no luck so far. MSDN has an example but I couldn't get it to work because I don't
know where the zip file should be located:
http://msdn.microsoft.com/en-us/library/cc190632(v=VS.95).aspx
Try to use IsolatedStorageFile and WebClient, something like this:
Code:
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
WebClient downloader = new WebClient();
downloader.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("myfile.zip", FileMode.Create, isf))
{
Byte[] buffer = new Byte[e.Result.Length];
e.Result.Read(buffer, 0, buffer.Length);
stream.Write(buffer, 0, buffer.Length);
}
DoSomethingWithZip("myfile.zip");
}
};
downloader.OpenReadAsync(new Uri("http://mysite.com/archive.zip", null));
Thank you for the quick answer. I will try it as soon as possible and post the results.
EDIT: Thanks, it's working as suggested.

[HACKING/DETECT MILESTONE] Quit silverlight application from everywhere, no p/invoke!

Code:
[U][SIZE="5"]new Microsoft.Xna.Framework.Game().Exit();[/SIZE][/U]
To exit app at any place in silverlight.
Add reference to:
> Microsoft.Xna.Framework.Game (.dll)
> Create class named eg Quit that inherits "Game" from XNA framework
Code:
public class Quit : Microsoft.Xna.Framework.Game { }
> Make random silverlight click handler or other that will capture the event
Code:
private void Root_Start_Click(object sender, RoutedEventArgs e)
{
new Quit().Exit();
}
OR
> Anywhere in the code there YOU want it to exit.
Code:
new Quit().Exit();
Explanation (complicated)
The XNA framework is based on a way that will make an infinitive loop where the "Exit();" ends the loop that get the !
Code:
private GameHost host;
! of XNA, the XNA and silverlight share the same base host,
the "taskhost.exe" %1 (args).
Now, to the point, the GameHost (host) includes a !void! that is completely !internal! witch calls the main taskhost, "yep im done, saved everything and you can now kill (shutdown) me (app/silverlight/XNA).
So, shorthanded.
> call
Code:
new Quit().Exit();
OR
> direct baseclass-call
Code:
new Microsoft.Xna.Framework.Game().Exit();
Goods:
-Passes Microsoft Application submission (no p/invoke what so ever)
-No GetMethods()[x].Invoke (CF 3.7 blocked))
-No need to make an "QuitException", submission fails probably.
Tested in emulator & [Europe] Omnia 7, Obi One Kanobie: "may the invokes be with someone else" (no, invokes) =D
If you use a QuitException the app will pass submission. That's the recommended method and my app passed just fine using it.
RustyGrom said:
If you use a QuitException the app will pass submission. That's the recommended method and my app passed just fine using it.
Click to expand...
Click to collapse
Its not recommended (source?), did you thought about Visual Studio 2010 catches all exceptions?, it gets extra anoying.
Rule: Do never burry exceptions and let them go unhandled.
Silverlight apps that use XNA methods and classes (and vice-versa) will fail certifications. It's in the guidelines:
4.2.5 The application must not call any APIs in the Microsoft.Xna.Framework.Game assembly or the Microsoft.Xna.Framework.Graphics assembly when using any methods from the System.Windows.Controls namespace
Click to expand...
Click to collapse

[Q] How Can I Make an Object Draggable?

Hello everybody,
Can someone explain me how can I make an object (an Image) draggable by the user in a Windows Phone Silverlight application?
I'm stuck because I don't know how to do this, I've assmued that the AllowDrop propery It's what I need...
Can you help me?
Thank you
There are lot of ways to implement... Simpliest (but not an optimal) way is: drop image to main page, attach these handlers to the image and LayoutRoot.
You should understand idea but your implementation may differ (and better)
Code:
private void image1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.image1.RenderTransform = new TranslateTransform();
}
private void image1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
this.image1.RenderTransform = null;
}
private void LayoutRoot_MouseMove(object sender, MouseEventArgs e)
{
TranslateTransform t = this.image1.RenderTransform as TranslateTransform;
if (t != null)
{
Point pt = e.GetPosition(this);
t.X = pt.X - (image1.Width / 2);
t.Y = pt.Y - (image1.Height / 2);
}
}
Thank you for the reply!
The code works, but the image is draggable even if I tap somewhere else, how can I make it draggable by only clicking the image?
Thank you again
EDIT: The TranslateTransform is a specific kind of render transformation. Rather that changing properties of the control (such as the Margin property), it simply affects how the control is displayed on the screen.
I need something that actually changes the image margins...
As for first question: attach MouseLeftButtonDown & MouseLeftButtonUp to image, not to the layout root (grid).
For second one: why do you need to change image margins? What's the reason? What are you trying to do?
P.S. Of course you can change margins instead TranslateTransform but I'm not sure is it GPU powered...
MouseLeftButtonDown & MouseLeftButtonUp are already attached to the image... Did you mean MouseMove? I tried to put all the three events on the image, but It doesn't work, I don't have the drag effect :\
I need this for a simple game
This is what I have to do:
1) A level where I don't need to change margins: You have to touch an image which is behind another one, so you have to drage the first image away to touch the second.
2) A level where I need to change margins: You have to complete a puzzle. You have a puzzle with a missing piece on the left and 4 pieces on the right. You have to take the right missing piece and drag it to the empty place in the puzzle. I wanted to so something like "if the block is in a specific range of margins(because it's too difficult to release the image exactly where It should go), then verify it it's the correct one".
Sorry but seems like you need to study game programming basics first. All tasks you've described are very simple but you need (at least) understand what are you doing...
I gave you an idea how to move image (but there are a lot (not, A LOT) of different ways). So you only need to:
- start "dragging" image by changing TranslateTransform coordinates;
- on each change you should check image bounds (it's e.GetPosition(this).X, e.GetPosition(this).Y, e.GetPosition(this).X + image1.Width, e.GetPosition(this).Y + image1.Height) intersection with your placeholder and "fix" image (just do not process MouseMove) . That's all.
If you still don't get it, try good book first.

ISETool.exe bug

Today I found very annoying and strange bug (or, may be, MS call it "feature" ). Seems like directories on isf can hold 1024 files only...
Try code below:
Code:
Random rnd = new Random();
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
byte[] data = new byte[1024];
isf.CreateDirectory("test");
for (int i=0; i<1025; i++)
{
string fileName = "test\\" + i.ToString("D4") + ".bin";
using (IsolatedStorageFileStream fs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf))
{
rnd.NextBytes(data);
fs.Write(data, 0, data.Length);
}
}
}
After loop completed, resulting directory "test" will be empty! But change i<1024 and you'll get all yours 1024 files...
Tested on emulator and HTC Surround, same results. Can't find any documentation about this limitation... Shame on you, MS!
Update: another strange behavior ('cause of this bug) - if you already have 1024 files and try to add one more, the whole directory content is "magically" disappear But exception isn't thrown...
Interesting, I'll try it as well. This would be lame to have to work around.
Dbeattie said:
Interesting, I'll try it as well.
Click to expand...
Click to collapse
Yes, please, confirm...
I can't test this at the moment but I know I write well over 1000 files to /shared/media so I'm curious to tet this.
sensboston said:
Yes, please, confirm...
Click to expand...
Click to collapse
Hey just tried it out, wrote 2k items to a folder called "Data".
While it didn't show up in the Windows Phone Power tools, the file does exist in the folder itself.
bool success = storage.FileExists(Path.Combine("data", "1999"));
So it's either a problem with the WPConnect api or with the power tools, haven't tried the command line tool.
Yep, fortunately you are right, it's a ISETool.exe (or drivers) bug, not a WP7 ISF.
sensboston said:
Yep, fortunately you are right, it's a ISETool.exe (or drivers) bug, not a WP7 ISF.
Click to expand...
Click to collapse
Could you therefore edit the title of the thread please?
Thanks.

[dev] hook into PhoneStatusBarPolicy

Hello alltogether,
I digged into the Lollipop code to look for a solution to restore the old Kitkat silent mode in Lollipop with Xposed.
I got a working prototype now but would like to add the silentmode icon back to the statusbar.
Unfortunately it got removed in Lollipop so I have to port it forward from an older ROM.
To do that I need to hook into the PhoneStatusBarPolicy class, which for some reason fails.
This is my code:
Code:
private static final String CLASS_PHONE_STATUSBAR_POLICY = "com.android.systemui.statusbar.phone.PhoneStatusBarPolicy$1";
public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
if (lpparam.packageName != "android")
return;
final Class<?> classStatusbarPolicy = XposedHelpers.findClass(CLASS_PHONE_STATUSBAR_POLICY, lpparam.classLoader);
XposedHelpers.findAndHookMethod(classStatusbarPolicy, "updateVolumeZen",
new XC_MethodReplacement() {
...
});
}
}
But for some reason it fails:
Code:
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.android.systemui.statusbar.phone.PhoneStatusBarPolicy" on path: DexPathList[[zip file "/system/framework/services.jar", zip file "/system/framework/ethernet-service.jar", zip file "/system/framework/wifi-service.jar"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
Does anyone have an idea?
Thanks!
You should change lpparam.packageName != "android"
to
lpparam.packageName.equals("android")
Why android? This class is within com.android.systemui package.
C3C076 said:
Why android? This class is within com.android.systemui package.
Click to expand...
Click to collapse
Ah I guess I misread rovos post about the new API with the dummy android package.
In detail, this means: If you want to hook a system service like PackageManagerService, you can no longer do that in initZygote(). Instead, move your code to handleLoadPackage() and check for dummy package "android". Make sure you use lpparam.classLoaders when looking for classes and hooking methods. This way has worked in older Android versions as well, so you don't lose backwards-compatiblity.
Click to expand...
Click to collapse
After reading it again this just applies to system services. And based on some code I saw at your Gravitybox repo it doesn't even seem to apply to all system services as you are still hooking a couple during initZygote
Xposed is new to me, but it's an amazing toolset!
So hooking works fine now, unfortunately it just got a bit ugly as the StatusBarManager which I'd like to use for the icons can't get imported. I guess I'll have to use some reflection to get into the class hehe.

Categories

Resources