Advertisement
IzaacJ

IndexOutOfBoundsException in MainViewModel->LoadData()

Aug 28th, 2013
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 13.51 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Xml;
  4. using System.Xml.Linq;
  5. using System.Collections.ObjectModel;
  6. using System.ComponentModel;
  7. using WinPhanDevs.Resources;
  8. using Izz0Lib;
  9. using RestSharp;
  10. using RestSharpEx;
  11. using System.Threading.Tasks;
  12. using Newtonsoft.Json;
  13. using System.Net;
  14.  
  15. namespace WinPhanDevs.ViewModels
  16. {
  17.     public class MainViewModel : INotifyPropertyChanged
  18.     {
  19.         public MainViewModel()
  20.         {
  21.             this.Devs = new ObservableCollection<DevViewModel>();
  22.             this.Featured = new ObservableCollection<AppViewModel>();
  23.             //this.Tweets = new ObservableCollection<TweetViewModel>();
  24.         }
  25.  
  26.         /// <summary>
  27.         /// A collection for ItemViewModel objects.
  28.         /// </summary>
  29.         public ObservableCollection<DevViewModel> Devs { get; private set; }
  30.         public ObservableCollection<AppViewModel> Featured { get; private set; }
  31.         //public ObservableCollection<TweetViewModel> Tweets { get; private set; }
  32.  
  33.         private App me = (App)App.Current;
  34.  
  35.         private string _sampleProperty = "Sample Runtime Property Value";
  36.         /// <summary>
  37.         /// Sample ViewModel property; this property is used in the view to display its value using a Binding
  38.         /// </summary>
  39.         /// <returns></returns>
  40.         public string SampleProperty
  41.         {
  42.             get
  43.             {
  44.                 return _sampleProperty;
  45.             }
  46.             set
  47.             {
  48.                 if (value != _sampleProperty)
  49.                 {
  50.                     _sampleProperty = value;
  51.                     NotifyPropertyChanged("SampleProperty");
  52.                 }
  53.             }
  54.         }
  55.  
  56.         /// <summary>
  57.         /// Sample property that returns a localized string
  58.         /// </summary>
  59.         public string LocalizedSampleProperty
  60.         {
  61.             get
  62.             {
  63.                 return AppResources.SampleProperty;
  64.             }
  65.         }
  66.  
  67.         public bool IsDataLoaded
  68.         {
  69.             get;
  70.             private set;
  71.         }
  72.  
  73.  
  74.         #region "Variables"
  75.         private string Url = "http://winphandev.izz0.eu/devs.xml";
  76.         private System.IO.IsolatedStorage.IsolatedStorageFile File;
  77.         private System.IO.IsolatedStorage.IsolatedStorageFileStream isoFile;
  78.         private System.Xml.Linq.XElement XMLData;
  79.         private ObservableCollection<TweetViewModel> twts;
  80.         private ObservableCollection<AppViewModel> apps;
  81.         string response = "";
  82.         #endregion
  83.         /// <summary>
  84.         /// Creates and loads all the data
  85.         /// </summary>
  86.         public void LoadData()
  87.         {
  88.             try
  89.             {
  90.                 var webClient = new System.Net.WebClient();
  91.                 webClient.DownloadStringCompleted += webClient_DownloadStringCompleted;
  92.                 webClient.DownloadStringAsync(new Uri("http://winphan.izz0.eu.preview.citynetwork.se/devs.xml"));
  93.             }catch(Exception ex)
  94.             {
  95.                 Devs.Add(new DevViewModel() { Name = ex.Source, Twitter = ex.Message });
  96.             }
  97.         }
  98.  
  99.         async void webClient_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
  100.         {
  101.             if (e.Error == null)
  102.             {
  103.                 string _proimage = "";
  104.                 me.twitterClient = new RestClient("https://api.twitter.com");
  105.                 me.tapiAuthToken = EncodeTo64(me.tapiCKey + ":" + me.tapiCSecret);
  106.                 // Authorize app for Twitter
  107.                 me.tweetReq = new RestRequest("oauth2/token", Method.POST);
  108.                 me.tweetReq.AddHeader("Authorization", "Basic " + me.tapiAuthToken);
  109.                 me.tweetReq.AddHeader("Host", "api.twitter.com");
  110.                 me.tweetReq.AddHeader("User-Agent", "WinPhanDevs");
  111.                 me.tweetReq.AddHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF8");
  112.                 me.tweetReq.AddParameter("grant_type", "client_credentials");
  113.                 try
  114.                 {
  115.                     me.resp = await me.twitterClient.GetResponseAsync(me.tweetReq);
  116.                     me.token = Newtonsoft.Json.JsonConvert.DeserializeObject<OAuthToken>(me.resp.Content);
  117.                 }
  118.                 catch (Exception ex)
  119.                 {
  120.                     ErrorClass error = Newtonsoft.Json.JsonConvert.DeserializeObject<ErrorClass>(me.resp.Content);
  121.                     App.ViewModel.Devs.Add(new WinPhanDevs.ViewModels.DevViewModel() { Name = error.errors[0].label, Twitter = error.errors[0].message, PublisherID = "", Site = "", StoryLink = "", Image= "", Tweets = null });
  122.                 }
  123.  
  124.                 XMLData = XElement.Parse(e.Result);
  125.                 var devs = from el in XMLData.Descendants("dev") select el;
  126.                 foreach (XElement el in devs)
  127.                 {
  128.                     #region "Load devs tweets"
  129.                     twts = new ObservableCollection<TweetViewModel>();
  130.                     if(el.Attribute("twitter").Value != "")
  131.                     {
  132.                         // Fetch tweets
  133.                         me.twitterClient = new RestClient(me.tapi);
  134.                         me.tweetReq = new RestRequest("search/tweets.json", Method.GET);
  135.                         me.tweetReq.AddHeader("Authorization", "Bearer " + me.token.access_token);
  136.                         me.tweetReq.AddHeader("Accept-Encoding", "gzip");
  137.                         me.tweetReq.AddParameter("q", "from:" + el.Attribute("twitter").Value + " exclude:retweets exclude:replies");
  138.  
  139.                         string[] _createdAt = new string[20];
  140.                         string[] _text = new string[20];
  141.                         string[] _link = new string[20];
  142.                         string[] _image = new string[20];
  143.  
  144.                         Peep res = await ExecuteAsync<Peep>(me.tweetReq, me.tapi);
  145.                         Status[] statuses = res.statuses;
  146.  
  147.                         int i = 0;
  148.                         foreach (Status tweet in statuses)
  149.                         {
  150.                             DateTime time = DateTime.ParseExact(tweet.created_at, "ddd MMM dd HH:mm:ss zzz yyyy", new System.Globalization.CultureInfo("en-US"));
  151.                             _createdAt[i] = time.ToShortDateString() + " " + time.ToShortTimeString();
  152.                             _text[i] = tweet.text;
  153.                             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] = ""; }
  154.                             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] = ""; }
  155.                             twts.Add(new WinPhanDevs.ViewModels.TweetViewModel() { Date = _createdAt[i], Tweet = _text[i], Link = _link[i] });
  156.                             i++;
  157.                         }
  158.                         _proimage = statuses[0].user.profile_image_url;
  159.                     }
  160.                     #endregion
  161.                     #region "Load devs apps"
  162.                     // ERROR HAPPENS HERE
  163.                     // ERROR HAPPENS HERE
  164.                     // ERROR HAPPENS HERE
  165.                     // ERROR HAPPENS HERE
  166.                     // ERROR HAPPENS HERE
  167.                     // Gets an IndexOutOfBoundsException in here while adding the 6th developers apps, none of the Catches are caught.
  168.                     try
  169.                     {
  170.                         RestClient devClient = new RestClient("http://zunderstorehost.azurewebsites.net/api/");
  171.                         string dev = el.Attribute("pubid").Value;
  172.                         //dev = dev.Replace(" ", "+");
  173.                         RestRequest devReq = new RestRequest("WP8StoreAppList/Query/" + dev, Method.GET);
  174.                         response = await devClient.GetContentAsync(devReq);
  175.                         AppClass[] Apps = JsonConvert.DeserializeObject<AppClass[]>(response);
  176.                         apps = new ObservableCollection<AppViewModel>();
  177.                         foreach (AppClass app in Apps)
  178.                         {
  179.                             string _price;
  180.                             if (app.Offers.Count > 1)
  181.                             {
  182.                                 if (app.Offers[0].Price != "0")
  183.                                 {
  184.                                     _price = app.Offers[0].DisplayPrice + " (Trial available)";
  185.                                 }
  186.                                 else
  187.                                 {
  188.                                     _price = app.Offers[1].DisplayPrice + " (Trial available)";
  189.                                 }
  190.                             }
  191.                             else
  192.                             {
  193.                                 if (app.Offers[0].Price == "0")
  194.                                 {
  195.                                     _price = "FREE";
  196.                                 }
  197.                                 else
  198.                                 {
  199.                                     _price = app.Offers[0].DisplayPrice;
  200.                                 }
  201.                             }
  202.                             try
  203.                             {
  204.                                 apps.Add(new AppViewModel()
  205.                                 {
  206.                                     Name = app.Name,
  207.                                     ReleaseDate = app.ReleaseDate,
  208.                                     GUID = app.Guid,
  209.                                     Icon = app.Icon,
  210.                                     Price = _price,
  211.                                     Publisher = app.Publisher,
  212.                                     Version = app.Version,
  213.                                     StoreLink = ""
  214.                                 });
  215.                             }catch (Exception ex)
  216.                             {
  217.                                 Devs.Add(new DevViewModel() { Name = "Failed to add!", Apps = null, Image = "", PublisherID = "", Site="", StoryLink="", Tweets=null, Twitter=ex.Message});
  218.                             }
  219.                         }
  220.                     }catch (Exception ex)
  221.                     {
  222.                         Devs.Add(new DevViewModel() { Name = "Failed to add!", Apps = null, Image = "", PublisherID = "", Site = "", StoryLink = "", Tweets = null, Twitter = ex.Message });
  223.                     }
  224.                     #endregion
  225.                     try
  226.                     {
  227.                         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 });
  228.                     }catch(Exception ex)
  229.                     {
  230.                         Devs.Add(new DevViewModel() { Name = "Failed to add!", Apps = null, Image = "", PublisherID = "", Site = "", StoryLink = "", Tweets = null, Twitter = ex.Message });
  231.                     }
  232.                 }
  233.                 this.IsDataLoaded = true;
  234.             }
  235.             else
  236.             {
  237.                 Devs.Add(new DevViewModel() { Name = e.Error.Source, Twitter = e.Error.Message, PublisherID = e.Error.InnerException.Message, Site = "", StoryLink = "" });
  238.             }
  239.         }
  240.  
  241.         public event PropertyChangedEventHandler PropertyChanged;
  242.         private void NotifyPropertyChanged(String propertyName)
  243.         {
  244.             PropertyChangedEventHandler handler = PropertyChanged;
  245.             if (null != handler)
  246.             {
  247.                 handler(this, new PropertyChangedEventArgs(propertyName));
  248.             }
  249.         }
  250.  
  251.         #region "Misc functions"
  252.  
  253.         public Task<T> ExecuteAsync<T>(RestRequest request, string host = "") where T : new()
  254.         {
  255.             var client = new RestClient(host);
  256.  
  257.             var task = new TaskCompletionSource<T>();
  258.  
  259.             var handle = client.ExecuteAsync(request, (response) =>
  260.             {
  261.                 if (response == null)
  262.                 {
  263.                     task.TrySetException(new Exception("No server response!"));
  264.                     return;
  265.                 }
  266.  
  267.                 if (response.ErrorException != null)
  268.                 {
  269.                     task.TrySetException(response.ErrorException);
  270.                 }
  271.                 else
  272.                 {
  273.                     try
  274.                     {
  275.                         if (response.StatusCode != HttpStatusCode.OK)
  276.                         {
  277.                             task.TrySetException(new Exception(response.StatusDescription));
  278.                             return;
  279.                         }
  280.  
  281.                         task.TrySetResult(JsonConvert.DeserializeObject<T>(response.Content));
  282.                     }
  283.                     catch (Exception)
  284.                     {
  285.                         task.TrySetException(new Exception(response.StatusDescription));
  286.                     }
  287.                 }
  288.             });
  289.  
  290.             return task.Task;
  291.         }
  292.  
  293.         static public string EncodeTo64(string toEncode)
  294.         {
  295.             byte[] toEncodeAsBytes
  296.                     = System.Text.UTF8Encoding.UTF8.GetBytes(toEncode);
  297.             // = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
  298.             string returnValue
  299.                   = System.Convert.ToBase64String(toEncodeAsBytes);
  300.             return returnValue;
  301.         }
  302.         #endregion
  303.     }
  304. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement