WebClient.DownloadStringAsync webexception wp7 - windows-phone-7

I'm trying to remove a node from an xml file, everything works, but sometimes it happens that the xml web page does not load. this is my code:
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
if (e.Error == null)
{
XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);
var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
TextBlock1.Text = lyric.Value;
}
}
}
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad));
}
I' ve read to use the WebException to handle this "mistake" but I am not able to use it. can someone give me some help?

Have you tried this way?
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
try
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad"));
}
catch (WebException ex)
{
// Check the exception here
}
}
And check for error in the handler too:
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
if (e.Error == null)
{
XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);
var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
TextBlock1.Text = lyric.Value;
}
}
else
{
// Check for error here
}
}
I realized it sometimes return Error, and I think the problem is in the server, because if I access it from the web browser, I sometimes get the result, but many times I get an error.

Related

Issue while Playing, the recorded audio in WP7

Hi Developers,
If we save the recorded voice as a mp3 file. we get the error while opening the file as Windows Media Player cannot play the file. The Player might not support the file type or might not support the codec that was used to compress the file.
Please Give a Solution to overcome this Issue ....
Here is My Source code
namespace Windows_Phone_Audio_Recorder
{
public partial class MainPage : PhoneApplicationPage
{
MemoryStream m_msAudio = new MemoryStream();
Microphone m_micDevice = Microphone.Default;
byte[] m_baBuffer;
SoundEffect m_sePlayBack;
ViewModel vm = new ViewModel();
long m_lDuration = 0;
bool m_bStart = false;
bool m_bPlay = false;
private DispatcherTimer m_dispatcherTimer;
public MainPage()
{
InitializeComponent();
SupportedOrientations = SupportedPageOrientation.Portrait | SupportedPageOrientation.Landscape;
DataContext = vm;
m_dispatcherTimer = new DispatcherTimer();
m_dispatcherTimer.Interval = TimeSpan.FromTicks(10000);
m_dispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
m_dispatcherTimer.Start();
FrameworkDispatcher.Update();
//icBar.ItemsSource = vm.AudioData;
}
void frameworkDispatcherTimer_Tick(object sender, EventArgs e)
{
FrameworkDispatcher.Update();
}
private void btnStart_Click(object sender, RoutedEventArgs e)
{
m_bStart = true;
tbData.Text = "00:00:00";
m_lDuration = 0;
m_micDevice.BufferDuration = TimeSpan.FromMilliseconds(1000);
m_baBuffer = new byte[m_micDevice.GetSampleSizeInBytes(m_micDevice.BufferDuration)];
//m_micDevice.BufferReady += new EventHandler(m_Microphone_BufferReady);
m_micDevice.BufferReady += new EventHandler<EventArgs>(m_Microphone_BufferReady);
m_micDevice.Start();
}
void m_Microphone_BufferReady(object sender, EventArgs e)
{
m_micDevice.GetData(m_baBuffer);
Dispatcher.BeginInvoke(()=>
{
vm.LoadAudioData(m_baBuffer);
m_lDuration++;
TimeSpan tsTemp = new TimeSpan(m_lDuration * 10000000);
tbData.Text = tsTemp.Hours.ToString().PadLeft(2, '0') + ":" + tsTemp.Minutes.ToString().PadLeft(2, '0') + ":" + tsTemp.Seconds.ToString().PadLeft(2, '0');
}
);
//this.Dispatcher.BeginInvoke(new Action(() => vm.LoadAudioData(m_baBuffer)));
//this.Dispatcher.BeginInvoke(new Action(() => tbData.Text = m_baBuffer[0].ToString() + m_baBuffer[1].ToString() + m_baBuffer[2].ToString() + m_baBuffer[3].ToString()));
m_msAudio.Write(m_baBuffer,0, m_baBuffer.Length);
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
if (m_bStart)
{
m_bStart = false;
m_micDevice.Stop();
ProgressPopup.IsOpen = true;
}
if (m_bPlay)
{
m_bPlay = false;
m_sePlayBack.Dispose();
}
}
private void btnPlay_Click(object sender, RoutedEventArgs e)
{
m_bPlay = true;
m_sePlayBack = new SoundEffect(m_msAudio.ToArray(), m_micDevice.SampleRate, AudioChannels.Mono);
m_sePlayBack.Play();
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (txtAudio.Text != "")
{
IsolatedStorageFile isfData = IsolatedStorageFile.GetUserStoreForApplication();
string strSource = txtAudio.Text + ".wav";
int nIndex = 0;
while (isfData.FileExists(txtAudio.Text))
{
strSource = txtAudio.Text + nIndex.ToString().PadLeft(2, '0') + ".wav";
}
IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(strSource, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());
isfStream.Write(m_msAudio.ToArray(), 0, m_msAudio.ToArray().Length);
isfStream.Close();
}
this.Dispatcher.BeginInvoke(new Action(() => ProgressPopup.IsOpen = false));
}
}
}
DotNet Weblineindia
my Source Code For UPLOADING A AUDIO TO PHP SERVER:
public void UploadAudio()
{
try
{
if (m_msAudio != null)
{
var fileUploadUrl = "uploadurl";
var client = new HttpClient();
m_msAudio.Position = 0;
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StreamContent(m_msAudio), "uploaded_file", strFileName);
// upload the file sending the form info and ensure a result.it will throw an exception if the service doesn't return a valid successful status code
client.PostAsync(fileUploadUrl, content)
.ContinueWith((postTask) =>
{
try
{
postTask.Result.EnsureSuccessStatusCode();
var respo = postTask.Result.Content.ReadAsStringAsync();
string[] splitChar = respo.Result.Split('"');
FilePath = splitChar[3].ToString();
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/VoiceSlider.xaml?FName=" + strFileName, UriKind.Relative)));
}
catch (Exception ex)
{
// Logger.Log.WriteToLogger(ex.Message);
MessageBox.Show("voice not uploaded" + ex.Message);
}
});
}
}
catch (Exception ex)
{
//Logger.Log.WriteToLogger(ex.Message + "Error occured while uploading image to server");
}
}
First of all Windows Phone does not allow to record .mp3 files. So, the .mp3 file that you are saving will not be played by Windows Phone player.
Have a look at this. This demo is working fine for recording .wav file.
If you wish to save other formats like .aac,.amr then user AudioVideoCaptureDevice class.

