wp7: App failing! Can not figure out where? - visual-studio-2010

I think I've narrowed it down to this code in the Deactivation event:
Here's the thing... When I put a break point in this code everything works fine. The application does NOT fail. However, when I take the break point off it fails. What I don't understand is why the try/catch isn't firing.
I should also note that I commented everything out of this event with no break point and the application worked fine. So it is something in this code...
Could it be that the Save Event is not finished for the unsaved object and when it tries to reactivate the Activation event is actually the one failing???
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
//MessageBox.Show("deactivated");
try
{
//if ((Application.Current as App).infoSaved == false)
//{
unsaved unSavedPillInfo = new unsaved();
unSavedPillInfo.RXName = (Application.Current as App).appRXName;
unSavedPillInfo.RXNumber = (Application.Current as App).appRXNumber;
unSavedPillInfo.DosageNotes = (Application.Current as App).appDosageNotes;
unSavedPillInfo.Generic = (Application.Current as App).appGeneric;
unSavedPillInfo.Instructions = (Application.Current as App).appInstructions;
unSavedPillInfo.Reason = (Application.Current as App).appReason;
unSavedPillInfo.Quantity = (Application.Current as App).appQuantity;
unSavedPillInfo.Refills = (Application.Current as App).appRefills;
unSavedPillInfo.Doctor = (Application.Current as App).appDoctor;
unSavedPillInfo.DoctorNumber = (Application.Current as App).appDoctorNumber;
unSavedPillInfo.Pharmacy = (Application.Current as App).appPharmacy;
unSavedPillInfo.PharmacyNumber = (Application.Current as App).appPharmacyNumber;
unSavedPillInfo.OrigDate = (Application.Current as App).appOrigDate;
unSavedPillInfo.ReorderReminder = (Application.Current as App).appReorderReminder;
unSavedPillInfo.ReorderDate = (Application.Current as App).appReorderDate;
unSavedPillInfo.ConsumptionFrequency = (Application.Current as App).appConsumptionFrequency;
unSavedPillInfo.PerscriptionUpdated = (Application.Current as App).perscriptionUpdated;
unSavedPillInfo.PerscriptionUpdated = (Application.Current as App).doctorUpdated;
unSavedPillInfo.PerscriptionUpdated = (Application.Current as App).detailsUpdated;
unSavedPillInfo.PerscriptionUpdated = (Application.Current as App).pharmacyUpdated;
unSavedPillInfo.Save();
//}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

This is hardly perfect but try putting a Messagebox inside of each of the eventhandlers. That way you can tell when each one is firing and see if one isn't firing.
Also you might want to unistall the application often to clear the IsolatedStorage. This is known to create issues if you keep running on the same installation.
EDIT: Yeah from what I have run into, the application can hang if you aren't properly saving to isolated storage. It can also happen if you aren't properly loading data from isolated storage. You might want to try each one seperately. Use a messagebox to make sure it saves and loads properly because VisualStudio will exit the current debugging session.
UPDATE What you should do is create a global variable called unsavedPrescription. Now when the user selects a prescription assign the global variable "unsaved" the prescription they selected. Note: you should not be assigning properties when the app is deactivating because it is very possible it won't save completely which leads to the app hanging. Instead all you have to do is assign the selected prescription to the global variable and change your code in App.xaml.cs to the following:
public unsaved unsavedPrescription {get; set;}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
//Open up IsolatedStorageSettings
IsolatedStorageSettings settings = Isolated StorageSettings.ApplicationSettings;
//Use a model to save prescription
//So create a name/value pair to store the prescription in isolatedstorage
//Notice we used the global variable
settings["UnsavedPrescription"] = unsavedPrescription;
}
private void Application_Activated(object sender, ActivatedEventArgs e)
{
//Now you can easily load the prescription you saved
//I'm reassigning the global variable that will contain the savedprescription
if(settings.TryGetValue("UnsavedPrescription", out prescription)
{
unsavedPrescription = prescription;
}
}
This greatly simplifies your code when loading and saving. Also you'll be able to test using the messageboxes like I said earlier, which isn't professional but it works nicely. Also your not running too much stuff when the app is trying to deactivate. THIS WAY WILL WORK AS I TESTED IT. The way you did it above looks like your running to much code while the app is deactivating which is probably why its hanging. Also this explains why when you remove it, everything works.

I had a problem that seems similar to yours that wasn't actually related to the Saving/Loading from IsolatedStorage itself, but rather the property I was setting / getting had inifinite recursion. This caused the application to terminate before getting to Catch statements.
It might be worthwhile for you to turn off the Debugger stepping over Properties:
Tools -> Options -> Debugger -> Step over Properties and Operators (Managed Only)
public Dictionary<string, object> Dictionary
{
get
{
if (_dictionary == null)
_dictionary = new Dictionary<string, object>();
return _dictionary;
}
set
{
Dictionary = value;
}
}
App Never launches successfully again after Tombstoning. No exception thrown

Related

Telerik Winforms Reports freeze on Terminal Services

I am using Telerik reports in our app and it is being accessed mostly through an RDP session running in "app mode". Everything works fine locally but when I put it on the TS machine it freezes after the print dialog comes up.
The standard print dialog comes up and you can choose the printer and hit ok but then a small box opens with header of Printing... and then never does anything.
I am not sure what code to post since its fine locally, let me know what you want to see. also printing other things like the Telerik grids and charts are fine.
Found the answer on my own.
I created a standard printdialog screen and "rolled my own" print method and all seems to be good. Hope this helps someone else.
private void reportViewer1_Print(object sender, CancelEventArgs e)
{
this.Cursor = Cursors.WaitCursor;
e.Cancel = true;
try
{
PrintDialog pd = new PrintDialog();
pd.PrinterSettings = new System.Drawing.Printing.PrinterSettings();
var result = pd.ShowDialog();
if (result ==DialogResult.OK)
{
// Print the report using the custom print controller
var reportProcessor
= new Telerik.Reporting.Processing.ReportProcessor();
reportProcessor.PrintReport(this.reportViewer1.ReportSource, pd.PrinterSettings);
}
}
catch (Exception ex)
{
Program.ExceptionHandler(ex);
}
this.Cursor = Cursors.Default;
}

Custom live tile rendering issue on Windows Phone (7/8)

In my Windows Phone app's main page, users can click a button to do some stuff and that will trigger the live tile to update.
The problem I am having is, if the user clicks the button and then hit the phone's Back button really quickly, the live tile sometimes will not render properly. This issue rarely happens, but it does happen and when it happens it just looks bad...
The way I implement the live tile is, create a user control that looks exactly the same as the live tile and then save it to isolated storage. Then retrieve it and store it in a FliptileData object. Finally I call the Update method on the ShellTile. Please see the following piece of code to demonstrate the process.
// the function that saves the user control to isolated storage
public Uri SaveJpegToIsolatedStorage(FrameworkElement tile, string suffix, int tileWidth = 336, int tileHeight = 336)
{
var bmp = new WriteableBitmap(tileWidth, tileHeight);
// Force the content to layout itself properly
tile.Measure(new Size(tileWidth, tileHeight));
tile.Arrange(new Rect(0, 0, tileWidth, tileHeight));
bmp.Render(tile, null);
bmp.Invalidate();
// Obtain the virtual store for the application
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(IsolatedStorageFileName + suffix, FileMode.Create, myStore))
{
try
{
bmp.SaveJpeg(fileStream, tileWidth, tileHeight, 0, 100);
}
catch (Exception)
{
return null;
}
}
return new Uri("isostore:/" + IsolatedStorageFileName + suffix, UriKind.Absolute);
}
// save the user control to isolated storage and prepare the FlipTileData object
wideFrontTileImage = SaveJpegToIsolatedStorage((UserControl)this.WideFrontTile, "_wide_front", 691);
var flipTileData = new FlipTileData();
flipTileData.WideBackgroundImage = wideFrontTileImage;
return flipTileData;
// update the live tile
var shellTile = ShellTile.ActiveTiles.FirstOrDefault();
shellTile.Update(customTile.GetFlipTileData(data.UndoneMemosCount == "0" && data.TotalMemosCount == "0"));
I think the reason that's causing all this is, when the user clicks the Back button too quickly, the OS terminates all the processes running within the app and the rendering wasn't done at that time. I'm thinking if there's a way to know when the rendering is finished, so I can cancel the Back button and wait until it's finished then manually exit the app. But I simply dunno how...
Any help on this one will be greatly appreciated!
I have ran into similar issue in my WP8 app. The problem was that I was updating my Tile in ApplicationDeactivated event handler. The thing is you should not update your tiles there, but rather in your MainPage.OnNavigatedFrom override. Once I changed this, it works just fine.

