Loading...

Tuesday, May 28, 2013

How to Monitor and Track Error Logs for SharePoint Apps?

Apart from developing app, it is equally important to  track the usages of SharePoint apps
To do so, step through as follow
1)In Ribbon--> Admin-->SharePoint--> select Apps tab (in Left )--> Apps catalog


2)Upload the tested App in this document library (Apps for SharePoint)

when you upload app here it is available to all the tenants associated with it

3)Now go back to Apps setting Page , and click Monitor Apps Link


4)Now select the App to Monitor,and see the analytic about the App.


 

Sunday, May 19, 2013

Developing Search App to Query by Result Sources using Search REST

I hope many people know about Result Source in SharePoint 2013 by now (if not Please  google out :))
Now Result sources can be queried using Search Rest Api
Following code snippet show how to do that
1)Along with query parameter you need to know guid for Result Source
To get this GUID , browse to this link _layouts/15/manageresultsources.aspx?level=site

2) Edit the required Result Source, and in browser  ,guid can be obtained from url similar to this url
_layouts/15/EditResultSource.aspx?level=site&sourceid=48fec42e-4a92-48ce-8363-c2703a40e67d&view=1
3)Add New Napa Project and add  replace app.js with this code snippet


$(document).ready(function () {
    var e = ExecuteOrDelayUntilScriptLoaded(showToolbar, "sp.js");
});

function showToolbar() {
    $("#toolbarDiv").show();
}

function executeQuery(queryTerms) {

    Results = {
        element: '',
        url: '',

        init: function (element) {
            Results.element = element;
            Results.url = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='" + queryTerms + "'&sourceid='48fec42e-4a92-48ce-8363-c2703a40e67d'";
        },

        load: function () {
            $.ajax(
                    {
                        url: Results.url,
                        method: "GET",
                        headers: {
                            "accept": "application/json;odata=verbose",
                        },
                        success: Results.onSuccess,
                        error: Results.onError
                    }
                );
        },

        onSuccess: function (data) {
            var results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
            var html = "<table>";

            for (var i = 0; i < results.length; i++) {
                html += "<tr><td>";
                html += results[i].Cells.results[0].Value;
                html += "</td><td>"
                html += results[i].Cells.results[1].Value;
                html += "</td></tr>";
     html += "<tr><td>";
                html += results[i].Cells.results[2].Value;
                html += "</td><td>"
                html += results[i].Cells.results[3].Value;
                html += "</td></tr>";
     html += "<tr><td>";
                html += results[i].Cells.results[4].Value;
                html += "</td><td>"
                html += results[i].Cells.results[5].Value;
                html += "</td></tr>";
     html += "<tr><td>";
                html += results[i].Cells.results[6].Value;
                html += "</td><td>"
                html += results[i].Cells.results[7].Value;
                html += "</td></tr>";
            }

            html += "</table>";
            Results.element.html(html);
        },

        onError: function (err) {
            alert(JSON.stringify(err));
        }
    }

    Results.init($('#resultsDiv'));
    Results.load();

}


4) and Replace Default.aspx as follows


<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>
<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
 <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
 <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
 <script type="text/javascript" src="/_layouts/15/sp.js"></script>

 <!-- Add your CSS styles to the following file -->
 <link rel="Stylesheet" type="text/css" href="../Content/App.css" />

 <!-- Add your JavaScript to the following file -->
 <script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
 Page Title
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

 <div>
  <div id="toolbarDiv" style="display: none">
        <input type="text" style="width: 200px" id="queryTerms" />
        <input type="button" value="Search" onclick="executeQuery($get('queryTerms').value);" />
    </div>
    <div id="resultsDiv"></div>
 </div>

</asp:Content>

5)And Apply Search Permissions as Read In Settings-->Permissions tab of Project 

To  Know more about search end point visit this post

Developing A Social SharePoint Hosted App With Social REST

