Beispiel #1
0
        public NewsFeedModel GetNews(string newsFeed, string storyCount)
        {
            _news = new NewsFeedModel();
            var    loadedEventArgs = new LoadEventArgs();
            string queryString     = string.Format("{0}?feed={1}&pageSize={2}", Settings.NewsUrl, newsFeed ?? "",
                                                   storyCount ?? "");
            var webClient = new SharpGIS.GZipWebClient();

            Observable.FromEvent <DownloadStringCompletedEventArgs>(webClient, "DownloadStringCompleted")
            .ObserveOn(Scheduler.ThreadPool)
            .Select(x => ProcessNews(x.EventArgs.Result))
            .ObserveOn(Scheduler.Dispatcher)
            .Subscribe(s =>
            {
                BuildNewsFeedModel(s);
                loadedEventArgs.IsLoaded = true;
                loadedEventArgs.Message  = "";
                OnNewsLoaded(loadedEventArgs);
            }, e =>
            {
                loadedEventArgs.IsLoaded = false;
                loadedEventArgs.Message  = e.Message.ToString(CultureInfo.InvariantCulture);
                OnNewsLoaded(loadedEventArgs);
            });
            webClient.DownloadStringAsync(new Uri(queryString));
            return(_news);
        }
Beispiel #2
0
        public NewsFeature GetFeatures(string team, string pageSize)
        {
            _features = new NewsFeature();
            _features.FeatureItems.Clear();
            var loadedEventArgs = new LoadEventArgs();

            string qS = string.Format("{0}?feed={1}&pageSize={2}", Settings.FeaturesUrl, team ?? "",
                                      pageSize ?? "");


            var wb = new SharpGIS.GZipWebClient();

            Observable.FromEvent <DownloadStringCompletedEventArgs>(wb, "DownloadStringCompleted")
            .ObserveOn(Scheduler.ThreadPool)
            .Select(newString => ProcessFeatures(newString.EventArgs.Result))
            .Subscribe(s =>
            {
                loadedEventArgs.IsLoaded = true;
                loadedEventArgs.Message  = "";

                _features.Copyright   = s.Copyright;
                _features.Description = s.Description;
                _features.Language    = s.Language;
                _features.Link        = s.Link;
                _features.Title       = s.Title;

                for (int i = 0; i < s.FeatureItems.Count; i++)
                {
                    NewsFeatureItem newsFeatureItem = s.FeatureItems[i];
                    Deployment.Current.Dispatcher.BeginInvoke(() => _features.FeatureItems.Add(newsFeatureItem));
                }

                Deployment.Current.Dispatcher.BeginInvoke(() => OnFeaturesLoaded(loadedEventArgs));
                if (!(App.isoSettings.Contains("Features")))
                {
                    ThreadPool.QueueUserWorkItem(o =>
                    {
                        var json = JsonHelpers.SerializeJson(_features);
                        App.isoSettings.Add("Features", json);
                    });
                }
                else
                {
                    ThreadPool.QueueUserWorkItem(o =>
                    {
                        var json = JsonHelpers.SerializeJson(_features);
                        App.isoSettings["Features"] = json;
                    });
                }
            }, e =>
            {
                loadedEventArgs.IsLoaded = false;
                loadedEventArgs.Message  = e.Message.ToString(CultureInfo.InvariantCulture);
            }
                       );
            wb.DownloadStringAsync(new Uri(qS));
            return(_features);
        }
        public void  GetFile(string url, string isolatedStorageFile)
        {
            var client = new SharpGIS.GZipWebClient();

            client.DownloadStringCompleted += (s, e) =>
            {
                try
                {
                    var responseStream = e.Result;
                    using (var writer = new StreamWriter(_isolatedStorage.OpenFile(isolatedStorageFile, FileMode.Create)))
                    {
                        writer.Write(responseStream);
                        writer.Close();
                        Messenger.Default.Send(new BattlelogResponseMessage(this, DefaultMessage, true));
                    }
                }
                catch (WebException we)
                {
                    Messenger.Default.Send(new BattlelogResponseMessage(we.Message, false));
                }
            };
            client.DownloadStringAsync(new Uri(url), client);
            client = null;
            //var request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
            //if (request == null)
            //    throw new ArgumentNullException();

            //request.Method = DefaultMethod;
            //request.Accept = Accept;
            //request.UserAgent = UserAgent;
            //request.CookieContainer = CookieJar;

            //request.BeginGetResponse(responseAsyncResult =>
            //{
            //    try
            //    {
            //        var response = (HttpWebResponse)request.EndGetResponse(responseAsyncResult);
            //        var responseStream = response.GetResponseStream();
            //        using (var writer = _isolatedStorage.OpenFile(isolatedStorageFile, FileMode.Create))
            //        {
            //            byte[] bytesInStream = new byte[responseStream.Length];
            //            responseStream.Read(bytesInStream, 0, bytesInStream.Length);
            //            writer.Write(bytesInStream, 0, bytesInStream.Length);
            //            writer.Close();
            //            Messenger.Default.Send(new BattlelogResponseMessage(this, DefaultMessage, true));
            //        }
            //    }
            //    catch (WebException we)
            //    {
            //        Messenger.Default.Send(new BattlelogResponseMessage(we.Message, false));
            //    }
            //}, null);
        }
        public void GetFile(string url, string isolatedStorageFile)
        {
            var client = new SharpGIS.GZipWebClient();
            client.DownloadStringCompleted += (s, e) =>
                {
                    try
                    {
                        var responseStream = e.Result;
                        using (var writer = new StreamWriter(_isolatedStorage.OpenFile(isolatedStorageFile, FileMode.Create)))
                        {
                            writer.Write(responseStream);
                            writer.Close();
                            Messenger.Default.Send(new BattlelogResponseMessage(this, DefaultMessage, true));
                        }
                    }
                    catch (WebException we)
                    {
                        Messenger.Default.Send(new BattlelogResponseMessage(we.Message, false));
                    }
                };
            client.DownloadStringAsync(new Uri(url), client);
            client = null;
            //var request = WebRequest.Create(new Uri(url)) as HttpWebRequest;
            //if (request == null)
            //    throw new ArgumentNullException();

            //request.Method = DefaultMethod;
            //request.Accept = Accept;
            //request.UserAgent = UserAgent;
            //request.CookieContainer = CookieJar;

            //request.BeginGetResponse(responseAsyncResult =>
            //{
            //    try
            //    {
            //        var response = (HttpWebResponse)request.EndGetResponse(responseAsyncResult);
            //        var responseStream = response.GetResponseStream();
            //        using (var writer = _isolatedStorage.OpenFile(isolatedStorageFile, FileMode.Create))
            //        {
            //            byte[] bytesInStream = new byte[responseStream.Length];
            //            responseStream.Read(bytesInStream, 0, bytesInStream.Length);
            //            writer.Write(bytesInStream, 0, bytesInStream.Length);
            //            writer.Close();
            //            Messenger.Default.Send(new BattlelogResponseMessage(this, DefaultMessage, true));
            //        }
            //    }
            //    catch (WebException we)
            //    {
            //        Messenger.Default.Send(new BattlelogResponseMessage(we.Message, false));
            //    }
            //}, null);
        }
