Showing posts with label Web Part. Show all posts
Showing posts with label Web Part. Show all posts

Wednesday, August 19, 2015

How to integrate Bing News with Sharepoint 2013

Hello, you may be here to know how to display your Bing news results onto your SharePoint page.

Firstly, you have to register an application at Bing Search API site and then you get an AccountKey.

Secondly, you have to use AccountKey in the API to get access to the Bing search API and get news results of the query.

Here is a sample BnHelper.cs code:

Next, you have to create a controller as shown:

 //Bing controller to get news from Bing search API
using Integration.Bing;
using log4net;

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

        private const string RootUrl = "https://api.datamarket.azure.com/Bing/Search";
        private const string Market = "en-us";
        private const string NewsCategory = "rt_ScienceAndTechnology";

        public List GetBingNews(string Query)
        {
            try
            {
                if (_log.IsDebugEnabled) { _log.Debug("Calling GetBingNews"); }
                return Integration.Bing.BnHelper.GetBingNews(Query, RootUrl, Market, NewsCategory);
            }
            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"
                });
            }
        }
    }
}

Then you have to publish the API to your Azure instance, here is test site url to get Bing news: https://{enteryoursite}.azurewebsites.net/api/bing/GetBingNews?Query={enterQuery}

Finally you can use this url in SharePoint using JQuery:
Place below code to a Sharepoint master gallery file, for example: /script/custom.js
//Bing News
function _initBingNews(query) {
    var bnfeed = $('#bing-news-feed');
    // get Bing News from api
    function __getBingNews(callback) {
        var apiUri = 'https://{enteryoursite}.azurewebsites.net/api/bing/GetBingNews?Query=';

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

    // format the data returned from the bing search api
    function __processBingNews(posts) {
        var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
        var bingNewsHtml = '';
        var title;
        var description;
        var link;
        var source;
        var date;
        var post;
        for (var post in posts) {
            title = posts[post].ContentTitle;
            description = posts[post].ContentDescription;
            link = posts[post].ContentUrl;
            date = posts[post].ContentDate.match(/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/);
     date = formatDate( date[2], date[3], date[1]);
           
            if (title.length > 0) {                
                if (link != null) {
                    post = '
  • '; } bingNewsHtml += post; } } bingNewsHtml = '
      '+bingNewsHtml+'
    '; return bingNewsHtml; } // get Bing news posts and add them to the Bing News UI __getBingNews(function (bingNewsPosts) { bnFeed.html(__processBingNews(bingNewsPosts)); }); }

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

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

    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.

    Tuesday, August 18, 2015

    How to integrate Facebook with Sharepoint 2013

    Hello, you may be here to know how to display your Facebook feed onto your SharePoint page.

    Firstly, you have to register an app at Facebook Developers site and then you get ClientId and ClientSecret, but to get an access_token use below url string:

    https://graph.facebook.com/oauth/access_token?client_id={enterClientId}&client_secret={enterClientSecret}&grant_type=client_credentials

    Once you have this access_token, use it in the API to get access to the user account and get user feed.
    Optional: Use Graph API Explorer tool to get an idea which fields you need.
    Here is a sample code:

    //Helper class
    using Newtonsoft.Json;
    using System;
    
    namespace Integration.Facebook
    {
        public static class FbHelper
        {
            //returns Facebook Feed
            public static ICollection< FbFeedItem > ReadFeed(string fbUserId, string accessToken)
            {
                /***
                 * Graph API v2.4
                 * /{user-id}/feed 
                 * The feed of posts (including status updates) and links published by this person, or by others on this person's profile. There are other edges which provide filtered versions of this edge:
                 * /{user-id}/links shows only the links that were published by this person.
                 * /{user-id}/posts shows only the posts that were published by this person.
                 * /{user-id}/statuses shows only the status update posts that were published by this person.
                 * /{user-id}/tagged shows only the posts that this person was tagged in.
                 * 
                 ***/
    
                //gets recent 20 user posts when limit=20
                const string UriJson = "https://graph.facebook.com/v2.4/{0}/posts?fields=message,description,created_time,id,name,link,picture,from,status_type&limit=20&access_token={1}";
                
                var returnFbFeedItems = new List< FbFeedItem >();
    
                try
                {
                    var fbJsonString = Core.Utilities.Json.GetJsonString(String.Format(UriJson, fbUserId, accessToken), null, null, true);
                    //create a stream to hold the contents of the response and create Facebook Object 
                    var fbObject = JsonConvert.DeserializeObject< FbFeedJson >(fbJsonString);
    
                    if (fbObject == null || !fbObject.Data.Any()) return returnFbFeedItems;
    
                    else
                    {
                        if (fbObject.Data != null)
                        {
                            //return feed
                            returnFbFeedItems = fbObject.Data.Select(fbItem => new FbFeedItem
                            {
                                Message = fbItem.Message,
                                Description = fbItem.Description,
                                CreatedTime = fbItem.CreatedTime,
                                PostId = fbItem.Id,
                                Picture = fbItem.Picture,
                                Link = fbItem.Link,
                                Name = fbItem.Name,
                                FromName = fbItem.From.Name,
                                FromId = fbItem.From.Id,
                                StatusType = fbItem.StatusType
                            }).ToList();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error : " + ex);
                }
                return returnFbFeedItems.ToList();
            }
        }
    }
    

    Next, you have to create a controller as shown:

     //Facebook controller
    public class FacebookController : ApiController
    {
        public ICollection< FbFeedItem > GetFacebookFeed(string fbUserId) 
        {
            return Integration.Facebook.FbHelper.ReadFeed(fbUserId);
        }
    }
    

    Then you have to publish the API to your Azure instance, here is test site url: https://{enteryoursite}.azurewebsites.net/api/facebook/GetFacebookFeed?fbUserId={enterFbUserId}

    Finally you can use this url in SharePoint using JQuery:
    Place below code to a Sharepoint master gallery file, for example: /script/custom.js
    //Facebook Feed
    function _initFacebookFeed(FbUserId) {
        var fbFeed = $('#facebook-feed');
        // get facebook posts from api
        function __getFacebookPosts(callback) {
            var apiUri = 'https://{enteryoursite}.azurewebsites.net/api/facebook/GetFacebookFeed?fbUserId=';
    
            $.ajax({
                url: apiUri + FbUserId,
                type: 'GET',
                success: function (result) {
                    callback(result);
                },
                error: function () {
                    //fbFeed.closest('.ms-webpartzone-cell').hide();
                }
            });
        }
    
        // format the data returned from the facebook api
        function __processFacebookPosts(posts) {
            var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
            var facebookPostsHtml = '';
            var message;
            var link;
            var description;
            var picture;
            var date;
            var post;
            for (var post in posts) {
                message = posts[post].Message;
                description = posts[post].Description; 
                link = posts[post].Link; 
                picture = posts[post].Picture;
                date = date.match(/([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2})/);    
         date = date[3] + ' ' + months[date[2] - 1] + ' ' + date[1];
     
                if (message.length > 0) { 
                    if ( message.length > 180 ) {
                         message = message.substring(0, 180) + '...';
                    }               
                    if (picture != null) {
                        post = '';
                    }
                    else {
                        post = '';
                    }
                    facebookPostsHtml += post;
                }
            }
            facebookPostsHtml = '';
            return facebookPostsHtml;
        }
    
        // get facebook posts and add them to the facebook UI
        __getFacebookPosts(function (facebookPosts) {
            fbFeed.html(__processFacebookPosts(facebookPosts));
        });
    }
    

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

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

    How to integrate Instagram with Sharepoint 2013

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

    Firstly, you have to register an application at Instagram Developer site and then you get an access_token.

    Secondly, you have to use this access_token in the API to get access to the user account and get recent photos of the user.

    Here is a sample code:

    //Instagram Helper class
    using Newtonsoft.Json;
    
    namespace Integration.Instagram
    {
        public class IgHelper
        {
            //returns Instagram object
            public static ICollection< IgFeedItem > ReadFeed(string IgUserId, string AccessToken)
            {
                //gets recent media photos; when count=3, it returns 3 recent photos 
                const string UriJson = "https://api.instagram.com/v1/users/{0}/media/recent/?access_token={1}&count=3";
    
                var returnIgFeedItems = new List< IgFeedItem >();
    
                try
                {
                    var IgJsonString = Core.Utilities.Json.GetJsonString(String.Format(UriJson, IgUserId, AccessToken), null, null, true);
                    //create a stream to hold the contents of the response and create Instagram Object 
                    var IgObject = JsonConvert.DeserializeObject< IgFeedJson >(IgJsonString);
    
                    if (IgObject == null || !IgObject.Data.Any()) return returnIgFeedItems;
    
                    else
                    {
                        if (IgObject.Data != null)
                        {
                            //return feed
                            returnIgFeedItems = IgObject.Data.Select(IgItem => new IgFeedItem
                            {
                                Caption = IgItem.Caption.Text,
                                Link = IgItem.Link,
                                SmallImage = IgItem.Images.LowResolution.Url,
                                ThumbnailImage = IgItem.Images.Thumbnail.Url,
                                LargeImage = IgItem.Images.StandardResolution.Url,
                                Type = IgItem.Type,
                                CreatedTime = IgItem.CreatedTime
                            }).ToList();
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error : " + ex);
                }
                return returnIgFeedItems.ToList();
            }
        }
    }
    

    Next, you have to create a controller as shown:

     //Instagram controller
    public class InstagramController : ApiController
    {
        public ICollection< IgFeedItem > GetInstagramFeed(string IgUserId) 
        {
            return Integration.Instagram.IgHelper.ReadFeed(IgUserId);
        }
    }
    

    Then you have to publish the API to your Azure instance, here is test site url: https://{enteryoursite}.azurewebsites.net/api/instagram/GetInstagramFeed?IgUserId={enterUserId}

    Finally you can use this url in SharePoint using JQuery:
    Place below code to a Sharepoint master gallery file, for example: /script/custom.js
    //Instagram Feed
    function _initInstagramFeed(IgUserId) {
        var igFeed = $('#instagram-feed');
        // get instagram posts from api
        function __getInstagramPosts(callback) {
            var apiUri = 'https://{enteryoursite}.azurewebsites.net/api/instagram/GetInstagramFeed?IgUserId=';
    
            $.ajax({
                url: apiUri + IgUserId,
                type: 'GET',
                success: function (result) {
                    callback(result);
                },
                error: function () {
                    //igFeed.closest('.ms-webpartzone-cell').hide();
                }
            });
        }
    
        // format the data returned from the instagram api
        function __processInstagramPosts(posts) {
            var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
            var instagramPostsHtml = '';
            var thumbnailImage;
            var link;
            //var caption;
            //var smallImage;
            //var largeImage;
            //var date;
            //var type;
            var post;
            for (var post in posts) {
                //caption = posts[post].Caption;
                thumbnailImage = posts[post].ThumbnailImage; 
                link = posts[post].Link;            
                if (thumbnailImage.length > 0) {                
                    if (link != null) {
                        post = '
  • '; } instagramPostsHtml += post; } } instagramPostsHtml = '
      '+instagramPostsHtml+'
    '; return instagramPostsHtml; } // get instagram posts and add them to the Instagram UI __getInstagramPosts(function (instagramPosts) { igFeed.html(__processInstagramPosts(instagramPosts)); }); }

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

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