c# - TweetSharp 使用 PhotoChooserTask 和 SendTweetWithMedia 上传图片

标签 c# .net tweetsharp windows-phone-7.8

我正在尝试在 Twitter 上上传一张 PhotoChooserTask 抓到他的照片。我遇到的问题是我不知道如何传递 BitmapImage,这是我选择图像并将其传递给 Stream 时的格式。

下面是我的代码示例:

namespace Twitter
{
    public partial class TwitterUploadImage : PhoneApplicationPage
    {

        // Constructor

        TwitterService service;
        private const string consumerKey = "";
        private const string consumerSecret = "";
        private OAuthRequestToken requestToken;
        private OAuthAccessToken accesToken;
        private bool userAuthenticated = false;

        //Uri uri = new Uri("/Background.png", UriKind.Relative);
        //Stream imageStream = Application.GetResourceStream(uri);
        Stream imageStream;
        string namePhoto;

        public TwitterUploadImage()
        {

            InitializeComponent();
            service = new TwitterService(consumerKey,consumerSecret);

            //Chek if we already have the Autehntification data
            var token = getAccessToken();
            if (token != null)
            {
                service.AuthenticateWith(token.Token, token.TokenSecret);
                userAuthenticated = true;
            }
        }

        //protected override void OnNavigatedTo(NavigationEventArgs e)
        //{
        //    // Get a dictionary of query string keys and values. 
        //    IDictionary<string, string> queryStrings = this.NavigationContext.QueryString;

        //    // Ensure that there is at least one key in the query string, and check whether the "FileId" key is present. 
        //    if (queryStrings.ContainsKey("FileId"))
        //    {
        //        // Retrieve the photo from the media library using the FileID passed to the app. 
        //        MediaLibrary library = new MediaLibrary();
        //        Picture photoFromLibrary = library.GetPictureFromToken(queryStrings["FileId"]);

        //        // Create a BitmapImage object and add set it as the image control source. 
        //        // To retrieve a full-resolution image, use the GetImage() method instead. 
        //        BitmapImage bitmapFromPhoto = new BitmapImage();
        //        bitmapFromPhoto.SetSource(photoFromLibrary.GetPreviewImage());
        //        image1.Source = bitmapFromPhoto;
        //    }
        //} 

        private void tweetClick(object sender, RoutedEventArgs e)
        {
            if (userAuthenticated)
                Tweet(Message.Text, imageStream);
            else
                service.GetRequestToken(processRequestToken);
        }

        private void processRequestToken(OAuthRequestToken token, TwitterResponse response)
        {
            if (token == null)
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Error obtaining Request token"); });
            else
            {
                requestToken = token;
                Dispatcher.BeginInvoke(() =>
                {
                    Browser.Visibility = System.Windows.Visibility.Visible;
                    Browser.Navigate(service.GetAuthorizationUri(requestToken));
                });
            }
        }

        private void processAccessToken(OAuthAccessToken token, TwitterResponse response)
        {
            if (token == null)
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Error obtaining Access token"); });
            else
            {
                accesToken = token;
                service.AuthenticateWith(token.Token, token.TokenSecret);
                saveAccessToken(token);
                userAuthenticated = true;
                Dispatcher.BeginInvoke(() =>
                {
                    Tweet(Message.Text, imageStream);
                });
            }
        }

        private void Tweet(string message, Stream ImageStream)
        {
            //SendTweetOptions msg = new SendTweetOptions();
            //msg.Status = message;
            //service.SendTweet(msg, tweetResponse);

            //MediaLibrary library = new MediaLibrary();
            //Picture picture = library.GetPictureFromToken(namePhoto);
            ////Stream stream = picture.ToString;
            //var stream = library.GetPictureFromToken(namePhoto);

            PhotoChooserTask photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
            photoChooserTask.Show();

            SendTweetWithMediaOptions msgMedia = new SendTweetWithMediaOptions();
            msgMedia.Status = message;
            Dictionary<string, Stream> imageDict = new Dictionary<string, Stream> { { "test", imageStream } };
            //imageDict.Add(imagePath, imageStream);
            msgMedia.Images = imageDict;
            //status = service.SendTweetWithMedia(new SendTweetWithMediaOptions() { Status = readerMsg.Message, Images = imageDict });
            service.SendTweetWithMedia(msgMedia, tweetResponse);

            ////var service = GetAuthenticatedService();
            //using (var stream = new FileStream("daniel_8bit.png", FileMode.Open))
            //{
            //    var tweet = service.SendTweetWithMedia(new SendTweetWithMediaOptions
            //        {
            //            Status = "Can_tweet_with_image:Tweet",
            //            Images = new Dictionary<string, Stream> {{"test", stream}}
            //        });
            //    //Assert.IsNotNull(tweet);
            //    //Assert.AreNotEqual(0, tweet.Id);
            //}

            //service.SendTweetWithMedia(new SendTweetWithMediaOptions
            //{
            //    Status = "Can_tweet_with_image:Tweet",
            //    Images = new Dictionary<string, Stream> { { "test", imageStream } }
            //});

        }