Beispiel #5
0
        public void GetData()
        {
            SessionList = new ObservableCollection <SessionItemModel>();
            SpeakerList = new ObservableCollection <SpeakerItemModel>();
            DateTime sessionLastDownload = DateTime.MinValue;


            // Get the data from Isolated storage if it is there
            if (IsolatedStorageSettings.ApplicationSettings.Contains("SessionData"))
            {
                var converted = (IsolatedStorageSettings.ApplicationSettings["SessionData"] as IEnumerable <SessionItemModel>);

                SessionList = converted.ToObservableCollection(SessionList);
                var loadedEventArgs = new LoadEventArgs {
                    IsLoaded = true, Message = string.Empty
                };
                OnDataLoaded(loadedEventArgs);
            }
            // Get the data from Isolated storage if it is there
            if (IsolatedStorageSettings.ApplicationSettings.Contains("SpeakerData"))
            {
                var converted = (IsolatedStorageSettings.ApplicationSettings["SpeakerData"] as IEnumerable <SpeakerItemModel>);

                SpeakerList = converted.ToObservableCollection(SpeakerList);
                var loadedEventArgs = new LoadEventArgs {
                    IsLoaded = true, Message = string.Empty
                };
                OnDataLoaded(loadedEventArgs);
            }


            // Get the last time the data was downloaded.
            if (IsolatedStorageSettings.ApplicationSettings.Contains("SessionLastDownload"))
            {
                sessionLastDownload = (DateTime)IsolatedStorageSettings.ApplicationSettings["SessionLastDownload"];
            }

            // Check if we need to download the latest data, or if we can just use the isolated storage data
            // Cache the data for 2 hours
            if ((sessionLastDownload.AddHours(2) < DateTime.Now) || !IsolatedStorageSettings.ApplicationSettings.Contains("SessionData"))
            {
                // Download the session data
                var sessionWebClient = new SharpGIS.GZipWebClient();
                sessionWebClient.DownloadStringCompleted += sessionWebClient_DownloadStringCompleted;
                sessionWebClient.DownloadStringAsync(new Uri(Settings.SessionServiceUri));

                // Download speaker data
                var speakerWebClient = new SharpGIS.GZipWebClient();
                speakerWebClient.DownloadStringCompleted += speakerWebClient_DownloadStringCompleted;
                speakerWebClient.DownloadStringAsync(new Uri(Settings.SpeakerServiceUri));
            }
        }
        public ObservableCollection<CompletedViewSchedule> GetFinalScores(string url, string pageStart, string pageSize)
        {
            _finalScores = new ObservableCollection<CompletedViewSchedule>();
            var finalScores2 = new List<CompletedSchedule>();
            var loadedEventArgs = new LoadEventArgs();

            string queryString = string.Format("{0}?start={1}&pageSize={2}", url, pageStart ?? "",
                                               pageSize ?? "");
            var wb = new SharpGIS.GZipWebClient();

            Observable.FromEvent<DownloadStringCompletedEventArgs>(wb, "DownloadStringCompleted")
                .ObserveOn(Scheduler.ThreadPool)
                .Select(x => ProcessFinalItems(x.EventArgs.Result))
                .ObserveOn(Scheduler.Dispatcher)
                .Subscribe(s =>
                               {
                                   loadedEventArgs.IsLoaded = true;
                                   loadedEventArgs.Message = "";
                                   foreach (CompletedSchedule finalScores in s)
                                   {
                                       finalScores2.Add(finalScores);
                                       _finalScores.Add(ConvertToFinalView(finalScores));
                                   }

                                   ThreadPool.QueueUserWorkItem(o =>
                                                                    {
                                                                        InsertIntoIS(finalScores2);
                                                                        CacheFinalScores(_finalScores);
                                                                    });

                                   OnFinalScoresLoaded(loadedEventArgs);
                               }, e =>
                                      {
                                          loadedEventArgs.IsLoaded = true;
                                          //TODO: LOG Error
                                          ErrorService error = new ErrorService(
                                              "Unable to retrieve any upcoming events", "")
                                              .ErrorDialog(true);
                                          error.HandleError();
                                          OnFinalScoresLoaded(loadedEventArgs);
                                      }
                );
            wb.DownloadStringAsync(new Uri(queryString));
            return _finalScores;
        }