PositionChanged & StatusChanged event getting fired twice in WP7

I am trying to getting coordinates with the help of GPS and when i am putting a dry run or debug the event makes PositionChange & StatusChange to call TWICE. Here is my code please help me.
private void button1_Click(object sender, RoutedEventArgs e)
{
if (NetworkInterface.GetIsNetworkAvailable())
{
flag = true;
if (watcher == null)
{
watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
watcher.MovementThreshold = 20;
watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
watcher.Start();
}
}
}
void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
MessageBox.Show("Location Service is not enabled on the device");
break;
case GeoPositionStatus.NoData:
MessageBox.Show(" The Location Service is working, but it cannot get location data.");
break;
}
}
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (e.Position.Location.IsUnknown)
{
MessageBox.Show("Please wait while your prosition is determined....");
return;
}
List<string> locationData = new List<string>();
locationData.Add(e.Position.Location.Latitude.ToString("Latitude:" + "0.000"));
locationData.Add(e.Position.Location.Longitude.ToString("Longitude:" + "0.000"));
locationData.Add(e.Position.Location.Altitude.ToString());
locationData.Add(e.Position.Location.Speed.ToString());
locationData.Add(e.Position.Location.Course.ToString());
}
It's called twice because the status changes from
Initializing -> Ready
For Initializing it fires once and For ready the second time :)

Set the query string, but still get NullReferenceException