wp7 background process during application runs

I have a project which includes many pages. I want to import information to my database periodically whatever the situation of my application is.
I tried to put my code inside App.xaml.cs but it is only saves data for once (I put it inside launching and tried in Constructor. My method is getting device id's location which is like
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
Location loc = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);
//Send Data to Database
dclient.CreateUserLocationCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(dclient_CreateUserLocationCompleted);
dclient.CreateUserLocationAsync(1, loc.Latitude, loc.Longitude);
}
and my watcher position changed is inside the constructor.
if (watcher == null)
{
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
}
MovementThreshold = getSelectedDeviceLocationFrequencyFromInternalFolder();
watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
watcher.Start();
and defined globally inside the App.xaml.cs
How can I run this periodically all the time while program runs ? Any other way ? Thanks (To sum up I want to insert the location data periodically to my database.)
You will need to launch a thread when the app launches that sleeps for whatever time it wants to (or wake up on a signal from the app - when the new value is received) and writes the data to your data store inside it.

How to I get access NavigationService in a WIndows Phone app without going through a PhoneApplicationPage?

How to I get access NavigationService in a Windows Phone app without going through a PhoneApplicationPage? My goal is to pass it to the application's primary view-model on startup, a technique that worked quite well for me in WPF and Silverlight.
You can get it from the app's PhoneApplicationFrame. It will be accessible from anywhere in the app since every Windows Phone app has a Frame.
((PhoneApplicationFrame)Application.Current.RootVisual).Navigate(...);
Another place to get it is from the RootFrame field in the default implementation of Application:
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion

