Веб-служба Twitter в веб-проекте Silverlight

#c# #silverlight #silverlight-4.0 #twitter

#c# #silverlight #silverlight-4.0 #Twitter

Вопрос:

В настоящее время я использую эту страницу http://www.silverlightshow.net/items/Silvester-A-Silverlight-Twitter-Widget.aspx создать приложение Silverlight, которое получает ленту пользователей Twitter и отображает ее.

Я внес некоторые изменения в код, но он все равно должен работать так же. Однако я получаю это сообщение об ошибке при попытке преобразовать xml:

 >System.NullReferenceException was unhandled by user code
  Message=Object reference not set to an instance of an object.
  Source=USElab.Web
  StackTrace:
       at USElab.Web.TwitterWebService.<GetUserTimeline>b__1(XElement status) in H:USEUSEUSEUSElabUSElab.WebTwitterWebService.asmx.cs:line 58
       at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at USElab.Web.TwitterWebService.GetUserTimeline(String twitterUser, String userName, String password) in H:USEUSEUSEUSElabUSElab.WebTwitterWebService.asmx.cs:line 57
  InnerException: 
  

Я не могу понять, почему это происходит. Вот код:

    namespace USElab.Web
   {
/// <summary>
/// Summary description for TwitterWebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]

public class TwitterWebService : System.Web.Services.WebService
{
    private const string UserTimelineUri = "http://twitter.com/statuses/user_timeline/{0}.xml";
    private const string StatusElementName = "status";
    private const string CreatedAtElementName = "created_at";
    private const string TextElementName = "text";
    private const string ProfileImageUrlElementName = "profile_image_url";
    private const string NameElementName = "name";
    private const string UserElementName = "user";
    private const string UserUrlElementName = "url";
    public const int RequestRateLimit = 70;

    [WebMethod]
        public List<TwitterItem> GetUserTimeline( string twitterUser, string userName, string password )
        {
              if ( string.IsNullOrEmpty( twitterUser ) )
              {
                  throw new ArgumentNullException( "twitterUser", "twitterUser parameter is mandatory" );
              }

              WebRequest rq = HttpWebRequest.Create( string.Format( UserTimelineUri, twitterUser ) );

              if ( !string.IsNullOrEmpty( userName ) amp;amp; !string.IsNullOrEmpty( password ) )
              {
                  rq.Credentials = new NetworkCredential( userName, password );
              }

              HttpWebResponse res = rq.GetResponse() as HttpWebResponse;

              // rate limit exceeded
              if ( res.StatusCode == HttpStatusCode.BadRequest )
              {
                  throw new ApplicationException( "Rate limit exceeded" );
              }

              XDocument xmlData = XDocument.Load(XmlReader.Create(res.GetResponseStream()));
              List<TwitterItem> data = (from status in xmlData.Descendants(StatusElementName)
                           select new TwitterItem
                           {
                               Message = status.Element(StatusElementName).Element(TextElementName).Value.Trim(),
                               ImageSource = status.Element(StatusElementName).Element(ProfileImageUrlElementName).Value.Trim(),
                               UserName = status.Element(StatusElementName).Element(UserElementName).Value.Trim()
                           }).ToList();



                return data;
          }
  

Согласно отладчику, это происходит в строке, которая запускает select new TwitterItem.

Любая помощь была бы высоко оценена!

Комментарии:

1. Вы уверены, что значение не равно null перед вызовом Trim()?

Ответ №1:

NullReferenceException обычно возникает, когда вы пытаетесь сделать что-то вроде null.Member

У вас есть довольно продвинутый код создания TwitterItems, извлеките его в другой метод и выполните нулевые проверки для всех возможных нулевых объектов (элементов в вашем случае), прежде чем вызывать функции-члены, такие как .Element .Value или .Trim()

также убедитесь, что значение xmlData не равно null, прежде чем вызывать .Descendants его.

Комментарии:

1. Спасибо! Я кое-что понял, если я прокомментирую сообщение, источник изображения и имя пользователя, это не приведет к ошибке сейчас. Итак, проблема заключается в этом..

2. ваш диагноз был точен! Большое вам спасибо!