Google Windows 10 UWP Community Toolkit: Twitter integration sample (C#-Xaml) | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Monday, 5 September 2016

Windows 10 UWP Community Toolkit: Twitter integration sample (C#-Xaml)

Introduction:
In the previous article, I wrote an article about "How to integrate twitter in silver-light windows phone 8.0". Previously we need to integrate third party libraries with so many lines of code to post a status message on the social network. But fortunately, now it is very easy to post a status message on Twitter & Facebook social networks with windows 10 UWP Community Toolkit Services.
Note: If you are new to Windows 10 UWP app development, please read Windows 10 Beginners Guide.

Requirements:
  • This article is targeted for windows 10 Anniversary Update, so make sure you’ve downloaded and installed the latest Anniversary Windows 10 SDK from here.
  • We no longer need a developer license with Windows 10. But we must Enable Developer Mode to your device for development.
  • This post assumes you’re using Microsoft Visual Studio 2015 Update 3 or Later.
  • This article is developed on windows 10 machine.
    Note: 
    1. UWP Community Toolkit is compatible with apps developed for Windows 10 SDK Build 10586 or above.
    2. Windows 10 SDK works best on the Windows 10 operating system. And it is also supported on Windows 8.1, Windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2, but not all tools are supported on these operating systems.

    Description:
    This article can explain you about below topics
    1. How to create new project With Windows 10 Anniversary SDK?
    2. How to Add UWP Community Toolkit in Windows 10 Project?
    3. How to use UWP Community Toolkit in Windows 10?
    4. How to post the status message on Twitter in Windows 10 UWP Project?
    5. How to tweet with the picture, getting user timelines, also search for the specific tag in Windows 10 UWP Project?
    6. How to run and test Windows 10 UWP project?

    1. How to create new project With Windows 10 Anniversary SDK?
    Before to use Windows 10 UWP Community Toolkit, first we need to create the new project. 
    • Launch Visual Studio 2015 Update 3 or Later
    • On the File menu, select New > Project.
    • The New Project dialog appears. The left pane of the dialog lets you select the type of templates to display.In the left pane, expand Installed > Templates Visual C# > Windows, then pick the Universal template group. The dialog's center pane displays a list of project templates for Universal Windows Platform (UWP) apps.
    • In the center pane, select the Blank App (Universal Windows) template.The Blank App template creates a minimal UWP app that compiles and runs but contains no user interface controls or data. You add controls to the app over the course of this tutorial.In the Name text box, type "UWPTwitterIntegration".Click OK to create the project.
    For this sample, you must target the app with minimum version 10.0.10586 or later. Because UWP Community Toolkit is compatible with apps developed for Windows 10 SDK Build 10586 or above.

    2. How to Add UWP Community Toolkit in Windows 10 Project?
    In Solution Explorer panel, right click on your project name and select "Manage NuGet Packages".

    Search for "Microsoft.Toolkit.UWP.Services" to select desired packages and install them.
    This will add Microsoft.Toolkit.Uwp.Services.dll in 'References' of your project, as shown below:


    3. How to use UWP Community Toolkit in Windows 10?
    In this article, We are using services from UWP Community Toolkit for twitter integration. So we need to add related namespace "using Microsoft.Toolkit.Uwp.Services.Twitter" to Initialize "TwitterService" class
    4. How to post the status message on Twitter in Windows 10 UWP Project?
    We have to follow below steps to post a status message on twitter.
    Step 1:
    First of all, you have to create the twitter application Consumer id & Consumer secrets. So go to Twitter Developer Website and create new twitter app like below information.
    Step 2: After creating your Twitter App. Now you have to set the access level for your app under "Permissions" Tab. There are three options for setting level.
    Read Only: Select this permission if you want to only read the data and don’t want to post anything.
    Read & Write: Select this permission if you want to read as well as post the data.
    Read, Write & Acess direct messages: This permission will allow an application to read or delete a user's direct messages.
    Step 3: Get Consumer Key (API Key), Consumer Secret (API Secret) from "Keys and Access Tokens" Tab. Also we have to note Callback URL from "Settings" Tab.
    Step 4: Create XAML UI for user twitter login, displaying user details and also for sending the status message.
    1. <Page  
    2.     x:Class="UWPTwitterIntegration.MainPage"  
    3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
    4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
    5.     xmlns:local="using:UWPTwitterIntegration"  
    6.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
    7.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
    8.     mc:Ignorable="d">  
    9.   
    10.     <Grid Background="White" >  
    11.         <Grid>  
    12.             <Grid.RowDefinitions>  
    13.                 <RowDefinition Height="Auto"/>  
    14.                 <RowDefinition Height="*"/>  
    15.             </Grid.RowDefinitions>  
    16.             <!--Header Titile-->  
    17.             <TextBlock Grid.Row="0" Foreground="#FF736B74" Margin="12" Text="UWP Twitter Integration" FontWeight="Bold" FontSize="25" />  
    18.               
    19.             <!--Twitter Login Button-->  
    20.             <Button Name="BtnTwitterLogin" Grid.Row="1" HorizontalAlignment="Stretch" Margin="12"  BorderThickness="0" Content="Login in Twitter" Background="#FF3FD483" Foreground="White" Click="BtnTwitterLogin_Click" />  
    21.               
    22.             <!--UI for After Twitter Login-->  
    23.             <Grid Grid.Row="1" Name="GridRoot" Visibility="Collapsed" VerticalAlignment="Center">  
    24.                 <Grid.RowDefinitions>  
    25.                     <RowDefinition Height="Auto"/>  
    26.                     <RowDefinition Height="*"/>  
    27.                 </Grid.RowDefinitions>  
    28.                   
    29.                 <!--UI for displaying User details after twitter login-->  
    30.                 <Grid Name="GridUserDetails">  
    31.                     <Grid.ColumnDefinitions>  
    32.                         <ColumnDefinition Width="100"/>  
    33.                         <ColumnDefinition Width="Auto" />  
    34.                     </Grid.ColumnDefinitions>  
    35.   
    36.                     <!--Displaying User Image profile by binding with ProfileImageUrl-->  
    37.                     <Image Name="ImgTwitterProfile" Stretch="UniformToFill" Source="{Binding ProfileImageUrl}" Grid.Column="0" Margin="12" HorizontalAlignment="Center" />  
    38.   
    39.                     <!--Displaying User profile details by binding with Name & ScreenName-->  
    40.                     <Grid Grid.Column="1">  
    41.                         <Grid.RowDefinitions>  
    42.                             <RowDefinition Height="Auto"/>  
    43.                             <RowDefinition Height="*"/>  
    44.                         </Grid.RowDefinitions>  
    45.                         <TextBlock Grid.Row="0" Foreground="Black" Margin="12" Text="{Binding Name}" FontSize="18" />  
    46.                         <TextBlock Grid.Row="1" Foreground="Black" Margin="12,5,0,0" Text="{Binding ScreenName}" FontSize="18" />  
    47.                     </Grid>  
    48.                 </Grid>  
    49.                   
    50.                 <!--UI for post status-->  
    51.                 <StackPanel Grid.Row="1" Name="StckPostMessage" Margin="0,12,0,0">  
    52.                     <TextBox Name="TbxStatus" TextWrapping="Wrap" BorderBrush="#FF23E0D8" Height="150" Margin="12" HorizontalAlignment="Stretch"   Foreground="#FF736B74" />  
    53.                     <Button Name="BtnTwitterPost" Content="Post Status" HorizontalAlignment="Stretch" Margin="12"  BorderThickness="0" Background="#FF3FD483" Foreground="White" Click="BtnTwitterPost_Click" />  
    54.                 </StackPanel>  
    55.   
    56.             </Grid>  
    57.         </Grid>  
    58.           
    59.         <!--Loader-->  
    60.         <ProgressRing x:Name="myProgressRing" IsActive="False" Height="50" Width="50" />  
    61.     </Grid>  
    62. </Page>  
    Step 5: Now it is time for twitter login, but first we have to initialize twitter service class from Community Toolkit. Please note that, here you need to pass three arguments(your twitter ConsumerKey, ConsumerSecret & CallbackUri). 
    1. // Initialize service  
    2. TwitterService.Instance.Initialize(ConsummerKey, ConsumerSecret, CallbackUri);  

    Step 6: After that write below code in login button click
    1. private void BtnTwitterLogin_Click(object sender, RoutedEventArgs e)  
    2.        {  
    3.            //Activate loader on twitter login  
    4.            myProgressRing.IsActive = true;  
    5.   
    6.            //Pass ConsumerKey, consumerSecret & CallbackUri  
    7.            TwitterLogin("YOUR CONSUMER_KEY""YOUR CONSUMER_SECRET""CALLBACK_URI");  
    8.        }  
    9.        private async void TwitterLogin(string ConsummerKey, string ConsumerSecret, string CallbackUri)  
    10.        {  
    11.            // Initialize service  
    12.            TwitterService.Instance.Initialize(ConsummerKey, ConsumerSecret, CallbackUri);  
    13.   
    14.            // Login to Twitter  
    15.            if (!await TwitterService.Instance.LoginAsync())  
    16.            {  
    17.                myProgressRing.Visibility = Visibility.Collapsed;  
    18.   
    19.                //Showing login fialure message  
    20.                MessageDialog messageDialog = new MessageDialog("Login failure!");  
    21.                await messageDialog.ShowAsync();  
    22.                return;  
    23.            }  
    24.   
    25.            myProgressRing.Visibility = Visibility.Collapsed;  
    26.            BtnTwitterLogin.Visibility = Visibility.Collapsed;  
    27.            GridRoot.Visibility = Visibility.Visible;  
    28.            // Get current user info  
    29.            var user = await TwitterService.Instance.GetUserAsync();  
    30.   
    31.            //Binding UI with user info  
    32.            GridUserDetails.DataContext = user;  
    33.        }  
    Step 7: Now we are almost done, and it is time for post status message on Twitter. So write below code on post status button click.
    1. private void BtnTwitterPost_Click(object sender, RoutedEventArgs e)  
    2.        {  
    3.            TwitterPostStatus(TbxStatus.Text);  
    4.        }  
    5.   
    6.        private async void TwitterPostStatus(string StatusMessage)  
    7.        {  
    8.            // Post a tweet  
    9.            await TwitterService.Instance.TweetStatusAsync(StatusMessage);  
    10.        }  
    5. How to tweet with the picture, getting user timelines, also search for the specific tag in Windows 10 UWP Project?
    It is very easy to tweet with the picture, to get user timelines and also search for the specific tag.
    1. // Get user timeline  
    2.   ListView.ItemsSource = await TwitterService.Instance.GetUserTimeLineAsync(user.ScreenName, 50);  
    3.   
    4.  // Post a tweet with a picture  
    5.   await TwitterService.Instance.TweetStatusAsync(TweetText.Text, stream);  
    6.   
    7.     // Search for a specific tag  
    8.   ListView.ItemsSource = await TwitterService.Instance.SearchAsync(TagText.Text, 50);  


    6.  How to run and test Windows 10 UWP project?
    Now its time to test our sample App, In addition to the option to Debug on a desktop device, Visual Studio provides options for deploying and debugging your app on a physical mobile device connected to the computer, or on a mobile device emulator. You can choose among emulators for devices with different memory and display configurations like below

    Note: 
    1. It's a good idea to test your app on a device with a small screen and limited memory, so use the Emulator 10.0.10586.0 WVGA 4 inch 512MB option.
    2. If you want to test our app in physical device, you must Register your Windows Phone device for development.
    3. If you already have .APPx file, you can deploy it from WinAppDeployCmd.exe tool

    After selecting emulator/device, From the Debug menu, click Start Debugging or Press F5. Then we can found below screen on emulator/device:

    Intial UI, User need to click login button for authentication.
    After that screen will redirect to twitter website, and it will ask for user twitter login and password.
    After twitter login success, UI will display user details and also there is an option to post status message.

    User needs to type his status message and need to click on "Post Status" button.
     After that status message will post on user's timeline.

    UWPTwitterSample
    FeedBack Note:
    Please share your thoughts,what you think about this post,Is this post really helpful for you?I always welcome if you drop comments on this post and it would be impressive.

    Follow me always at @Subramanyam_B
    Have a nice day by  :)

    9 comments:

    1. If anyone wants to get Mobile App Development service at low cost in India then you can visit us now.

      ReplyDelete
    2. nice article,keep sharing!

      some of the best mens shoes available here
      oxford men shoes online

      ReplyDelete
    3. Appaustic is an app development company helping start ups, enterprises in effective interaction with their clients. We are developing smart apps for iOS and Android. We have experts for facebook app development too.

      ReplyDelete
    4. I think in this days Microsoft just forgot about UWP JS/HTML apps, and I’m worrying they will one day just throw the support away…

      advanced windows tips and tricks

      ReplyDelete
    5. Nice Information on this blog this is very helpful information for us regarding Best Mobile Phones app.

      ReplyDelete
    6. Thankyou! Very well written article.
      Yberry Infosystem is a global corporation offering solutions in IT, Mobile Application Development,Web Application Development. Ecommerce services, branding designing, graphics design as well as SEO solutions. Visit: www.yberryinfosystem.com

      ReplyDelete
    7. A huge info for the windows 10 community toolkit with your post sharing. Thank you very much for the sharing. E-Commerce in Coimbatore | portal solutions in coimbatore

      ReplyDelete
    8. When fishing, when you want to catch as many fish as possible, you use a large net and spread it as far as you can, right? Likewise, when you want to build your Twitter profile you should keep working on sending visitors to your profile. weblink

      ReplyDelete

    Search Engine Submission - AddMe