http://winphone8dev.blogspot.com/2012/12/longlistmultiselector.html
Ảnh minh họa example : http://blogs.windows.com/buildingapps/2012/11/20/windows-phone-toolkit-overview/
http://channel9.msdn.com/Series/Windows-Phone-8-Development-for-Absolute-Beginners/Part-31-Multiple-Selection-with-the-LongListMultiSelector
Thứ Tư, 17 tháng 12, 2014
Thứ Năm, 4 tháng 12, 2014
Tương tác twitter trong window phone 8
Chúng ta sử dụng thư viện hammock và newtonsoft.Json để parse kết quả :
Example:
<phone:PhoneApplicationPage
x:Class="TwitterPost.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="5*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Popup x:Name="StandardPopup" Width="400" Height="700" IsOpen="False">
<Grid >
<phone:WebBrowser Margin="-6,3,0,1" Name="loginBrowserControl"
Navigated="loginBrowserControl_Navigated" Navigating="loginBrowserControl_Navigating"
IsScriptEnabled="True" Width="400" Height="700"/>
</Grid>
</Popup>
<Grid x:Name="TweetPanel" Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height=".15*"/>
<RowDefinition Height=".10*"/>
<RowDefinition Height=".60*"/>
<RowDefinition Height=".15*"/>
<RowDefinition Height=".15*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" x:Name="txtUserName" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="26" FontFamily="Segoe WP Bold" Foreground="Red"/>
<TextBlock Grid.Row="1" Margin="10" VerticalAlignment="Center" HorizontalAlignment="Left" Text="Enter your Tweet" FontSize="24" FontFamily="Segoe WP Bold"/>
<TextBox Grid.Row="2" x:Name="txtTweetContent" Margin="20,-10,20,100" TextWrapping="Wrap" Text="" FontSize="24" FontFamily="Segoe WP Bold" />
<Button Grid.Row="3" x:Name="btnPostTweet" Content="Post Tweet" HorizontalAlignment="Center" Click="btnPostTweet_Click"/>
</Grid>
<Grid Grid.Row="1" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Button x:Name="btnSignIn" Content="Signin" HorizontalAlignment="Center" Click="btnLogin_Click" Grid.Column="0"/>
<Button x:Name="btnSignOut" Content="Signout" HorizontalAlignment="Center" Click="MenuItemSignOut_Click" Grid.Column="1"/>
</Grid>
<!--<Button Grid.Row="3" x:Name="btnPostTweet1" Content="Post Tweet" HorizontalAlignment="Center" Click="btnPostTweet_Click1"/>-->
</Grid>
</phone:PhoneApplicationPage>
File class:
using System;
using System.Collections.Generic;
using System.Linq;
using Hammock.Web;
using System.IO;
using Hammock;
using System.Text;
using Hammock.Authentication.OAuth;
using Microsoft.Phone.Controls;
using System.Windows;
using System.Net;
using Newtonsoft.Json.Linq;
namespace TwitterPost
{
public partial class MainPage : PhoneApplicationPage
{
//http://developer.nokia.com/Community/Wiki/Twitter:_OAuth_1.0_Authentication_using_Hammock
string OAuthTokenKey = string.Empty;
string tokenSecret = string.Empty;
string accessToken = string.Empty;
string accessTokenSecret = string.Empty;
string userID = string.Empty;
string userScreenName = string.Empty;
Uri lasturl ;
public MainPage()
{
InitializeComponent();
TweetPanel.Visibility = Visibility.Collapsed;
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
if (isAlreadyLoggedIn())
{
userLoggedIn();
}
else
{
StandardPopup.IsOpen = true;
var requestTokenQuery = OAuthUtil.GetRequestTokenQuery();
requestTokenQuery.RequestAsync(AppSettings.RequestTokenUri, null);
requestTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
}
}
private Boolean isAlreadyLoggedIn()
{
accessToken = MainUtil.GetKeyValue<string>("AccessToken");
accessTokenSecret = MainUtil.GetKeyValue<string>("AccessTokenSecret");
userScreenName = MainUtil.GetKeyValue<string>("ScreenName");
if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(accessTokenSecret))
return false;
else
return true;
}
private void userLoggedIn()
{
Dispatcher.BeginInvoke(() =>
{
// var SignInMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[0];
// SignInMenuItem.IsEnabled = false;
// var SignOutMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[1];
//SignOutMenuItem.IsEnabled = true;
StandardPopup.IsOpen = false;
TweetPanel.Visibility = System.Windows.Visibility.Visible;
txtUserName.Text = "Welcome " + userScreenName;
});
}
private void MenuItemSignOut_Click(object sender, EventArgs e)
{
MainUtil.SetKeyValue<string>("AccessToken", string.Empty);
MainUtil.SetKeyValue<string>("AccessTokenSecret", string.Empty);
Dispatcher.BeginInvoke(() =>
{
// var SignInMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[0];
// SignInMenuItem.IsEnabled = true;
// var SignOutMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[1];
// SignOutMenuItem.IsEnabled = false;
TweetPanel.Visibility = System.Windows.Visibility.Collapsed;
MessageBox.Show("You have been signed out successfully.");
});
}
private void btnPostTweet_Click(object sender, RoutedEventArgs e)
{
try
{
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
};
var restClient = new RestClient
{
Authority = "https://api.twitter.com",
HasElevatedPermissions = true
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = "/1.1/statuses/update.json",
Method = WebMethod.Post
};
restRequest.AddParameter("status", txtTweetContent.Text);
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
}
catch
{
}
}
public string GetTwitterAvatarUrl(string twitterHandle)
{
string avatarUrl = string.Empty;
var request = new RestRequest
{
Credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
}
};
request.Path =
string.Format(
"https://api.twitter.com/1.1/users/lookup.json?screen_name={0}&include_entities=0&include_rts=0",
twitterHandle);
request.Method = WebMethod.Get;
RestClient client = new RestClient();
try
{
client.BeginRequest(request, new RestCallback(RetriveAvatarCallback));
}
catch (Exception)
{
return "default.png";
}
return avatarUrl;
}
private void RetriveAvatarCallback(RestRequest request, RestResponse response, object obj)
{
JArray jArray = JArray.Parse(response.Content);
var avatarUrl = (string)jArray[0]["profile_image_url_https"];
}
public void getFollower(String name)
{
var request = new RestRequest
{
Credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
}
};
request.Path =
string.Format(
"https://api.twitter.com/1.1/followers/list.json?cursor=-1&screen_name={0}&skip_status=true&include_user_entities=false", name);
request.Method = WebMethod.Get;
RestClient client = new RestClient();
try
{
client.BeginRequest(request, new RestCallback(RetriveFollowerCallback));
}
catch (Exception)
{
}
}
private void RetriveFollowerCallback(RestRequest request, RestResponse response, object obj)
{
JArray jArray = JArray.Parse(response.Content);
// var avatarUrl = (string)jArray[0]["profile_image_url_https"];
}
public void GetTwitterTimelineUrl()
{
var request = new RestRequest
{
Credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
}
};
request.Path =
string.Format(
"https://api.twitter.com/1.1/statuses/home_timeline.json");
request.Method = WebMethod.Get;
RestClient client = new RestClient();
try
{
client.BeginRequest(request, new RestCallback(RetriveTimelineCallback));
}
catch (Exception)
{
}
}
private void RetriveTimelineCallback(RestRequest request, RestResponse response, object obj)
{
JArray jArray = JArray.Parse(response.Content);
// var avatarUrl = (string)jArray[0]["profile_image_url_https"];
}
private void PostTweetRequestCallback(RestRequest request, RestResponse response, object obj)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
MessageBox.Show("TWEET_POSTED_SUCCESSFULLY");
}
else if (response.StatusCode == HttpStatusCode.Forbidden)
{
MessageBox.Show("TWEET_POST_ERR_UPDATE_LIMIT");
}
else
{
MessageBox.Show("WEET_POST_ERR_FAILED");
}
txtTweetContent.Text = "";
});
//var requestTokenQuery = OAuthUtil.GetRequestTokenQuery();
//requestTokenQuery.RequestAsync(AppSettings.RequestTokenUri, null);
//requestTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
}
void requestTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
{
try
{
StreamReader reader = new StreamReader(e.Response);
string strResponse = reader.ReadToEnd();
var parameters = MainUtil.GetQueryParameters(strResponse);
OAuthTokenKey = parameters["oauth_token"];
tokenSecret = parameters["oauth_token_secret"];
var authorizeUrl = AppSettings.AuthorizeUri + "?oauth_token=" + OAuthTokenKey;
Dispatcher.BeginInvoke(() =>
{
StandardPopup.IsOpen = true;
this.loginBrowserControl.Navigate(new Uri(authorizeUrl, UriKind.RelativeOrAbsolute));
});
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.Message);
});
}
}
private void loginBrowserControl_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
lasturl = e.Uri;
System.Diagnostics.Debug.WriteLine("loginBrowserControl_Navigated");
//StandardPopup.IsOpen = false;
// this.loginBrowserControl.Navigated -= loginBrowserControl_Navigated;
}
private void loginBrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
System.Diagnostics.Debug.WriteLine("loginBrowserControl_Navigating");
try
{
if (e.Uri.ToString().StartsWith(AppSettings.CallbackUri))
{
var AuthorizeResult = MainUtil.GetQueryParameters(e.Uri.ToString());
var VerifyPin = AuthorizeResult["oauth_verifier"];
var AccessTokenQuery = OAuthUtil.GetAccessTokenQuery(OAuthTokenKey, tokenSecret, VerifyPin);
AccessTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(AccessTokenQuery_QueryResponse);
AccessTokenQuery.RequestAsync(AppSettings.AccessTokenUri, null);
}
}
catch
{
}
}
void AccessTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
{
try
{
StreamReader reader = new StreamReader(e.Response);
string strResponse = reader.ReadToEnd();
var parameters = MainUtil.GetQueryParameters(strResponse);
accessToken = parameters["oauth_token"];
accessTokenSecret = parameters["oauth_token_secret"];
userID = parameters["user_id"];
userScreenName = parameters["screen_name"];
MainUtil.SetKeyValue<string>("AccessToken", accessToken);
MainUtil.SetKeyValue<string>("AccessTokenSecret", accessTokenSecret);
MainUtil.SetKeyValue<string>("ScreenName", userScreenName);
//GetTwitterAvatarUrl(userScreenName);
//GetTwitterTimelineUrl();
getFollower(userScreenName);
userLoggedIn();
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.Message);
});
}
}
private void btnPostTweet_Click1(object sender, RoutedEventArgs e)
{
//this.loginBrowserControl.Visibility = Visibility.Collapsed;
//this.loginBrowserControl.Navigate(lasturl);
//this.loginBrowserControl.InvokeScript("eval", "history.go(-1)");
//var requestTokenQuery = OAuthUtil.GetRequestTokenQuery();
//requestTokenQuery.RequestAsync(AppSettings.RequestTokenUri, null);
//requestTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
}
}
}
Bonus thêm các link quan trọng:
Lấy thông tin timeline :https://api.twitter.com/1.1/statuses/home_timeline.json
Lấy thông tin những người follower mình :https://api.twitter.com/1.1/followers/list.json?cursor=-1&screen_name={0}&skip_status=true&include_user_entities=false
Lấy avatar của người có tên là : https://api.twitter.com/1.1/users/lookup.json?screen_name={0}&include_entities=0&include_rts=0
Reference:
http://bsubramanyamraju.blogspot.in/2013/11/latest-twitter-integration-in-windows.html
https://code.msdn.microsoft.com/windowsapps/Latest-Twitter-integration-a42e8bb6
http://www.rhizohm.net/irhetoric/post/2013/05/01/Getting-Twitter-Avatar-Via-C-With-11-API.aspx
Example hay nhưng chưa thử :https://code.msdn.microsoft.com/windowsapps/twitter-sample-using-0dfcce61
Example:
<phone:PhoneApplicationPage
x:Class="TwitterPost.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="5*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Popup x:Name="StandardPopup" Width="400" Height="700" IsOpen="False">
<Grid >
<phone:WebBrowser Margin="-6,3,0,1" Name="loginBrowserControl"
Navigated="loginBrowserControl_Navigated" Navigating="loginBrowserControl_Navigating"
IsScriptEnabled="True" Width="400" Height="700"/>
</Grid>
</Popup>
<Grid x:Name="TweetPanel" Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height=".15*"/>
<RowDefinition Height=".10*"/>
<RowDefinition Height=".60*"/>
<RowDefinition Height=".15*"/>
<RowDefinition Height=".15*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" x:Name="txtUserName" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="26" FontFamily="Segoe WP Bold" Foreground="Red"/>
<TextBlock Grid.Row="1" Margin="10" VerticalAlignment="Center" HorizontalAlignment="Left" Text="Enter your Tweet" FontSize="24" FontFamily="Segoe WP Bold"/>
<TextBox Grid.Row="2" x:Name="txtTweetContent" Margin="20,-10,20,100" TextWrapping="Wrap" Text="" FontSize="24" FontFamily="Segoe WP Bold" />
<Button Grid.Row="3" x:Name="btnPostTweet" Content="Post Tweet" HorizontalAlignment="Center" Click="btnPostTweet_Click"/>
</Grid>
<Grid Grid.Row="1" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Button x:Name="btnSignIn" Content="Signin" HorizontalAlignment="Center" Click="btnLogin_Click" Grid.Column="0"/>
<Button x:Name="btnSignOut" Content="Signout" HorizontalAlignment="Center" Click="MenuItemSignOut_Click" Grid.Column="1"/>
</Grid>
<!--<Button Grid.Row="3" x:Name="btnPostTweet1" Content="Post Tweet" HorizontalAlignment="Center" Click="btnPostTweet_Click1"/>-->
</Grid>
</phone:PhoneApplicationPage>
File class:
using System;
using System.Collections.Generic;
using System.Linq;
using Hammock.Web;
using System.IO;
using Hammock;
using System.Text;
using Hammock.Authentication.OAuth;
using Microsoft.Phone.Controls;
using System.Windows;
using System.Net;
using Newtonsoft.Json.Linq;
namespace TwitterPost
{
public partial class MainPage : PhoneApplicationPage
{
//http://developer.nokia.com/Community/Wiki/Twitter:_OAuth_1.0_Authentication_using_Hammock
string OAuthTokenKey = string.Empty;
string tokenSecret = string.Empty;
string accessToken = string.Empty;
string accessTokenSecret = string.Empty;
string userID = string.Empty;
string userScreenName = string.Empty;
Uri lasturl ;
public MainPage()
{
InitializeComponent();
TweetPanel.Visibility = Visibility.Collapsed;
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
if (isAlreadyLoggedIn())
{
userLoggedIn();
}
else
{
StandardPopup.IsOpen = true;
var requestTokenQuery = OAuthUtil.GetRequestTokenQuery();
requestTokenQuery.RequestAsync(AppSettings.RequestTokenUri, null);
requestTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
}
}
private Boolean isAlreadyLoggedIn()
{
accessToken = MainUtil.GetKeyValue<string>("AccessToken");
accessTokenSecret = MainUtil.GetKeyValue<string>("AccessTokenSecret");
userScreenName = MainUtil.GetKeyValue<string>("ScreenName");
if (string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(accessTokenSecret))
return false;
else
return true;
}
private void userLoggedIn()
{
Dispatcher.BeginInvoke(() =>
{
// var SignInMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[0];
// SignInMenuItem.IsEnabled = false;
// var SignOutMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[1];
//SignOutMenuItem.IsEnabled = true;
StandardPopup.IsOpen = false;
TweetPanel.Visibility = System.Windows.Visibility.Visible;
txtUserName.Text = "Welcome " + userScreenName;
});
}
private void MenuItemSignOut_Click(object sender, EventArgs e)
{
MainUtil.SetKeyValue<string>("AccessToken", string.Empty);
MainUtil.SetKeyValue<string>("AccessTokenSecret", string.Empty);
Dispatcher.BeginInvoke(() =>
{
// var SignInMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[0];
// SignInMenuItem.IsEnabled = true;
// var SignOutMenuItem = (Microsoft.Phone.Shell.ApplicationBarMenuItem)this.ApplicationBar.MenuItems[1];
// SignOutMenuItem.IsEnabled = false;
TweetPanel.Visibility = System.Windows.Visibility.Collapsed;
MessageBox.Show("You have been signed out successfully.");
});
}
private void btnPostTweet_Click(object sender, RoutedEventArgs e)
{
try
{
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
};
var restClient = new RestClient
{
Authority = "https://api.twitter.com",
HasElevatedPermissions = true
};
var restRequest = new RestRequest
{
Credentials = credentials,
Path = "/1.1/statuses/update.json",
Method = WebMethod.Post
};
restRequest.AddParameter("status", txtTweetContent.Text);
restClient.BeginRequest(restRequest, new RestCallback(PostTweetRequestCallback));
}
catch
{
}
}
public string GetTwitterAvatarUrl(string twitterHandle)
{
string avatarUrl = string.Empty;
var request = new RestRequest
{
Credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
}
};
request.Path =
string.Format(
"https://api.twitter.com/1.1/users/lookup.json?screen_name={0}&include_entities=0&include_rts=0",
twitterHandle);
request.Method = WebMethod.Get;
RestClient client = new RestClient();
try
{
client.BeginRequest(request, new RestCallback(RetriveAvatarCallback));
}
catch (Exception)
{
return "default.png";
}
return avatarUrl;
}
private void RetriveAvatarCallback(RestRequest request, RestResponse response, object obj)
{
JArray jArray = JArray.Parse(response.Content);
var avatarUrl = (string)jArray[0]["profile_image_url_https"];
}
public void getFollower(String name)
{
var request = new RestRequest
{
Credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
}
};
request.Path =
string.Format(
"https://api.twitter.com/1.1/followers/list.json?cursor=-1&screen_name={0}&skip_status=true&include_user_entities=false", name);
request.Method = WebMethod.Get;
RestClient client = new RestClient();
try
{
client.BeginRequest(request, new RestCallback(RetriveFollowerCallback));
}
catch (Exception)
{
}
}
private void RetriveFollowerCallback(RestRequest request, RestResponse response, object obj)
{
JArray jArray = JArray.Parse(response.Content);
// var avatarUrl = (string)jArray[0]["profile_image_url_https"];
}
public void GetTwitterTimelineUrl()
{
var request = new RestRequest
{
Credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = AppSettings.consumerKey,
ConsumerSecret = AppSettings.consumerKeySecret,
Token = this.accessToken,
TokenSecret = this.accessTokenSecret,
Version = "1.0"
}
};
request.Path =
string.Format(
"https://api.twitter.com/1.1/statuses/home_timeline.json");
request.Method = WebMethod.Get;
RestClient client = new RestClient();
try
{
client.BeginRequest(request, new RestCallback(RetriveTimelineCallback));
}
catch (Exception)
{
}
}
private void RetriveTimelineCallback(RestRequest request, RestResponse response, object obj)
{
JArray jArray = JArray.Parse(response.Content);
// var avatarUrl = (string)jArray[0]["profile_image_url_https"];
}
private void PostTweetRequestCallback(RestRequest request, RestResponse response, object obj)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
MessageBox.Show("TWEET_POSTED_SUCCESSFULLY");
}
else if (response.StatusCode == HttpStatusCode.Forbidden)
{
MessageBox.Show("TWEET_POST_ERR_UPDATE_LIMIT");
}
else
{
MessageBox.Show("WEET_POST_ERR_FAILED");
}
txtTweetContent.Text = "";
});
//var requestTokenQuery = OAuthUtil.GetRequestTokenQuery();
//requestTokenQuery.RequestAsync(AppSettings.RequestTokenUri, null);
//requestTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
}
void requestTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
{
try
{
StreamReader reader = new StreamReader(e.Response);
string strResponse = reader.ReadToEnd();
var parameters = MainUtil.GetQueryParameters(strResponse);
OAuthTokenKey = parameters["oauth_token"];
tokenSecret = parameters["oauth_token_secret"];
var authorizeUrl = AppSettings.AuthorizeUri + "?oauth_token=" + OAuthTokenKey;
Dispatcher.BeginInvoke(() =>
{
StandardPopup.IsOpen = true;
this.loginBrowserControl.Navigate(new Uri(authorizeUrl, UriKind.RelativeOrAbsolute));
});
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.Message);
});
}
}
private void loginBrowserControl_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
lasturl = e.Uri;
System.Diagnostics.Debug.WriteLine("loginBrowserControl_Navigated");
//StandardPopup.IsOpen = false;
// this.loginBrowserControl.Navigated -= loginBrowserControl_Navigated;
}
private void loginBrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
System.Diagnostics.Debug.WriteLine("loginBrowserControl_Navigating");
try
{
if (e.Uri.ToString().StartsWith(AppSettings.CallbackUri))
{
var AuthorizeResult = MainUtil.GetQueryParameters(e.Uri.ToString());
var VerifyPin = AuthorizeResult["oauth_verifier"];
var AccessTokenQuery = OAuthUtil.GetAccessTokenQuery(OAuthTokenKey, tokenSecret, VerifyPin);
AccessTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(AccessTokenQuery_QueryResponse);
AccessTokenQuery.RequestAsync(AppSettings.AccessTokenUri, null);
}
}
catch
{
}
}
void AccessTokenQuery_QueryResponse(object sender, WebQueryResponseEventArgs e)
{
try
{
StreamReader reader = new StreamReader(e.Response);
string strResponse = reader.ReadToEnd();
var parameters = MainUtil.GetQueryParameters(strResponse);
accessToken = parameters["oauth_token"];
accessTokenSecret = parameters["oauth_token_secret"];
userID = parameters["user_id"];
userScreenName = parameters["screen_name"];
MainUtil.SetKeyValue<string>("AccessToken", accessToken);
MainUtil.SetKeyValue<string>("AccessTokenSecret", accessTokenSecret);
MainUtil.SetKeyValue<string>("ScreenName", userScreenName);
//GetTwitterAvatarUrl(userScreenName);
//GetTwitterTimelineUrl();
getFollower(userScreenName);
userLoggedIn();
}
catch (Exception ex)
{
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.Message);
});
}
}
private void btnPostTweet_Click1(object sender, RoutedEventArgs e)
{
//this.loginBrowserControl.Visibility = Visibility.Collapsed;
//this.loginBrowserControl.Navigate(lasturl);
//this.loginBrowserControl.InvokeScript("eval", "history.go(-1)");
//var requestTokenQuery = OAuthUtil.GetRequestTokenQuery();
//requestTokenQuery.RequestAsync(AppSettings.RequestTokenUri, null);
//requestTokenQuery.QueryResponse += new EventHandler<WebQueryResponseEventArgs>(requestTokenQuery_QueryResponse);
}
}
}
Bonus thêm các link quan trọng:
Lấy thông tin timeline :https://api.twitter.com/1.1/statuses/home_timeline.json
Lấy thông tin những người follower mình :https://api.twitter.com/1.1/followers/list.json?cursor=-1&screen_name={0}&skip_status=true&include_user_entities=false
Lấy avatar của người có tên là : https://api.twitter.com/1.1/users/lookup.json?screen_name={0}&include_entities=0&include_rts=0
Reference:
http://bsubramanyamraju.blogspot.in/2013/11/latest-twitter-integration-in-windows.html
https://code.msdn.microsoft.com/windowsapps/Latest-Twitter-integration-a42e8bb6
http://www.rhizohm.net/irhetoric/post/2013/05/01/Getting-Twitter-Avatar-Via-C-With-11-API.aspx
Example hay nhưng chưa thử :https://code.msdn.microsoft.com/windowsapps/twitter-sample-using-0dfcce61
Thứ Ba, 2 tháng 12, 2014
Login facebook với facebook client window phone
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp9.Resources;
using Facebook.Client;
namespace PhoneApp9
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void OnSessionStateChanged(object sender, Facebook.Client.Controls.SessionStateChangedEventArgs e)
{
// this.ContentPanel.Visibility = (e.SessionState == Facebook.Client.Controls.FacebookSessionState.Opened) ? Visibility.Visible : Visibility.Collapsed;
if (e.SessionState == Facebook.Client.Controls.FacebookSessionState.Opened)
{
this.RetriveUserInfo();
}
if (e.SessionState == Facebook.Client.Controls.FacebookSessionState.Opened && loginButton.CurrentUser !=null )
{
String birthday = loginButton.CurrentUser.Birthday;
String firstname = loginButton.CurrentUser.FirstName;
String link = loginButton.CurrentUser.Link;
GraphLocation location = loginButton.CurrentUser.Location;
}
}
private async System.Threading.Tasks.Task RetriveUserInfo()
{
var client = new Facebook.FacebookClient(this.loginButton.CurrentSession.AccessToken);
dynamic result = await client.GetTaskAsync("me");
var currentUser = new Facebook.Client.GraphUser(result);
}
}
}
File giao dien:
<phone:PhoneApplicationPage
x:Class="PhoneApp9.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:facebookControls="clr-namespace:Facebook.Client.Controls;assembly=Facebook.Client"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="2">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<facebookControls:FriendPicker
x:Name="friendPicker"
AccessToken="{Binding CurrentSession.AccessToken, ElementName=loginButton}" Grid.Column="0"/>
</Grid>
<!--user information-->
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<facebookControls:ProfilePicture
x:Name="profilePicture"
Width="60"
Height="60"
CropMode="Original"
ProfileId="{Binding CurrentSession.FacebookId, ElementName=loginButton}" />
<TextBlock
Margin="10,0,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="{Binding CurrentUser.Name, ElementName=loginButton}"/>
</StackPanel>
<facebookControls:LoginButton
x:Name="loginButton"
Grid.Row="2"
Margin="5"
HorizontalAlignment="Right"
ApplicationId="634204333355972" SessionStateChanged="OnSessionStateChanged" Grid.Column="1"
Permissions="user_location, user_birthday, user_likes"/>
</Grid>
<!-- login control -->
</Grid>
</phone:PhoneApplicationPage>
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp9.Resources;
using Facebook.Client;
namespace PhoneApp9
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void OnSessionStateChanged(object sender, Facebook.Client.Controls.SessionStateChangedEventArgs e)
{
// this.ContentPanel.Visibility = (e.SessionState == Facebook.Client.Controls.FacebookSessionState.Opened) ? Visibility.Visible : Visibility.Collapsed;
if (e.SessionState == Facebook.Client.Controls.FacebookSessionState.Opened)
{
this.RetriveUserInfo();
}
if (e.SessionState == Facebook.Client.Controls.FacebookSessionState.Opened && loginButton.CurrentUser !=null )
{
String birthday = loginButton.CurrentUser.Birthday;
String firstname = loginButton.CurrentUser.FirstName;
String link = loginButton.CurrentUser.Link;
GraphLocation location = loginButton.CurrentUser.Location;
}
}
private async System.Threading.Tasks.Task RetriveUserInfo()
{
var client = new Facebook.FacebookClient(this.loginButton.CurrentSession.AccessToken);
dynamic result = await client.GetTaskAsync("me");
var currentUser = new Facebook.Client.GraphUser(result);
}
}
}
File giao dien:
<phone:PhoneApplicationPage
x:Class="PhoneApp9.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:facebookControls="clr-namespace:Facebook.Client.Controls;assembly=Facebook.Client"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel Grid.Row="0" Margin="2">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<facebookControls:FriendPicker
x:Name="friendPicker"
AccessToken="{Binding CurrentSession.AccessToken, ElementName=loginButton}" Grid.Column="0"/>
</Grid>
<!--user information-->
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<facebookControls:ProfilePicture
x:Name="profilePicture"
Width="60"
Height="60"
CropMode="Original"
ProfileId="{Binding CurrentSession.FacebookId, ElementName=loginButton}" />
<TextBlock
Margin="10,0,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="{Binding CurrentUser.Name, ElementName=loginButton}"/>
</StackPanel>
<facebookControls:LoginButton
x:Name="loginButton"
Grid.Row="2"
Margin="5"
HorizontalAlignment="Right"
ApplicationId="634204333355972" SessionStateChanged="OnSessionStateChanged" Grid.Column="1"
Permissions="user_location, user_birthday, user_likes"/>
</Grid>
<!-- login control -->
</Grid>
</phone:PhoneApplicationPage>
Thứ Hai, 1 tháng 12, 2014
Mở video youtube vơi MyToolkit
https://code.msdn.microsoft.com/windowsapps/youtube-video-sample-f2692dc9
Đăng ký:
Bài đăng (Atom)