Refactor nested IF statement for clarity [closed] - refactoring

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I want to refactor this mumbo jumbo of a method to make it more readible, it has way to many nested IF's for my liking.
How would you refactor this?
public static void HandleUploadedFile(string filename)
{
try
{
if(IsValidFileFormat(filename)
{
int folderID = GetFolderIDFromFilename(filename);
if(folderID > 0)
{
if(HasNoViruses(filename)
{
if(VerifyFileSize(filename)
{
// file is OK
MoveToSafeFolder(filename);
}
else
{
DeleteFile(filename);
LogError("file size invalid");
}
}
else
{
DeleteFile(filename);
LogError("failed virus test");
}
}
else
{
DeleteFile(filename);
LogError("invalid folder ID");
}
}
else
{
DeleteFile(filename);
LogError("invalid file format");
}
}
catch (Exception ex)
{
LogError("unknown error", ex.Message);
}
finally
{
// do some things
}
}

I would reverse the conditions in the test to if bad then deleteAndLog as the example below. This prevent nesting and puts the action near the test.
try{
if(IsValidFileFormat(filename) == false){
DeleteFile(filename);
LogError("invalid file format");
return;
}
int folderID = GetFolderIDFromFilename(filename);
if(folderID <= 0){
DeleteFile(filename);
LogError("invalid folder ID");
return;
}
...
}...

Guard clauses.
For each condition, negate it, change the else block into the then block, and return.
Thus
if(IsValidFileFormat(filename)
{
// then
}
else
{
// else
}
Becomes:
if(!IsValidFileFormat(filename)
{
// else
return;
}
// then

If you are not against using exceptions, you could handle the checks without nesting.
Warning, air code ahead:
public static void HandleUploadedFile(string filename)
{
try
{
int folderID = GetFolderIDFromFilename(filename);
if (folderID == 0)
throw new InvalidFolderException("invalid folder ID");
if (!IsValidFileFormat(filename))
throw new InvalidFileException("invalid file format!");
if (!HasNoViruses(filename))
throw new VirusFoundException("failed virus test!");
if (!VerifyFileSize(filename))
throw new InvalidFileSizeException("file size invalid");
// file is OK
MoveToSafeFolder(filename);
}
catch (Exception ex)
{
DeleteFile(filename);
LogError(ex.message);
}
finally
{
// do some things
}
}

One possible approach is to have single if statements that check for when the condition isn't true. Have a return for each one of these checks. This turns your method into a sequence of 'if' blocks instead of a nest.

There's not a lot to refactor here, as you keep the 3 tests separately due to the fact that the error messages relate to the test performed. You could opt for having the test methods report back the error to log so you don't have them in the if/else tree, which could make things simpler abit as you then could simply test for an error and log it + delete the file.

In David Waters reply, I don't like the repeated DeleteFile LogError pattern. I would either write a helper method called DeleteFileAndLog(string file, string error) or I would write the code like this:
public static void HandleUploadedFile(string filename)
{
try
{
string errorMessage = TestForInvalidFile(filename);
if (errorMessage != null)
{
LogError(errorMessage);
DeleteFile(filename);
}
else
{
MoveToSafeFolder(filename);
}
}
catch (Exception err)
{
LogError(err.Message);
DeleteFile(filename);
}
finally { /* */ }
}
private static string TestForInvalidFile(filename)
{
if (!IsValidFormat(filename))
return "invalid file format.";
if (!IsValidFolder(filename))
return "invalid folder.";
if (!IsVirusFree(filename))
return "has viruses";
if (!IsValidSize(filename))
return "invalid size.";
// ... etc ...
return null;
}

It's the elses above that throw my eye. Here's an alternative, inside the try {}
You can make this even shorter by returning after MoveToSafeFolder (Even though you're returning the finally block will be executed.) Then you don't need to assign an empty string to errorMessage, and you don't need to check is errorString empty before deleting the file and logging the message). I didn't do it here because many find early returns offensive, and I'd agree in this instance, since having the finally block execute after the return is unintuitive for many people.
Hope this helps
string errorMessage = "invalid file format";
if (IsValidFileFormat(filename))
{
errorMessage = "invalid folder ID";
int folderID = GetFolderIDFromFilename(filename);
if (folderID > 0)
{
errorMessage = "failed virus test";
if (HasNoViruses(filename))
{
errorMessage = "file size invalid";
if (VerifyFileSize(filename))
{
// file is OK
MoveToSafeFolder(filename);
errorMessage = "";
}
}
}
}
if (!string.IsNullOrEmpty(errorMessage))
{
DeleteFile(filename);
LogError(errorMessage);
}

I would to something like this:
public enum FileStates {
MoveToSafeFolder = 1,
InvalidFileSize = 2,
FailedVirusTest = 3,
InvalidFolderID = 4,
InvalidFileFormat = 5,
}
public static void HandleUploadedFile(string filename) {
try {
switch (Handledoc(filename)) {
case FileStates.FailedVirusTest:
deletefile(filename);
logerror("Virus");
break;
case FileStates.InvalidFileFormat:
deletefile(filename);
logerror("Invalid File format");
break;
case FileStates.InvalidFileSize:
deletefile(filename);
logerror("Invalid File Size");
break;
case FileStates.InvalidFolderID:
deletefile(filename);
logerror("Invalid Folder ID");
break;
case FileStates.MoveToSafeFolder:
MoveToSafeFolder(filename);
break;
}
}
catch (Exception ex) {
logerror("unknown error", ex.Message);
}
}
private static FileStates Handledoc(string filename) {
if (isvalidfileformat(filename)) {
return FileStates.InvalidFileFormat;
}
if ((getfolderidfromfilename(filename) <= 0)) {
return FileStates.InvalidFolderID;
}
if ((HasNoViruses(filename) == false)) {
return FileStates.FailedVirusTest;
}
if ((VerifyFileSize(filename) == false)) {
return FileStates.InvalidFileSize;
}
return FileStates.MoveToSafeFolder;
}

How about this?
public static void HandleUploadedFile(string filename)
{
try
{
if(!IsValidFileFormat(filename))
{ DeleteAndLog(filename, "invalid file format"); return; }
if(GetFolderIDFromFilename(filename)==0)
{ DeleteAndLog(filename, "invalid folder ID"); return; }
if(!HasNoViruses(filename))
{ DeleteAndLog(filename, "failed virus test"); return; }
if(!!VerifyFileSize(filename))
{ DeleteAndLog(filename, "file size invalid"); return; }
// --------------------------------------------------------
MoveToSafeFolder(filename);
}
catch (Exception ex) { LogError("unknown error", ex.Message); throw; }
finally { // do some things }
}
private void DeleteAndLog(string fileName, string logMessage)
{
DeleteFile(fileName);
LogError(logMessage));
}
or, even better, ... this:
public static void HandleUploadedFile(string filename)
{
try
{
if(ValidateUploadedFile(filename))
MoveToSafeFolder(filename);
}
catch (Exception ex) { LogError("unknown error", ex.Message); throw; }
finally { // do some things }
}
private bool ValidateUploadedFile(string fileName)
{
if(!IsValidFileFormat(filename))
{ DeleteAndLog(filename, "invalid file format"); return false; }
if(GetFolderIDFromFilename(filename)==0)
{ DeleteAndLog(filename, "invalid folder ID"); return false; }
if(!HasNoViruses(filename))
{ DeleteAndLog(filename, "failed virus test"); return false; }
if(!!VerifyFileSize(filename))
{ DeleteAndLog(filename, "file size invalid"); return false; }
// ---------------------------------------------------------------
return true;
}
private void DeleteAndLog(string fileName, string logMessage)
{
DeleteFile(fileName);
LogError(logMessage));
}
NOTE: You shouldn't be catching and swallowing generic Exception without rethrowing it...

Related

How to apply compatplaylist to HwCertTestCollection

For HLK testing automation I would like to apply the compatplaylist on my test list.
Generell automation instruction, but no info how to apply a playlist.
One option is to modify the master test list based on the compatplaylist - both are xml based (with the help of Export-HwCertTestCollectionToXml and import-hwcerttestcollectionfromxml),
But maybe somebody already has a solution or knows an offical support for it.
Try this:-
public static PlaylistManager ApplyPlaylist(Project projectname, string playlistpath)
{
PlaylistManager pl_manager = null;
try
{
pl_manager = new PlaylistManager(projectname);
if (pl_manager == null)
Console.WriteLine("Cannot make playlist manager for the project:- {0}", projectname.Name.ToString());
if(pl_manager.IsPlaylistLoaded() == true)
{
Console.WriteLine("Playlist loaded.. unloading ");
pl_manager.UnloadPlaylist();
if (pl_manager.IsPlaylistLoaded() == false)
Console.WriteLine("Unloaded successfully");
}
else
{
if (File.Exists(playlistpath))
{
pl_manager.LoadPlaylist(playlistpath);
if (pl_manager.IsPlaylistLoaded() == false)
Console.WriteLine("Error in applying playlist:- {0}", playlistpath);
else
Console.WriteLine("Loaded playlist:- {0}", playlistpath);
}
else
{
Console.WriteLine("ERROR!Playlist file {0} not found!", playlistpath);
return pl_manager;
}
}
}
catch(Exception e)
{
Console.WriteLine("Exception:-{0}", e.ToString());
}
return pl_manager;
}

To automate file upload in oracle open script [OATS]

I am very new to Oracle Application Testing Suite(OATS).In my project I need to automate the file uploading functionality. That is , after clicking browse..button , file explorer will open.
My question is how to aytomate this scenario.
I serached many websites and in youtube but did not get any useful. Please help as it is important in my current project. Any help will be appreciated.
Most of file upload based on windows objects .
Open Script doesn't support windows based object identification for that we have to use external plugin or jar files
best suitable one is RobotClass .
Here is the complete example
http://www.testinghive.com/how-to-perform-file-upload-in-oats-tool/
try
{
Robot robot = new Robot();
robot.delay(200);
upload_parseChars("C:\\testDemo.xlsx", robot);
robot.delay(200);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
catch (AWTException e) {
e.printStackTrace();
}
public void upload_parseChars(String letter, Robot robot) throws AbstractScriptException {
for (int i = 0; i < letter.length(); i++) {
//info("inside uf_Vik_parseChars method ");
char chary = letter.charAt(i);
//info("Current character = "+letter.charAt(i));
upld_typeCharacter(Character.toString(chary), robot);
}
}
public void upld_typeCharacter(String letter, Robot robot) throws AbstractScriptException {
// info("Pressed event ");
if (Character.isLetterOrDigit(letter.charAt(0))) {
try {
boolean upperCase = Character.isUpperCase(letter.charAt(0));
String variableName = "VK_" + letter.toUpperCase();
KeyEvent ke = new KeyEvent(new JTextField(), 0, 0, 0, 0, ' ');
#SuppressWarnings("rawtypes")
Class clazz = ke.getClass();
Field field = clazz.getField(variableName);
int keyCode = field.getInt(ke);
robot.delay(80);
if (upperCase)
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(keyCode);
robot.keyRelease(keyCode);
if (upperCase)
robot.keyRelease(KeyEvent.VK_SHIFT);
} catch (Exception e) {
System.out.println(e);
}
} else {
if (letter.equals("!")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_2);
robot.keyRelease(KeyEvent.VK_2);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("$")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_4);
robot.keyRelease(KeyEvent.VK_4);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("%")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_5);
robot.keyRelease(KeyEvent.VK_5);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("^")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_6);
robot.keyRelease(KeyEvent.VK_6);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("&")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_7);
robot.keyRelease(KeyEvent.VK_7);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("*")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_8);
robot.keyRelease(KeyEvent.VK_8);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("=")) {
robot.keyPress(KeyEvent.VK_EQUALS);
robot.keyRelease(KeyEvent.VK_EQUALS);
} else if (letter.equals(" ")) {
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
} else if (letter.equals("/")) {
robot.keyPress(KeyEvent.VK_BACK_SLASH);
robot.keyRelease(KeyEvent.VK_BACK_SLASH);
} else if (letter.equals("\\")) {
robot.keyPress(KeyEvent.VK_BACK_SLASH);
robot.keyRelease(KeyEvent.VK_BACK_SLASH);
} else if (letter.equals("_")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(":")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(";")) {
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
} else if (letter.equals(",")) {
robot.keyPress(KeyEvent.VK_COMMA);
robot.keyRelease(KeyEvent.VK_COMMA);
} else if (letter.equals("-")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SUBTRACT);
robot.keyRelease(KeyEvent.VK_SUBTRACT);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("?")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SLASH);
robot.keyRelease(KeyEvent.VK_SLASH);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(" ")) {
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
} else if (letter.equals(".")) {
robot.keyPress(KeyEvent.VK_PERIOD);
robot.keyRelease(KeyEvent.VK_PERIOD);
}
}
}
THE download dialog and upload dialog is supported. try to record one and try related

