开发者

How to reset if Null? XML Linq

开发者 https://www.devze.com 2023-03-29 08:24 出处:网络
I curently have the below which displasy a messagebox.show if the results is null. But it still gives me an unhandled exception.

I curently have the below which displasy a messagebox.show if the results is null. But it still gives me an unhandled exception.

How can I stop the exception and just let the user enter a different value?

void Trademe_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;
            if (e.Error == null)


                MessageBox.Show("Wrong try Again");

            var r = XDocument.Parse(e.Result);

Full code for clarity *****************

namespace TradeMe
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            WebClient Trademe = new WebClient();
            Trademe.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Trademe_DownloadStringCompleted);
            Trademe.DownloadStringAsync(new Uri("http://api.trademe.co.nz/v1/Search/General.xml?search_string=" + TradeSearch.Text));

            progressBar1.IsIndeterminate = true;
            progressBar1.Visibility = Visibility.Visible;


        }



        void Trademe_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error != null)
                return;






            var r = XDocument.Parse(e.Result);
            if (e.Result == null)
                MessageBox.Show("Wrong try Again");


          开发者_如何学C  // Declare the namespace
            XNamespace ns = "http://api.trademe.co.nz/v1";
            listBox1.ItemsSource = from TM in r.Root.Descendants(ns + "Listing").Take(50)
                                   select new TradeItem
                                   {
                                       ImageSource = TM.Element(ns + "PictureHref").Value,
                                       Title = TM.Element(ns + "Title").Value,
                                       Region = TM.Element(ns + "Region").Value,
                                       PriceDisplay = TM.Element(ns + "PriceDisplay").Value,
                                       ListingId = TM.Element(ns + "ListingId").Value,
                                   };

           ;

            progressBar1.IsIndeterminate = false;
            progressBar1.Visibility = Visibility.Collapsed;
        }



        public class TradeItem
        {
            public string Region { get; set; }
            public string ListingId { get; set; }
            public string PriceDisplay { get; set; }
            public string Title { get; set; }
            public string ImageSource { get; set; }
        }

        private void hyperlinkButton1_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/TestPage.xaml", UriKind.Relative));
        }

        private void eventhandler(object sender, SelectionChangedEventArgs e)
        {
            var item = (sender as ListBox).SelectedItem as TradeItem;

            if (item != null)
            {
                string id = item.ListingId.ToString();
                NavigationService.Navigate(new Uri("/TestPage.xaml?ListingId=" + id, UriKind.Relative));
            }


        }


    }
}

Full stack trace **************

   at TradeMe.MainPage.<>c__DisplayClass2.<Trademe_DownloadStringCompleted>b__1(XElement TM)
   at System.Linq.Enumerable.<SelectIterator>d__d`2.MoveNext()
   at System.Windows.Controls.ItemCollection.EnumerableCollectionView.InitializeSnapshot()
   at System.Windows.Controls.ItemCollection.EnumerableCollectionView..ctor(IEnumerable sourceCollection, ICollectionChangedListener collectionOwner)
   at System.Windows.Controls.ItemCollection.UpdateItemsSourceList(IEnumerable newItemsSource)
   at System.Windows.Controls.ItemsControl.ItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.RaisePropertyChangeNotifications(DependencyProperty dp, Object oldValue, Object newValue)
   at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation)
   at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet)
   at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value)
   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   at System.Windows.Controls.ItemsControl.set_ItemsSource(IEnumerable value)
   at TradeMe.MainPage.Trademe_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
   at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
   at System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
   at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at System.Delegate.DynamicInvokeOne(Object[] args)
   at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
   at System.Delegate.DynamicInvoke(Object[] args)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
   at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
   at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
   at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
   at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)


You're checking whether e.Error is null, not whether e.Result is null... and you're also not returning after showing the message box.

(It's hard to know exactly what's going on - if you could say what exception you're getting and under what circumstances, that would be useful...)

EDIT: Okay, from the stack trace, it looks like it's in the selection part of the iterator. I strongly suspect that one of these lines is failing:

ImageSource = TM.Element(ns + "PictureHref").Value,
Title = TM.Element(ns + "Title").Value,
Region = TM.Element(ns + "Region").Value,
PriceDisplay = TM.Element(ns + "PriceDisplay").Value,
ListingId = TM.Element(ns + "ListingId").Value,

My guess is that one of the elements you're looking for is missing.

If you change it to the following code, it won't throw an exception - but any property which would previously have thrown an exception will be null. That may be what you want, but even if not it would at least potentially help you to find the problem:

ImageSource = (string) TM.Element(ns + "PictureHref"),
Title = (string) TM.Element(ns + "Title"),
Region = (string) TM.Element(ns + "Region"),
PriceDisplay = (string) TM.Element(ns + "PriceDisplay"),
ListingId = (string) TM.Element(ns + "ListingId"),

The explicit conversion from XElement to string will return null if the element is null, e.g.

XElement element = null;
string value = (string) element;
// value will be null; no exception is thrown


according the .NET 4.0 MSDN documentation you should handle the callback as follows:

private static void DownloadStringCallback2 (Object sender, DownloadStringCompletedEventArgs e)
{
    // If the request was not canceled and did not throw
    // an exception, display the resource.
    if (!e.Cancelled && e.Error == null)
    {
        string textString = (string)e.Result;

        Console.WriteLine (textString);
    }
}

I presume you have to do something similar for WP7. So check if Cancelled is false and e.Error is not null. Then get the result.

0

精彩评论

暂无评论...
验证码 换一张
取 消