How to call webservice methods in Windows Phone 7?

For connecting to webservices i wrote the following code.
WebClient wc = new WebClient();
wc.DownloadStringAsync(new Uri("http://www.Webservices.asmx"));
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
void wc_DownloadStringCompleted(object sender,DownloadStringCompletedEventArgs e)
{
Debug.WriteLine("Web service says: " + e.Result);
using (var reader = new StringReader(e.Result))
{
String str = reader.ReadToEnd();
}
}
by using above code Get the string result.But i want get the result in HTMLVisulaizer then i know the what are the methods having that webservice.then i can easily access the particular method.
Please tell me how to call a web service method in Windows phone 7?in webservice i am having 5 webmethods.how to get that and how to call the Particular webmenthod.
Please tell me thanks in advance.
#venkateswara Are you talking about obtaining a list of known WebReference methods so you know which one to call in you code? Do you not see the this of known method calls when you add the WebReference to your WP7 project? Since you will be developing the WP7 app in VS I can't see the reason you would want to do this. Even if you don't own the webservice yourself, you will need to connect to it from VS in order to add the reference to your project.
Below is the screen in VS2010 where a WebReference is added. The Operations are listed on the right.
Once added you can use the ObjectBrowser to understand how the methods should be called.
Please let me know if I have missed something from your question.
#Jason James
The first step:
You must add referent Services ,like Jason James has very detailed instructions .
step 2 :
You can open App.xaml.cs , in Functions Apps
public Apps()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are being GPU accelerated with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
}
// You can declare objects here that you will use
//Examlpe: NameservicesReferent.(Function that returns services) = new NameservicesReferent.(Function that returns services)();
Ws_Function = new Nameservices.ServiceSoapClient();
}
step 3:
in Mainpage.xaml.cs
GlobalVariables.Ws_advertise.getLinkAdvertiseIndexCompleted += new EventHandler<advertise.getLinkAdvertiseIndexCompletedEventArgs>(Ws_advertise_getLinkAdvertiseIndexCompleted);
GlobalVariables.***NameWedservise***.getLinkAdvertiseIndexAsync("**parameters to be passed**");
step 4:
void Ws_advertise_getLinkAdvertiseIndexCompleted(object sender, advertise.getLinkAdvertiseIndexCompletedEventArgs e)
{
//function returns the results to you, the example here is an array
string[] array = null;
try
{
array = e.result;
if(array != null)
}
cath(exception ex)
{
}
finally
{
array = null;
GlobalVariables.Ws_advertise.getLinkAdvertiseIndexCompleted -= new EventHandler<advertise.getLinkAdvertiseIndexCompletedEventArgs>(Ws_advertise_getLinkAdvertiseIndexCompleted);
}
}

Resources