        private void tweetResponse(TwitterStatus tweet, TwitterResponse response)
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Dispatcher.BeginInvoke(() => { MessageBox.Show("Tweet posted successfully"); });
            }
            else
            {
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    saveAccessToken(null);
                    userAuthenticated = false;
                    Dispatcher.BeginInvoke(() => { MessageBox.Show("Authentication error"); });
                }
                else
                    Dispatcher.BeginInvoke(() => { MessageBox.Show("Error, please try again later"); });
            }
        }

        private void BrowserNavitaged(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.Uri.AbsoluteUri.Contains("oauth_verifier"))
            {
                var values = ParseQueryString(e.Uri.AbsoluteUri);
                string verifier = values["oauth_verifier"];
                service.GetAccessToken(requestToken, verifier, processAccessToken);
                Dispatcher.BeginInvoke(() => { Browser.Visibility = System.Windows.Visibility.Collapsed; });
            }
        }

        private void saveAccessToken(OAuthAccessToken token)
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("accessToken"))
                IsolatedStorageSettings.ApplicationSettings["accessToken"] = token;
            else
                IsolatedStorageSettings.ApplicationSettings.Add("accessToken", token);

            IsolatedStorageSettings.ApplicationSettings.Save();
        }

        private OAuthAccessToken getAccessToken()
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains("accessToken"))
                return IsolatedStorageSettings.ApplicationSettings["accessToken"] as OAuthAccessToken;
            else
                return null;
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (Browser.Visibility == System.Windows.Visibility.Visible)
            {
                Browser.Visibility = System.Windows.Visibility.Collapsed;
                e.Cancel = true;
            }
            base.OnBackKeyPress(e);
        }

        // From Hammock.Extensions.StringExtensions.cs
        public static IDictionary<string, string> ParseQueryString(string query)
        {
            // [DC]: This method does not URL decode, and cannot handle decoded input
            if (query.StartsWith("?")) query = query.Substring(1);

            if (query.Equals(string.Empty))
            {
                return new Dictionary<string, string>();
            }

            var parts = query.Split(new[] { '&' });

            return parts.Select(
                part => part.Split(new[] { '=' })).ToDictionary(
                    pair => pair[0], pair => pair[1]
                );
        }

        private void takepicture(object sender, RoutedEventArgs e)
        {
            //PhotoChooserTask photoChooserTask = new PhotoChooserTask();
            //photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
            //photoChooserTask.Show();
        }

        void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                var img = new BitmapImage();
                img.SetSource(e.ChosenPhoto);



                imageStream = img;
                //namePhoto = e.OriginalFileName;



                //BitmapImage image = new BitmapImage();
                //image.SetSource(e.ChosenPhoto);
                //this.img.Source = image;
            }
        }

    }
}

最佳答案

我有一个非常相似的问题,但解决方案是相同的,所以我提出了一个问题,一段时间后我自己找到了解决方案,这是解决方案。 Cannot use SendTweetWithMediaOptions in windows phone

关于c# - TweetSharp 使用 PhotoChooserTask 和 SendTweetWithMedia 上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16442895/

相关文章:

wpf - 如何设置项目以使用 TweetSharp

c# - 使用 C# 和 Microsoft Graph SDK 从日历获取事件

C# 聚合列表中的属性

c# - 需要更多地控制文本框的 MouseDown 和 KeyDown

.net - ImageList 透明度错误的解决方法?

asp.net - 如果回调 url 包含 IP 地址,则 TweetSharp 异常

c# - Base64编码字符串到文件

.Net 问题 "Illegal characters in path."

c# - ASP.Net弹性搜寻

c# - TweetSharp 2.0 搜索和地理编码