How to initiate a Video call using lync sdk?

My Aim: I want to initiate a video call from the start.
My Problem: It is getting initiated into audio call and then it's turning into video after end user answers the call.
void ConversationManager_ConversationAdded_Video(object sender, ConversationManagerEventArgs e)
{
Console.WriteLine("Inside conversation added for Video");
if (e.Conversation.Modalities[ModalityTypes.AudioVideo].State != ModalityState.Notified)
{
if (e.Conversation.CanInvoke(ConversationAction.AddParticipant))
{
try
{
e.Conversation.ParticipantAdded += Conversation_ParticipantAdded_Video;
e.Conversation.AddParticipant(client.ContactManager.GetContactByUri(receipient));
}
catch (ItemAlreadyExistException ex)
{
}
}
}
}
void Conversation_ParticipantAdded_Video(object source, ParticipantCollectionChangedEventArgs data)
{
if (data.Participant.IsSelf != true)
{
if (((Conversation)source).Modalities[ModalityTypes.AudioVideo].CanInvoke(ModalityAction.Connect))
{
object[] asyncState = { ((Conversation)source).Modalities[ModalityTypes.AudioVideo], "CONNECT" };
try
{
((Conversation)source).Modalities[ModalityTypes.AudioVideo].ModalityStateChanged += _AVModality_ModalityStateChanged_Video;
Console.WriteLine("entered video Satheesh participant added");
// ((Conversation)source).Modalities[ModalityTypes.AudioVideo].BeginConnect(ModalityCallback, asyncState);
((Conversation)source).Modalities[ModalityTypes.AudioVideo].BeginConnect(ModalityCallback, asyncState);
//((Conversation)source).Modalities[ModalityTypes.AudioVideo].EndConnect(ModalityCallback, asyncState);
Thread.Sleep(6000);
Console.WriteLine(source);
Console.WriteLine("entered video participant added");
}
catch (LyncClientException lce)
{
throw new Exception("Lync Platform Exception on BeginConnect: " + lce.Message);
}
}
}
}
public void ModalityCallback(IAsyncResult ar)
{
Object[] asyncState = (Object[])ar.AsyncState;
try
{
if (ar.IsCompleted == true)
{
if (asyncState[1].ToString() == "RETRIEVE")
{
((AVModality)asyncState[0]).EndRetrieve(ar);
}
if (asyncState[1].ToString() == "HOLD")
{
((AVModality)asyncState[0]).EndHold(ar);
}
if (asyncState[1].ToString() == "CONNECT")
{
Console.WriteLine("inside connect method CONNECT");
((AVModality)asyncState[0]).EndConnect(ar);
}
if (asyncState[1].ToString() == "FORWARD")
{
((AVModality)asyncState[0]).EndForward(ar);
}
if (asyncState[1].ToString() == "ACCEPT")
{
((AVModality)asyncState[0]).Accept();
}
}
}
catch (LyncClientException)
{ }
}
public void _AVModality_ModalityStateChanged_Video(object sender, ModalityStateChangedEventArgs e)
{
Console.WriteLine(sender);
Console.WriteLine("entered video modality changed");
switch (e.NewState)
{
case ModalityState.Connected:
if (_VideoChannel == null)
{
_VideoChannel = ((AVModality)sender).VideoChannel;
_VideoChannel.StateChanged += new EventHandler<ChannelStateChangedEventArgs>(_VideoChannel_StateChanged);
}
if (_VideoChannel.CanInvoke(ChannelAction.Start))
{
Console.WriteLine("entered video modality changed123");
_VideoChannel.BeginStart(MediaChannelCallback, _VideoChannel);
}
break;
case ModalityState.OnHold:
break;
case ModalityState.Connecting:
case ModalityState.Forwarding:
break;
case ModalityState.Transferring:
break;
}
}
private void MediaChannelCallback(IAsyncResult ar)
{
((VideoChannel)ar.AsyncState).EndStart(ar);
}
I Think it is because you call _AVModality_ModalityStateChanged_Video in ParticipantAdded event.
that means that you start your video when the person you call (the new participant) joins the conversation. thats why it is getting initiated into audio call and then it's turning into video after end user answers the call.
The solution is to fire a new event : ConversationStateChangedEvent
this is where I did it and works fine :
/// <summary>
/// Handles event raised when New meetNow window change it's state
/// </summary>
private void _NewMeetNowConversation_StateChanged(object sender, ConversationStateChangedEventArgs e)
{
Conversation conference = (Conversation)sender;
switch(e.NewState)
{
case ConversationState.Active:
conference.Modalities[ModalityTypes.AudioVideo].ModalityStateChanged += AVConferenceModalityStateChanged;
conference.ParticipantAdded += ConfParticipantAdded;
break;
case ConversationState.Terminated: //conversation window completely closed
break;
case ConversationState.Inactive:
break;
case ConversationState.Parked:
break;
case ConversationState.Invalid:
break;
}
}