I want to show the error message on the other page. I got the NullReferenceException, but the query string is set on the page which has error. Would someone tell me what is wrong with my code?
catch (Exception ex)
{
//Dispatcher.BeginInvoke(new Action(() =>MessageBox.Show(ex.StackTrace,"Error!",MessageBoxButton.OK)));
string query=#"/ErrorPage.xaml?msg=" + ex.StackTrace.ToString() ;
Dispatcher.BeginInvoke(new Action(() =>this.NavigationService.Navigate(new Uri(query, UriKind.Relative))));
}
There is the code for showing the error message when the page is loaded on other page
public ErrorPage()
{
InitializeComponent();
string msg = NavigationContext.QueryString["msg"].ToString();
lstMessage.Items.Add(msg);
}
I should put my code into the MainPage_Load method. It works.
public ErrorPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
MessageBoxResult result = MessageBox.Show(CMSPhoneApp.App.GlobalVariables.strNofifyEmailSubject,
"Report Error", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
//according to the serach it works on real devices (not on the emulator)
//the reason the EmailComposer not pop up because can't set up an email account on the emulator
EmailComposeTask emailcomposer = new EmailComposeTask();
emailcomposer.To = CMSPhoneApp.App.GlobalVariables.reportAddress;
emailcomposer.Subject = CMSPhoneApp.App.GlobalVariables.strNofifyEmailSubject;
emailcomposer.Body = CMSPhoneApp.App.GlobalVariables.errorMsg;
emailcomposer.Show();
}
else
{
App.GoBack();
}
}

NotImplementedException when handling errors in Global.asax Application_Error

I have code
protected void Application_Error(object sender, EventArgs e)
{
HttpContext ctx = HttpContext.Current;
Exception ex = ctx.Server.GetLastError();
ctx.Response.Clear();
var viewResult = new ViewResult();
if (ex.GetType() != typeof(SecurityException))
{
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
IController controller = new ModuleController();
var context = new ControllerContext(rc, (ControllerBase)controller);
var httpException = ex as HttpException;
if (httpException != null)
{
switch (httpException.GetHttpCode())
{
case 404:
viewResult.ViewName = "Error404";
Response.StatusCode = 404;
break;
case 500:
viewResult.ViewName = "Error500";
Response.StatusCode = 500;
break;
default:
viewResult.ViewName = "Error";
Response.StatusCode = httpException.GetHttpCode();
break;
}
}
else
{
viewResult.ViewName = "Error";
}
viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action"));
viewResult.ExecuteResult(context);
ctx.Server.ClearError();
}
else
{
var context = new ControllerContext { RouteData = new RouteData() };
context.RouteData.Values.Add("controller", "Security");
context.Controller = new SecurityController();
HttpCookie cookie = this.mebershipService.GetCookie();
cookie.Expires = DateTime.Now.AddDays(-1);
this.Context.Response.Cookies.Add(cookie);
viewResult.ViewName = "HackedDetect";
Response.StatusCode = 403;
viewResult.ExecuteResult(context);
ctx.Server.ClearError();
}
}
When processing SecurityException, and the call controller that does not relate to the system (in order not to walk in a circle) on the code viewResult.ExecuteResult (context); be a NotImplementedException
But I was not clear which method or operation is not defined.
That's what copied to the clipboard from the mistakes
System.NotImplementedException not handled by user code
HResult = -2147467263
Message = The method or operation is not implemented.
Source = System.Web
StackTrace:
in System.Web.HttpContextBase.get_Response ()
in System.Web.Mvc.ViewResultBase.ExecuteResult (ControllerContext context)
in SGN.Web.MvcApplication.Application_Error (Object sender, EventArgs e) in C: \ Project \ SGN \ SGN.Web \ Global.asax.cs: line 142
in System.EventHandler.Invoke (Object sender, EventArgs e)
in System.Web.HttpApplication.RaiseOnError ()
InnerException:
UPDATE
I'll write what I do to get this error
I created custom Identity class and when is initialized, I'm validate the cookie. If cookie not validate I create SecurityException

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