将Picasa中的图像加载到WP中

时间:2014-12-10 13:52:56

标签: c# json windows-phone-7 windows-phone-8 picasa

我一直在处理能够从picasa获取相册的Windows Phone应用程序,但是我收到了一个错误:'System.Reflection.TargetInvocationException'中出现System.ni.dll类型的例外但未处理相册page.xaml.cs

中的用户代码

项目来源:get picasa albums JSON

using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Collections;
using System.IO.IsolatedStorage;

namespace MyPicasa
{
    public partial class AlbumsPage : PhoneApplicationPage
    {
        private IsolatedStorageSettings appSettings;
        private const string emailKey = "emailKey";
        private const string passwordKey = "passwordKey";
        private const string usernameKey = "usernameKey";
        private string username = "";
        private string email = "";
        private string password = "";
        private string dataFeed = "";
        private App app = App.Current as App;

        // Handle loading animation in this page
        public bool ShowProgress
        {
            get { return (bool)GetValue(ShowProgressProperty); }
            set { SetValue(ShowProgressProperty, value); }
        }
        public static readonly DependencyProperty ShowProgressProperty =
            DependencyProperty.Register("ShowProgress", typeof(bool), typeof(AlbumsPage), new PropertyMetadata(false));

        // Constructor
        public AlbumsPage()
        {
            InitializeComponent();
            appSettings = IsolatedStorageSettings.ApplicationSettings;
        }

        // Navigate to this page
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            // load and show saved username from isolated storage
            if (appSettings.Contains(usernameKey))
            {
                string differentUsername = (string)appSettings[usernameKey];
                if (differentUsername != "") username = differentUsername;
            }

            // load and show saved email from isolated storage
            if (appSettings.Contains(emailKey))
            {
                email = (string)appSettings[emailKey]; // for example firstname.lastname@gmail.com
                if (username == "" && email.IndexOf("@") != -1) username = email.Substring(0, email.IndexOf("@")); // firstname.lastname
                dataFeed = String.Format("http://picasaweb.google.com/data/feed/api/user/{0}?alt=json", username);
            }

            // load password from isolated storage
            if (appSettings.Contains(passwordKey))
            {
                password = (string)appSettings[passwordKey];
            }

            // we are coming back from AlbumPage
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
            {
                AlbumsListBox.ItemsSource = app.albums;
                AlbumsListBox.SelectedIndex = -1;
            }
            else
            {
                // get authentication from Google
                GetAuth();
            }
        }

        // get authentication from Google
        private void GetAuth()
        {
            ShowProgress = true;
            string service = "lh2"; // Picasa
            string accountType = "GOOGLE";

            WebClient webClient = new WebClient();
            Uri uri = new Uri(string.Format("https://www.google.com/accounts/ClientLogin?Email={0}&Passwd={1}&service={2}&accountType={3}", email, password, service, accountType));
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(AuthDownloaded);
            webClient.DownloadStringAsync(uri);
        }