Once you know about the end points associated with Social data, Developing Social Apps become too easy.
Following example shows , how to get the feed activity of the current user  and by the people and content user is following
To create this App, Open up new Project in Napa and click App.js
 and add the following snippet

'use strict';

var context = SP.ClientContext.get_current();
var feedManagerEndpoint;

// Get the SPAppWebUrl parameter from the query string and build
// the feed manager endpoint.
$(document).ready(function () {
    var appweburl;
    var params = document.URL.split("?")[1].split("&");
    for (var i = 0; i < params.length; i = i + 1) {
        var param = params[i].split("=");
        if (param[0] === "SPAppWebUrl") appweburl = param[1];
    }
    feedManagerEndpoint = decodeURIComponent(appweburl)+ "/_api/social.feed";
    postToMyFeed();
});

// Publish a post to the current user's feed by using the 
// "<app web URL>/_api/social.feed/my/Feed/Post" endpoint.
function postToMyFeed() {
    $.ajax( {
        url: feedManagerEndpoint + "/my/Feed/Post",
        type: "POST",
        data: JSON.stringify( { 
            'restCreationData':{
                '__metadata':{ 
                    'type':'SP.Social.SocialRestPostCreationData'
                },
                'ID':null, 
                'creationData':{ 
                    '__metadata':{ 
                        'type':'SP.Social.SocialPostCreationData'
                    },
                'ContentText':'This post was published using REST.',
                'UpdateStatusText':false
                } 
            } 
        }),
        headers: { 
            "accept": "application/json;odata=verbose",
            "content-type":"application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: getMyFeed,
        error: function (xhr, ajaxOptions, thrownError) { 
            alert("POST error:\n" + xhr.status + "\n" + thrownError);
        }
    });
}

// Get the current user's feed by using the 
// "<app web URL>/_api/social.feed/my/Feed" endpoint.
function getMyFeed() {
    $.ajax( {
        url: feedManagerEndpoint + "/my/news",
        headers: { 
            "accept": "application/json;odata=verbose"
        },
        success: feedRetrieved,
        error: function (xhr, ajaxOptions, thrownError) { 
            alert("GET error:\n" + xhr.status + "\n" + thrownError);
        }
    });    
}

// Parse the JSON data and iterate through the feed.
function feedRetrieved(data) {
    var stringData = JSON.stringify(data);
    var jsonObject = JSON.parse(stringData); 
     
    var feed = jsonObject.d.SocialFeed.Threads; 
    var threads = feed.results;
    var feedContent = "";
    for (var i = 0; i < threads.length; i++) {
        var thread = threads[i];
  
        var participants = thread.Actors;
        var owner = participants.results[thread.OwnerIndex].Name;
  alert(thread.RootPost.Text);
        feedContent += '<p>' + owner + 
            ' said "' + thread.RootPost.Text + '"</p>';
    }  
    $("#message").html(feedContent); 
}

Also  to get the feeds for particular user, REST Url can be queried as follows.

https://siteurl/_api/social.feed/actor(item='abc@abc.onmicrosoft.com')/Feed

Read more about working with Social Feeds

Make sure that following permissions are granted to SharePoint App


This is very helpful REST API (End Point) reference for Social Data
And  Tutorial for using Social REST API for following contents (Requires office 365 developer site)

Friday, May 17, 2013

Adding Basic SharePoint App as Apppart

If you observe default SharePoint  app , created by NAPA tool.,
There are two pages associated with App
1)Default.aspx
2)ClientWebPart.aspx
To Add SharePoint App discussed in this post , Move the js and css reference
and also the html contents to ClientWebPart.aspx
and make sure that framing is enabled by adding the following control.


<WebPartPages:AllowFraming ID="AllowFraming1" runat="server" />














Deploy this app and Now go to the hosting page .Edit this page and in ribbon select AppPart.
Select this App and Odata will be populated in html div


Tuesday, May 14, 2013

How To Identify If SharePoint App is installed on On-Premise or In Cloud?


This can be determined by Context Token as follows

