Wednesday, August 19, 2015

How to integrate Twitter with Sharepoint 2013

Hello, you may be here to know how to display your Twitter recent tweets onto your SharePoint page.

Firstly, you have to register an application at Twitter Developers site and then you get an ApiKey, ApiSecret, Token and TokenSecret.

Secondly, you have to use these in the API to get access to the user account and get recent tweets only of the user.

Here is a sample TwDbHelper.cs code:

Next, you have to create two controllers as shown:

 //1. Twitter controller to get tweets only and write to azure db
using LinqToTwitter;
using Microsoft.WindowsAzure;
using log4net;

namespace SiteAPI.Controllers
{
    public class TwitterController : ApiController
    {
        private readonly ILog _log = LogManager.GetLogger("SiteAPI");

        public string GetNewMaxIDandUpdateDB(string username, ulong sinceID = 544516702412723892)
        {
            try
            {
                if (_log.IsDebugEnabled) { _log.Debug("Calling GetNewMaxIDandUpdateDB"); }
                return Integration.Twitter.TwDbHelper.GetNewMaxIDandUpdateDB(username, sinceID);
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message, ex);

                //Throw custom exception to the caller
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("An error occurred, please try again or contact the administrator."),
                    ReasonPhrase = "Critical Exception"
                });
            }
        }

    }
}
 //2. Twitter Database controller to get tweets from azure db
using LinqToTwitter;
using Core.Domain;

namespace SiteAPI.Controllers
{
    public class TwitterDBController : ApiController
    {
        public ICollection GetTweetsOnlyFeedFromDB(string username)
        {
            return Integration.Twitter.TwDbHelper.GetTweetsOnlyFeedFromDB(username);
        }
    }
}

Then you have to publish the API to your Azure instance, here is test site url to get tweets from db: https://{enteryoursite}.azurewebsites.net/api/twitterdb/GetTweetsOnlyFeedFromDB?username={enterUserName}

Finally you can use this url in SharePoint using JQuery:
Place below code to a Sharepoint master gallery file, for example: /script/custom.js
//twitter Feed
function _inittwitterFeed(userName) {
    var twFeed = $('#twitter-feed');
    // get twitter posts from api
    function __gettwitterPosts(callback) {
        var apiUri = 'https://{enteryoursite}.azurewebsites.net/api/twitterdb/GetTweetsOnlyFeedFromDB?username=';

        $.ajax({
            url: apiUri + userName,
            type: 'json',
            success: function (result) {
                callback(result);
            },
            error: function () {
                //twFeed.closest('.ms-webpartzone-cell').hide();
            }
        });
    }

    // format the data returned from the twitter api
    function __processtwitterPosts(posts) {
        var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
        var twitterPostsHtml = '';
        var profileImage;
        var link;
        var title;
        var date;
        var post;
        for (var post in posts) {
            title = posts[post].Text;
            profileImage = posts[post].ProfileImageUrlHttps; 
            link = '//twitter.com/' + posts[post].ScreenName + '/status/' + posts[post].StringStatusID;  
            date = posts[post].CreatedAt.match(/([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})/);
            date = date[3] + ' ' + months[date[2] - 1] + ' ' + date[1];
           
            if (profileImage.length > 0) {                
                if (link != null) {
                    post = '';
                }
                twitterPostsHtml += post;
            }
        }
        twitterPostsHtml = '';
        return twitterPostsHtml;
    }

    // get twitter posts and add them to the twitter UI
    __gettwitterPosts(function (twitterPosts) {
        twFeed.html(__processtwitterPosts(twitterPosts));
    });
}

Then create a SharePoint page and in edit mode, add a Script editor web part and add below snippet:
//twitter Feed

Once you save the page, you will see the user tweets loaded onto the web part.
Happy Coding...Hope you like this post!!! Please share or comment if you like it.

No comments:

Post a Comment