        // handle authentication from google
        private void AuthDownloaded(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null && e.Error == null)
                {
                    app.auth = "";
                    int index = e.Result.IndexOf("Auth=");
                    if (index != -1)
                    {
                        app.auth = e.Result.Substring(index + 5);
                    }
                    if (app.auth != "")
                    {
                        // get albums from Google
                        GetAlbums();
                        return;
                    }
                }
                MessageBox.Show("Cannot get authentication from google. Check your login and password.");
                ShowProgress = false;
            }
            catch (WebException)
            {
                MessageBox.Show("Cannot get authentication from google. Check your login and password.");
                ShowProgress = false;
            }
        }

        // Get albums from Google
        private void GetAlbums()
        {
            WebClient webClient = new WebClient();
            webClient.Headers[HttpRequestHeader.Authorization] = "GoogleLogin auth=" + app.auth;
            Uri uri = new Uri(dataFeed, UriKind.Absolute);
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(AlbumsDownloaded);
            webClient.DownloadStringAsync(uri);
        }

        // Albums loaded from Google
        public void AlbumsDownloaded(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Result == null || e.Error != null)
                {
                    MessageBox.Show("Cannot get albums data from Picasa server!");
                    ShowProgress = false;
                    return;
                }
                else
                {
                    // Deserialize JSON string to dynamic object
                    IDictionary<string, object> json = (IDictionary<string, object>)SimpleJson.DeserializeObject(e.Result);
                    // Feed object
                    IDictionary<string, object> feed = (IDictionary<string, object>)json["feed"];
                    // Author List
                    IList author = (IList)feed["author"];
                    // First author (and only)
                    IDictionary<string, object> firstAuthor = (IDictionary<string, object>)author[0];
                    // Album entries
                    IList entries = (IList)feed["entry"];
                    // Delete previous albums from albums list
                    app.albums.Clear();
                    // Find album details
                    for (int i = 0; i < entries.Count; i++)
                    {
                        // Create a new Album
                        Album album = new Album();
                        // Album entry object
                        IDictionary<string, object> entry = (IDictionary<string, object>)entries[i];
                        // Published object
                        IDictionary<string, object> published = (IDictionary<string, object>)entry["published"];
                        // Get published date
                        album.published = (string)published["$t"];
                        // Title object
                        IDictionary<string, object> title = (IDictionary<string, object>)entry["title"];
                        // Album title
                        album.title = (string)title["$t"];
                        // Link List
                        IList link = (IList)entry["link"];
                        // First link is album data link object
                        IDictionary<string, object> href = (IDictionary<string, object>)link[0];
                        // Get album data addres
                        album.href = (string)href["href"];
                        // Media group object
                        IDictionary<string, object> mediagroup = (IDictionary<string, object>)entry["media$group"];
                        // Media thumbnail object list
                        IList mediathumbnailList = (IList)mediagroup["media$thumbnail"];
                        // First thumbnail object (smallest)
                        var mediathumbnail = (IDictionary<string, object>)mediathumbnailList[0];
                        // Get thumbnail url
                        album.thumbnail = (string)mediathumbnail["url"];
                        // Add album to albums
                        app.albums.Add(album);
                    }
                    // Hide loading... animation
                    ShowProgress = false;
                    // Add albums to AlbumListBox
                    AlbumsListBox.ItemsSource = app.albums;
                }
            }
            catch (WebException)
            {
                MessageBox.Show("Cannot get albums data from Picasa server!");
                ShowProgress = false;
            }
            catch (KeyNotFoundException)
            {
                MessageBox.Show("Cannot load images from Picasa Server - JSON parsing error happened!");
                ShowProgress = false;
            }
        }

        // Handle selection from AlbumListBox
        private void AlbumsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If real selection is happened, go to a AlbumPage
            if (AlbumsListBox.SelectedIndex == -1) return;
            app.selectedAlbumIndex = AlbumsListBox.SelectedIndex;
            this.NavigationService.Navigate(new Uri("/AlbumPage.xaml?SelectedIndex=" + AlbumsListBox.SelectedIndex, UriKind.Relative));
        }
    }
}

错误发生在这行代码中:

if (e.Result != null && e.Error == null)

错误详情:

{System.Reflection.TargetInvocationException: An exception occurred during the operation, making the result invalid.  Check InnerException for exception details. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
   at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.<EndGetResponse>b__d(Object sendState)
   at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.<BeginOnUI>b__0(Object sendState)
   --- End of inner exception stack trace ---
   at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
   at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
   at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
   --- End of inner exception stack trace ---
   at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
   at System.Net.DownloadStringCompletedEventArgs.get_Result()
   at MyPicasa.AlbumsPage.AuthDownloaded(Object sender, DownloadStringCompletedEventArgs e)
   at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
   at System.Net.WebClient.DownloadStringOperationCompleted(Object arg)}

1 个答案:

答案 0 :(得分:0)

如果您收到System.Reflection.TargetInvocationException类型的无法处理的异常,理想情况下这意味着您正在调用未等待的async方法:

When it occurs An unhandled exception of type "'System.Reflection.TargetInvocationException' occurred in System.Windows.ni.dll" inWindows Phone