protected void Page_Load(object sender, EventArgs e)
{
  Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]);
  string contextTokenString =
    TokenHelper.GetContextTokenFromRequest(Request);

  if (string.IsNullOrEmpty(contextTokenString))
  {
    // if On-Prem
    using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(
      hostWeb,
      Request.LogonUserIdentity))
    {
      . . .
    }
  }
  else
  {
    // if Office365
    using (var clientContext = TokenHelper.GetClientContextWithContextToken(
      hostWeb.ToString(),
      contextTokenString,
      Request.Url.Authority))
    {
      . . .
    }
  }

  . . .
}

Read further to understand hybrid authentication 

Thank you 


Monday, May 13, 2013

How to access REST Endpoint In SharePoint App in SharePoint Online?

1)In your SharePoint Online site (Office 365) create site collection using Developer site template
(In Ribbon-->Admin-->SharePoint)

2)In SharePoint App store , search for NAPA and Install this app.

3)Now create new Project and set the REST endpoint as shown in following images












4)In Explorer, Open the Default.aspx
and put the code as in following snippet.

<!-- Placeholder for the remote content -->
<span id="categories"></span>

<!-- Add references to the JavaScript libraries. -->
<script 
    type="text/javascript" 
    src="../_layouts/15/SP.Runtime.js">
</script>
<script 
    type="text/javascript" 
    src="../_layouts/15/SP.js">
</script>
<script type="text/javascript">
(function () {
    "use strict";

    // Prepare the request to an OData source
    // using the GET verb.
    var context = SP.ClientContext.get_current();
    var request = new SP.WebRequestInfo();
    request.set_url(
        "http://services.odata.org/Northwind/Northwind.svc/Categories"
        );
    request.set_method("GET");

    // We need the response formatted as JSON.
    request.set_headers({ "Accept": "application/json;odata=verbose" });
    var response = SP.WebProxy.invoke(context, request);

    // Let users know that there is some
    // processing going on.
    document.getElementById("categories").innerHTML =
                "<P>Loading categories...</P>";

    // Set the event handlers and invoke the request.
    context.executeQueryAsync(successHandler, errorHandler);

    // Event handler for the success event.
    // Get the totalResults node in the response.
    // Render the value in the placeholder.
    function successHandler() {

        // Check for status code == 200
        // Some other status codes, such as 302 redirect
        // do not trigger the errorHandler. 
        if (response.get_statusCode() == 200) {
            var categories;
            var output;

            // Load the OData source from the response.
            categories = JSON.parse(response.get_body());

            // Extract the CategoryName and Description
            // from each result in the response.
            // Build the output as a list.
            output = "<UL>";
            for (var i = 0; i < categories.d.results.length; i++) {
                var categoryName;
                var description;
                categoryName = categories.d.results[i].CategoryName;
                description = categories.d.results[i].Description;
                output += "<LI>" + categoryName + ":&nbsp;" +
                    description + "</LI>";
            }
            output += "</UL>";

            document.getElementById("categories").innerHTML = output;
        }
        else {
            var errordesc;

            errordesc = "<P>Status code: " +
                response.get_statusCode() + "<br/>";
            errordesc += response.get_body();
            document.getElementById("categories").innerHTML = errordesc;
        }
    }

    // Event handler for the error event.
    // Render the response body in the placeholder.
    // The body includes the error message.
    function errorHandler() {
        document.getElementById("categories").innerHTML =
            response.get_body();
    }
})();
</script>

5) to set different app permissions, click on 'Settings' in explorer and make sure  that following permissions  are not required for App to run.

Saturday, May 4, 2013

SharePoint Search Refinement Webpart in SharePoint 2013

In SharePoint 2010,In Search Center Site,refinements were auto populating depending on managed properties mapped to crawl property and When metadata column was created for particular document library

In SharePoint 2013 ,refiners are configurable.To verify this
Edit Search Center Page-->Edit Refiner Webpart --> Click Choose refiners .
and hit on preview button