0

我目前正在开发一个应用程序,该应用程序加载一个加载了有关 WinPhanDev 社区中的开发人员信息的 XML,然后获取所有开发人员的推文。它还应该显示特定开发人员已发布的所有已发布应用程序,这是部分工作。

在运行解析从http://zunderstorehost.azurewebsites.net/api/获取的 json的代码时,在将第 5/6 或第 7 个开发人员添加到集合时,我会得到随机异常,而无需更改代码。

处理所有数据的整个方法包含以下代码:

async void webClient_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
{
   if (e.Error == null)
   {
       string _proimage = "";
       me.twitterClient = new RestClient("https://api.twitter.com");
       me.tapiAuthToken = EncodeTo64(me.tapiCKey + ":" + me.tapiCSecret);
       // Authorize app for Twitter
       me.tweetReq = new RestRequest("oauth2/token", Method.POST);
       me.tweetReq.AddHeader("Authorization", "Basic " + me.tapiAuthToken);
       me.tweetReq.AddHeader("Host", "api.twitter.com");
       me.tweetReq.AddHeader("User-Agent", "WinPhanDevs");
       me.tweetReq.AddHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF8");
       me.tweetReq.AddParameter("grant_type", "client_credentials");
       try
       {
            me.resp = await me.twitterClient.GetResponseAsync(me.tweetReq);
            me.token = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuthToken>(me.resp.Content);
       }
       catch (Exception ex)
       {
            ErrorClass error = Newtonsoft.Json.JsonConvert.DeserializeObject<ErrorClass>(me.resp.Content);
            App.ViewModel.Devs.Add(new WinPhanDevs.ViewModels.DevViewModel() { Name = error.errors[0].label, Twitter = error.errors[0].message, PublisherID = ex.Message, Site = "", StoryLink = "", Image= "", Tweets = null });
       }

       XMLData = XElement.Parse(e.Result);
       var devs = from el in XMLData.Descendants("dev") select el;
       foreach (XElement el in devs)
       {
            #region "Load devs tweets"
            twts = new ObservableCollection<TweetViewModel>();
            if(el.Attribute("twitter").Value != "")
            {
                // Fetch tweets
                me.twitterClient = new RestClient(me.tapi);
                me.tweetReq = new RestRequest("search/tweets.json", Method.GET);
                me.tweetReq.AddHeader("Authorization", "Bearer " + me.token.access_token);
                me.tweetReq.AddHeader("Accept-Encoding", "gzip");
                me.tweetReq.AddParameter("q", "from:" + el.Attribute("twitter").Value + " exclude:retweets exclude:replies");

                string[] _createdAt = new string[20];
                string[] _text = new string[20];
                string[] _link = new string[20];
                string[] _image = new string[20];

                Peep res = await ExecuteAsync<Peep>(me.tweetReq, me.tapi);
                Status[] statuses = res.statuses;

                int i = 0;
                foreach (Status tweet in statuses)
                {
                    DateTime time = DateTime.ParseExact(tweet.created_at, "ddd MMM dd HH:mm:ss zzz yyyy", new System.Globalization.CultureInfo("en-US"));
                    _createdAt[i] = time.ToShortDateString() + " " + time.ToShortTimeString();
                    _text[i] = tweet.text;
                    if (tweet.entities.urls.Length > 0) { _link[i] = tweet.entities.urls[0].expanded_url; _text[i] = _text[i].Replace(tweet.entities.urls[0].url, ""); } else { _link[i] = ""; }
                    if (tweet.entities.media != null) { _image[i] = tweet.entities.media[0].media_url; _text[i] = _text[i].Replace(tweet.entities.media[0].url, ""); } else { _image[i] = ""; }
                    twts.Add(new WinPhanDevs.ViewModels.TweetViewModel() { Date = _createdAt[i], Tweet = _text[i], Link = _link[i] });
                    i++;
                }
                _proimage = statuses[0].user.profile_image_url;
            }
            #endregion
            #region "Load devs apps"
            // Gets an IndexOutOfBounds/TargetInvocation/NullReference
            // exception in here while adding the 5th/6th or 7th developer,
            // none of the exceptions are caught.
            // Without this whole region the app runs smooth.
            try
            {
                RestClient devClient = new RestClient("http://zunderstorehost.azurewebsites.net/api/");
                string dev = el.Attribute("pubid").Value;
                //dev = dev.Replace(" ", "+");
                RestRequest devReq = new RestRequest("WP8StoreAppList/Query/" + dev, Method.GET);
                response = await devClient.GetContentAsync(devReq);
                AppClass[] apps = JsonConvert.DeserializeObject<AppClass[]>(response);
                Apps = new ObservableCollection<AppViewModel>();
                foreach (AppClass app in apps)
                {
                    string _price;
                    if (app.Offers.Count > 1)
                    {
                        if (app.Offers[0].Price != "0")
                        {
                            _price = app.Offers[0].DisplayPrice + " (Trial available)";
                        }
                        else
                        {
                            _price = app.Offers[1].DisplayPrice + " (Trial available)";
                        }
                    }
                    else
                    {
                        if (app.Offers[0].Price == "0")
                        {
                            _price = "FREE";
                        }
                        else
                        {
                            _price = app.Offers[0].DisplayPrice;
                        }
                    }
                    try
                    {
                        Apps.Add(new AppViewModel()
                        {
                            Name = app.Name,
                            ReleaseDate = app.ReleaseDate,
                            GUID = app.Guid,
                            Icon = app.Icon,
                            Price = _price,
                            Publisher = app.Publisher,
                            Version = app.Version,
                            StoreLink = ""
                        });
                    }catch (Exception ex)
                    {
                        Devs.Add(new DevViewModel() { Name = "Failed to add!", Apps = null, Image = "", PublisherID = "", Site="", StoryLink="", Tweets=null, Twitter=ex.Message});
                    }
                }
            }catch (Exception ex)
            {
                Devs.Add(new DevViewModel() { Name = "Failed to add!", Apps = null, Image = "", PublisherID = "", Site = "", StoryLink = "", Tweets = null, Twitter = ex.Message });
            }
            #endregion
            try
            {
                Devs.Add(new DevViewModel() { Name = el.Attribute("name").Value, Twitter = el.Attribute("twitter").Value, Site = el.Attribute("web").Value, PublisherID = el.Attribute("pubid").Value, StoryLink = el.Attribute("story").Value, Tweets = twts, Image = _proimage, Apps = Apps });
            }catch(Exception ex)
            {
                Devs.Add(new DevViewModel() { Name = "Failed to add!", Apps = null, Image = "", PublisherID = "", Site = "", StoryLink = "", Tweets = null, Twitter = ex.Message });
            }
        }
        this.IsDataLoaded = true;
    }
    else
    {
        Devs.Add(new DevViewModel() { Name = e.Error.Source, Twitter = e.Error.Message, PublisherID = e.Error.InnerException.Message, Site = "", StoryLink = "" });
    }
}

整个项目可在https://github.com/IzaacJ/WinPhanDevs获得,发生此问题的特定文件是 MainViewModel.cs

解决此问题的任何帮助将不胜感激!

4

0 回答 0