Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Xml;
- using System.Xml.Linq;
- using System.Collections.ObjectModel;
- using System.ComponentModel;
- using WinPhanDevs.Resources;
- using Izz0Lib;
- using RestSharp;
- using RestSharpEx;
- using System.Threading.Tasks;
- using Newtonsoft.Json;
- using System.Net;
- namespace WinPhanDevs.ViewModels
- {
- public class MainViewModel : INotifyPropertyChanged
- {
- public MainViewModel()
- {
- this.Devs = new ObservableCollection<DevViewModel>();
- this.Featured = new ObservableCollection<AppViewModel>();
- //this.Tweets = new ObservableCollection<TweetViewModel>();
- }
- /// <summary>
- /// A collection for ItemViewModel objects.
- /// </summary>
- public ObservableCollection<DevViewModel> Devs { get; private set; }
- public ObservableCollection<AppViewModel> Featured { get; private set; }
- //public ObservableCollection<TweetViewModel> Tweets { get; private set; }
- private App me = (App)App.Current;
- private string _sampleProperty = "Sample Runtime Property Value";
- /// <summary>
- /// Sample ViewModel property; this property is used in the view to display its value using a Binding
- /// </summary>
- /// <returns></returns>
- public string SampleProperty
- {
- get
- {
- return _sampleProperty;
- }
- set
- {
- if (value != _sampleProperty)
- {
- _sampleProperty = value;
- NotifyPropertyChanged("SampleProperty");
- }
- }
- }
- /// <summary>
- /// Sample property that returns a localized string
- /// </summary>
- public string LocalizedSampleProperty
- {
- get
- {
- return AppResources.SampleProperty;
- }
- }
- public bool IsDataLoaded
- {
- get;
- private set;
- }
- #region "Variables"
- private string Url = "http://winphandev.izz0.eu/devs.xml";
- private System.IO.IsolatedStorage.IsolatedStorageFile File;
- private System.IO.IsolatedStorage.IsolatedStorageFileStream isoFile;
- private System.Xml.Linq.XElement XMLData;
- private ObservableCollection<TweetViewModel> twts;
- private ObservableCollection<AppViewModel> apps;
- string response = "";
- #endregion
- /// <summary>
- /// Creates and loads all the data
- /// </summary>
- public void LoadData()
- {
- try
- {
- var webClient = new System.Net.WebClient();
- webClient.DownloadStringCompleted += webClient_DownloadStringCompleted;
- webClient.DownloadStringAsync(new Uri("http://winphan.izz0.eu.preview.citynetwork.se/devs.xml"));
- }catch(Exception ex)
- {
- Devs.Add(new DevViewModel() { Name = ex.Source, Twitter = ex.Message });
- }
- }
- 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 = "", 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"
- // ERROR HAPPENS HERE
- // ERROR HAPPENS HERE
- // ERROR HAPPENS HERE
- // ERROR HAPPENS HERE
- // ERROR HAPPENS HERE
- // Gets an IndexOutOfBoundsException in here while adding the 6th developers apps, none of the Catches are caught.
- 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 = "" });
- }
- }
- public event PropertyChangedEventHandler PropertyChanged;
- private void NotifyPropertyChanged(String propertyName)
- {
- PropertyChangedEventHandler handler = PropertyChanged;
- if (null != handler)
- {
- handler(this, new PropertyChangedEventArgs(propertyName));
- }
- }
- #region "Misc functions"
- public Task<T> ExecuteAsync<T>(RestRequest request, string host = "") where T : new()
- {
- var client = new RestClient(host);
- var task = new TaskCompletionSource<T>();
- var handle = client.ExecuteAsync(request, (response) =>
- {
- if (response == null)
- {
- task.TrySetException(new Exception("No server response!"));
- return;
- }
- if (response.ErrorException != null)
- {
- task.TrySetException(response.ErrorException);
- }
- else
- {
- try
- {
- if (response.StatusCode != HttpStatusCode.OK)
- {
- task.TrySetException(new Exception(response.StatusDescription));
- return;
- }
- task.TrySetResult(JsonConvert.DeserializeObject<T>(response.Content));
- }
- catch (Exception)
- {
- task.TrySetException(new Exception(response.StatusDescription));
- }
- }
- });
- return task.Task;
- }
- static public string EncodeTo64(string toEncode)
- {
- byte[] toEncodeAsBytes
- = System.Text.UTF8Encoding.UTF8.GetBytes(toEncode);
- // = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
- string returnValue
- = System.Convert.ToBase64String(toEncodeAsBytes);
- return returnValue;
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement