将图像从 Picasa 加载到 WP 中

本文关键字:WP 加载 Picasa 图像 | 更新日期: 2023-09-27 18:33:47

我一直在研究能够从 picasa 获取相册的 Windows Phone 应用程序,但我收到一个错误:System.ni.dll 中发生了 'System.Reflection.TargetInvocationException' 类型的异常,但在相册 page.xaml.cs 的用户代码中未处理

项目来源:获取Picasa专辑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)}

将图像从 Picasa 加载到 WP 中

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

当它发生时 Windows Phone 中的 System.Windows.ni.dll 中发生类型为"'System.Reflection.TargetInvocationException' "的未处理异常