Beispiel #7
0
        public ObservableCollection <CompletedViewSchedule> GetFinalScores(string url, string pageStart, string pageSize)
        {
            _finalScores = new ObservableCollection <CompletedViewSchedule>();
            var finalScores2    = new List <CompletedSchedule>();
            var loadedEventArgs = new LoadEventArgs();

            string queryString = string.Format("{0}?start={1}&pageSize={2}", url, pageStart ?? "",
                                               pageSize ?? "");
            var wb = new SharpGIS.GZipWebClient();

            Observable.FromEvent <DownloadStringCompletedEventArgs>(wb, "DownloadStringCompleted")
            .ObserveOn(Scheduler.ThreadPool)
            .Select(x => ProcessFinalItems(x.EventArgs.Result))
            .ObserveOn(Scheduler.Dispatcher)
            .Subscribe(s =>
            {
                loadedEventArgs.IsLoaded = true;
                loadedEventArgs.Message  = "";
                foreach (CompletedSchedule finalScores in s)
                {
                    finalScores2.Add(finalScores);
                    _finalScores.Add(ConvertToFinalView(finalScores));
                }

                ThreadPool.QueueUserWorkItem(o =>
                {
                    InsertIntoIS(finalScores2);
                    CacheFinalScores(_finalScores);
                });

                OnFinalScoresLoaded(loadedEventArgs);
            }, e =>
            {
                loadedEventArgs.IsLoaded = true;
                //TODO: LOG Error
                ErrorService error = new ErrorService(
                    "Unable to retrieve any upcoming events", "")
                                     .ErrorDialog(true);
                error.HandleError();
                OnFinalScoresLoaded(loadedEventArgs);
            }
                       );
            wb.DownloadStringAsync(new Uri(queryString));
            return(_finalScores);
        }
        public void GetData()
        {
            SessionList = new ObservableCollection<SessionItemModel>();
            SpeakerList = new ObservableCollection<SpeakerItemModel>();
            DateTime sessionLastDownload = DateTime.MinValue;

            // Get the data from Isolated storage if it is there
            if (IsolatedStorageSettings.ApplicationSettings.Contains("SessionData"))
            {
                var converted = (IsolatedStorageSettings.ApplicationSettings["SessionData"] as IEnumerable<SessionItemModel>);

                SessionList = converted.ToObservableCollection(SessionList);
                var loadedEventArgs = new LoadEventArgs { IsLoaded = true, Message = string.Empty };
                OnDataLoaded(loadedEventArgs);
            }
            // Get the data from Isolated storage if it is there
            if (IsolatedStorageSettings.ApplicationSettings.Contains("SpeakerData"))
            {
                var converted = (IsolatedStorageSettings.ApplicationSettings["SpeakerData"] as IEnumerable<SpeakerItemModel>);

                SpeakerList = converted.ToObservableCollection(SpeakerList);
                var loadedEventArgs = new LoadEventArgs { IsLoaded = true, Message = string.Empty };
                OnDataLoaded(loadedEventArgs);
            }

            // Get the last time the data was downloaded.
            if (IsolatedStorageSettings.ApplicationSettings.Contains("SessionLastDownload"))
            {
                sessionLastDownload = (DateTime)IsolatedStorageSettings.ApplicationSettings["SessionLastDownload"];
            }

            // Check if we need to download the latest data, or if we can just use the isolated storage data
            // Cache the data for 2 hours
            if ((sessionLastDownload.AddHours(2) < DateTime.Now) || !IsolatedStorageSettings.ApplicationSettings.Contains("SessionData"))
            {
                // Download the session data
                var sessionWebClient = new SharpGIS.GZipWebClient();
                sessionWebClient.DownloadStringCompleted += sessionWebClient_DownloadStringCompleted;
                sessionWebClient.DownloadStringAsync(new Uri(Settings.SessionServiceUri));

                // Download speaker data
                var speakerWebClient = new SharpGIS.GZipWebClient();
                speakerWebClient.DownloadStringCompleted += speakerWebClient_DownloadStringCompleted;
                speakerWebClient.DownloadStringAsync(new Uri(Settings.SpeakerServiceUri));
            }
        }