How can I input a email and let me register only if it contains # and .com

How do I validate an email address?
An address should have a "# " and end ".com "
Here's the code I used:
public void email(){
String a = "qwertyuiopasdfghjklzxcqwertyuiopasdfghjklzxcvbnmvbnmqwertyuiopasdfghjklzxcvbnm#qwertyuiopasdfghjklzxcvbnmqwertyuiopaqwertyuiopasdfghjklzxcvbnmsdfghjklzxcvbnm.com";
String b = JOptionPane.showInputDialog("Enter email");
try{
if(!b.contains(a)){
throw new Error("Incorrect");
}else{
System.out.println("Correct");
}
} catch (Error e){
System.out.println(""+e);
}
}
I think this might help you. From: What is the best Java email address validation method?
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}

Code to execute if a navigation fails

Hello I have no idea where I should start looking. I add few prop (before that my code run fine), then I get
System.Diagnostics.Debugger.Break();
so then I comment that changes, but that didn't help.
Could you suggest me where I should start looking for solution?
MyCode:
namespace SkydriveContent
{
public partial class MainPage : PhoneApplicationPage
{
private LiveConnectClient client;
FilesManager fileManager = new FilesManager();
// Constructor
public MainPage()
{
InitializeComponent();
}
private void signInButton1_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
infoTextBlock.Text = "Signed in.";
client.GetCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetAsync("/me/skydrive/files/");
fileManager.CurrentFolderId = "/me/skydrive/files/";
}
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}
void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
//Gdy uda nam się podłaczyc do konta skydrive
if (e.Error == null)
{
signInButton1.Visibility = System.Windows.Visibility.Collapsed;
infoTextBlock.Text = "Hello, signed-in user!";
List<object> data = (List<object>)e.Result["data"];
fileManager.FilesNames.Clear();
filemanager.filesnames.add("..");
foreach (IDictionary<string,object> item in data)
{
File file = new File();
file.fName = item["name"].ToString();
file.Type = item["type"].ToString();
file.Url = item["link"].ToString();
file.ParentId = item["parent_id"].ToString();
file.Id = item["id"].ToString();
fileManager.Files.Add(file);
fileManager.FilesNames.Add(file.fName);
}
FileList.ItemsSource = fileManager.FilesNames;
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
}
private void FileList_Tap(object sender, GestureEventArgs e)
{
foreach (File item in fileManager.Files)
{
if (item.fName == FileList.SelectedItem.ToString() )
{
switch (item.Type)
{
case "file":
MessageBox.Show("Still in progress");
break;
case "folder":
fileManager.CurrentFolderId = item.ParentId.ToString();
client.GetAsync(item.Id.ToString() + "/files");
break;
default:
MessageBox.Show("Coś nie działa");
break;
}
}
else if (FileList.SelectedItem.ToString() == "..")
{
client.GetAsync(fileManager.CurrentFolderId + "/files");
}
}
}
}
}
Running stop at that line.
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
You should check all of the URLs you have both in the XAML and code. When you get to the NavigationFailed function, it means that the phone tried to navigate to some page that did not existed. We would be able to help more if you could tell what were you doing when the app threw the exception.
System.Diagnostics.Debugger.Break();
usually happens because of an Uncaught Exception.
Either post the code which started giving problems, or the stack trace when you encounter this problem.
No one can tell anything without actually seeing what you are doing.

Resources