Beispiel #9
0
        public ObservableCollection <NewsStreamItem> GetNewsStream(string team, string start, string pageSize)
        {
            _newsStream = new ObservableCollection <NewsStreamItem>();
            var    loadedEventArgs = new LoadEventArgs();
            string queryString     = string.Format("{0}?team={1}&start={2}&pageSize={3}", Settings.StreamUrl,
                                                   team ?? "", start ?? "", pageSize ?? "");

            var wb = new SharpGIS.GZipWebClient();

            Observable.FromEvent <DownloadStringCompletedEventArgs>(wb, "DownloadStringCompleted")

            // Let's make sure that we’re on the thread pool
            .ObserveOn(Scheduler.ThreadPool)

            // When the event fires, just select the string and make
            // an IObservable<string> instead
            .Select(newString => ProcessNewsStreamItems(newString.EventArgs.Result))

            // Now go back to the UI Thread
            .ObserveOn(Scheduler.Dispatcher)

            // Subscribe to the observable
            .Subscribe(s =>
            {
                loadedEventArgs.IsLoaded = true;
                loadedEventArgs.Message  = "";
                for (int index = 0; index < s.Count; index++)
                {
                    NewsStreamItem newsStreamItem = s[index];
                    newsStreamItem.Title          = Regex.Replace(newsStreamItem.Title, "");
                    _newsStream.Add(newsStreamItem);
                }
                OnNewsStreamLoaded(loadedEventArgs);
                if (!(App.isoSettings.Contains("NewStream")))
                {
                    ThreadPool.QueueUserWorkItem(o =>
                    {
                        var json = JsonHelpers.SerializeJson(_newsStream);
                        App.isoSettings.Add("NewStream", json);
                    });
                }
                else
                {
                    ThreadPool.QueueUserWorkItem(o =>
                    {
                        var json = JsonHelpers.SerializeJson(_newsStream);
                        App.isoSettings["NewStream"] = json;
                    });
                }
            }, e =>
            {
                loadedEventArgs.IsLoaded = false;
                //TODO: LOG Error
                loadedEventArgs.Message =
                    "We were unable to retrieve the news feed. Please refresh";
                OnNewsStreamLoaded(loadedEventArgs);
            }
                       );

            wb.DownloadStringAsync(new Uri(queryString));
            return(_newsStream);
        }
        /// <summary>
        /// Gets the categories and put them to a CategoryList.
        /// </summary>
        /// <exception cref="APIKeyEception">if there is no api - key</exception>
        public void GetCategoriesAsync(Action<List<Model.Category>> callback)
        {
            validateAPIKey();
            try
            {
                string url = Config.UCategories + getQueryString(paramAPIKey(), paramLocale());

                SharpGIS.GZipWebClient wc = new SharpGIS.GZipWebClient();
                wc.DownloadStringCompleted +=
                delegate(object sender, System.Net.DownloadStringCompletedEventArgs e)
                    {
                        List<Model.Category> retVal = new List<Model.Category>();
                        try
                        {
                            if (e.Error != null)
                            {
                                if (e.Error is WebException)
                                {
                                    WebException wex = (WebException)e.Error;
                                    Debug.WriteLine(wex.ToString());
                                }
                                throw e.Error;
                            }

                            string jsonstr = e.Result;

                            JObject json = (JObject)JsonConvert.DeserializeObject(jsonstr);
                            foreach (var cat in json["categories"])
                            {
            #if DEBUG
                                Debug.WriteLine("categorie {0} ({1}, \"{2}\"",
                                    cat["id"], cat["identifier"], cat["localized_name"]);
            #endif
                                retVal.Add(new Model.Category() {
                                    id = cat["id"].Value<string>(),
                                    identifier = cat["identifier"].ToString(),
                                    localized_name = cat["localized_name"].ToString()
                                });
                            }

                        }
                        catch (Exception ex)
                        {
                            Debug.WriteLine(ex.ToString());
                            throw new Exception("load categories failed: " + ex.Message, ex);
                        }
                        if (callback != null) callback(retVal);
                    };

                Debug.WriteLine(url);
                wc.DownloadStringAsync(new Uri(url, UriKind.Absolute));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }
Beispiel #11
0
        public NewsFeature GetFeatures(string team, string pageSize)
        {
            _features = new NewsFeature();
            _features.FeatureItems.Clear();
            var loadedEventArgs = new LoadEventArgs();

            string qS = string.Format("{0}?feed={1}&pageSize={2}", Settings.FeaturesUrl, team ?? "",
                                      pageSize ?? "");

            var wb = new SharpGIS.GZipWebClient();
            Observable.FromEvent<DownloadStringCompletedEventArgs>(wb, "DownloadStringCompleted")
                .ObserveOn(Scheduler.ThreadPool)
                .Select(newString => ProcessFeatures(newString.EventArgs.Result))
                .Subscribe(s =>
                               {
                                   loadedEventArgs.IsLoaded = true;
                                   loadedEventArgs.Message = "";

                                   _features.Copyright = s.Copyright;
                                   _features.Description = s.Description;
                                   _features.Language = s.Language;
                                   _features.Link = s.Link;
                                   _features.Title = s.Title;

                                   for (int i = 0; i < s.FeatureItems.Count; i++)
                                   {
                                       NewsFeatureItem newsFeatureItem = s.FeatureItems[i];
                                       Deployment.Current.Dispatcher.BeginInvoke(() => _features.FeatureItems.Add(newsFeatureItem));

                                   }

                                  Deployment.Current.Dispatcher.BeginInvoke(() => OnFeaturesLoaded(loadedEventArgs));
                                   if (!(App.isoSettings.Contains("Features")))
                                   {
                                       ThreadPool.QueueUserWorkItem(o =>
                                       {
                                           var json = JsonHelpers.SerializeJson(_features);
                                           App.isoSettings.Add("Features", json);
                                       });
                                   }
                                   else
                                   {
                                       ThreadPool.QueueUserWorkItem(o =>
                                       {
                                           var json = JsonHelpers.SerializeJson(_features);
                                           App.isoSettings["Features"] = json;
                                       });
                                   }
                               }, e =>
                                      {
                                          loadedEventArgs.IsLoaded = false;
                                          loadedEventArgs.Message = e.Message.ToString(CultureInfo.InvariantCulture);
                                      }
                );
            wb.DownloadStringAsync(new Uri(qS));
            return _features;
        }
Beispiel #12
0
        public ObservableCollection<NewsStreamItem> GetNewsStream(string team, string start, string pageSize)
        {
            _newsStream = new ObservableCollection<NewsStreamItem>();
            var loadedEventArgs = new LoadEventArgs();
            string queryString = string.Format("{0}?team={1}&start={2}&pageSize={3}", Settings.StreamUrl,
                                               team ?? "", start ?? "", pageSize ?? "");

            var wb = new SharpGIS.GZipWebClient();
            Observable.FromEvent<DownloadStringCompletedEventArgs>(wb, "DownloadStringCompleted")

                // Let's make sure that we’re on the thread pool
                .ObserveOn(Scheduler.ThreadPool)

                // When the event fires, just select the string and make
                // an IObservable<string> instead
                .Select(newString => ProcessNewsStreamItems(newString.EventArgs.Result))

                // Now go back to the UI Thread
                .ObserveOn(Scheduler.Dispatcher)

                // Subscribe to the observable
                .Subscribe(s =>
                               {
                                   loadedEventArgs.IsLoaded = true;
                                   loadedEventArgs.Message = "";
                                   for (int index = 0; index < s.Count; index++)
                                   {
                                       NewsStreamItem newsStreamItem = s[index];
                                       newsStreamItem.Title = Regex.Replace(newsStreamItem.Title, "");
                                       _newsStream.Add(newsStreamItem);
                                   }
                                   OnNewsStreamLoaded(loadedEventArgs);
                                   if (!(App.isoSettings.Contains("NewStream")))
                                   {
                                       ThreadPool.QueueUserWorkItem(o =>
                                                                        {
                                                                            var json= JsonHelpers.SerializeJson(_newsStream);
                                                                            App.isoSettings.Add("NewStream", json);
                                                                        });
                                   }
                                   else
                                   {
                                       ThreadPool.QueueUserWorkItem(o =>
                                       {
                                           var json = JsonHelpers.SerializeJson(_newsStream);
                                           App.isoSettings["NewStream"] = json;
                                       });
                                   }

                               }, e =>
                                      {
                                          loadedEventArgs.IsLoaded = false;
                                          //TODO: LOG Error
                                          loadedEventArgs.Message =
                                              "We were unable to retrieve the news feed. Please refresh";
                                          OnNewsStreamLoaded(loadedEventArgs);
                                      }
                );

            wb.DownloadStringAsync(new Uri(queryString));
            return _newsStream;
        }
Beispiel #13
0
        public NewsFeedModel GetNews(string newsFeed, string storyCount)
        {
            _news = new NewsFeedModel();
            var loadedEventArgs = new LoadEventArgs();
            string queryString = string.Format("{0}?feed={1}&pageSize={2}", Settings.NewsUrl, newsFeed ?? "",
                                               storyCount ?? "");
            var webClient = new SharpGIS.GZipWebClient();

            Observable.FromEvent<DownloadStringCompletedEventArgs>(webClient, "DownloadStringCompleted")
                .ObserveOn(Scheduler.ThreadPool)
                .Select(x => ProcessNews(x.EventArgs.Result))
                .ObserveOn(Scheduler.Dispatcher)
                .Subscribe(s =>
                               {
                                   BuildNewsFeedModel(s);
                                   loadedEventArgs.IsLoaded = true;
                                   loadedEventArgs.Message = "";
                                   OnNewsLoaded(loadedEventArgs);
                               }, e =>
                                      {
                                          loadedEventArgs.IsLoaded = false;
                                          loadedEventArgs.Message = e.Message.ToString(CultureInfo.InvariantCulture);
                                          OnNewsLoaded(loadedEventArgs);
                                      });
            webClient.DownloadStringAsync(new Uri(queryString));
            return _news;
        }
Beispiel #14
0
        /// <summary>
        /// Gets the categories and put them to a CategoryList.
        /// </summary>
        /// <exception cref="APIKeyEception">if there is no api - key</exception>
        public void GetCategoriesAsync(Action <List <Model.Category> > callback)
        {
            validateAPIKey();
            try
            {
                string url = Config.UCategories + getQueryString(paramAPIKey(), paramLocale());

                SharpGIS.GZipWebClient wc = new SharpGIS.GZipWebClient();
                wc.DownloadStringCompleted +=
                    delegate(object sender, System.Net.DownloadStringCompletedEventArgs e)
                {
                    List <Model.Category> retVal = new List <Model.Category>();
                    try
                    {
                        if (e.Error != null)
                        {
                            if (e.Error is WebException)
                            {
                                WebException wex = (WebException)e.Error;
                                Debug.WriteLine(wex.ToString());
                            }
                            throw e.Error;
                        }

                        string jsonstr = e.Result;

                        JObject json = (JObject)JsonConvert.DeserializeObject(jsonstr);
                        foreach (var cat in json["categories"])
                        {
#if DEBUG
                            Debug.WriteLine("categorie {0} ({1}, \"{2}\"",
                                            cat["id"], cat["identifier"], cat["localized_name"]);
#endif
                            retVal.Add(new Model.Category()
                            {
                                id             = cat["id"].Value <string>(),
                                identifier     = cat["identifier"].ToString(),
                                localized_name = cat["localized_name"].ToString()
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.ToString());
                        throw new Exception("load categories failed: " + ex.Message, ex);
                    }
                    if (callback != null)
                    {
                        callback(retVal);
                    }
                };

                Debug.WriteLine(url);
                wc.DownloadStringAsync(new Uri(url, UriKind.Absolute));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }