Wednesday 7 June 2017

External Access Sharepoint API Online


Register Add-In
  • Navigate and login to SharePoint online site.
  • Then navigate to the Register Add-In page by entering the url as https://<sitename>.SharePoint.com/_layouts/15/appregnew.aspx
  • Click Generate button next to the Client Id and Client Secret textboxes to generate the respective values.
  • Enter Add-In Title in Title textbox
  • Enter AppDomian as a loclhost
  • Enter RedirectUri as a https://localhost 
  • Click Create button, which registers the add-in and returns the success message with created information.
Grant Permissions to Add-In 
  • Navigate to the SharePoint site
  • Then enter the URL https://<sitename>.sharepoint.com/_layouts/15/appinv.aspx in the browser. This will redirect to Grant permission page.
  • Enter the Client ID(which we have generated earlier), in AppId textbox and click Lookup button. That will populate the value to other textboxes in Title, App Domain and Redirect Url
  • Now enter the below permission request in XML format. 
    • <AppPermissionRequests AllowAppOnlyPolicy="true">     <AppPermissionRequest Scope="http://sharepoint/content/sitecollection/web" Right="Read" /></AppPermissionRequests>
  • Then click Create button. This will redirect to you page, where we have to trust the add-in to read items from website.

 Retrieve the Tenant ID

  •  Launch Postman chrome extension.
  • Select Get Method
  • Enter the below URL in the “Request URL” textbox https://<sitename>/sharepoint.com/_vti_bin/client.svc/
  • Configure the below information in the header section to send along with the url requestMethod = Get
  • Headers: Authorization Bearer


Generate the Access Token

  • After getting the Tenant ID, we have to form a URL with the below format    https://accounts.accesscontrol.windows.net/<TenantID>/tokens/OAuth/2 for requesting the access token.
  • Apply the below configurations in header
    • Method = POST
    • Headers
      • Content-Type : application/x-www-form-urlencoded
    • Body
      • grant_type : client_credentials
      • client_id :ClientID@TenantID
      • client_secret : ClientSecret
      • resource: resource/SiteDomain@TenantID               

  • After applying the configuration, click Send button. That will returns the response with the Access Token.


Access the SharePoint resource
  • In Postman tool, add the below URL to retrieve the web title https://<sitename>.sharepoint.com/sites/demo/_api/web/lists/getbytitle('customlist')/items
  • Apply configurations in header
  • Method = POST
    • Accept : application/json;odata=verbose
    • Authorization : Bearer ayx7fs.....
  • After applying the configuration, click Send button.
  • We will get the response successful as below if the permission xml applied correctly in app in the page. Otherwise, we will get the access denied error message.


Friday 17 February 2017

SharePoint REST API


  • SharePoint Search REST API 
  • Call External REST API 
  • Get and Create List Items using REST API 
  • Get Current Login User Name Using REST API


SharePoint Search REST API
<html>
<head>
<script type="text/javascript" src="/sites/testing/SiteAssets/jquery-1.9.1.min.js"></script>
<script type="text/javascript">

function SearchResult(clicked_id){

 var searchString=document.getElementById('txtSearch').value;
 var rootSite="https://<domain>/sites/testing";
 $("#result").html("");
    $.ajax({
      dataType: 'text',
      url: rootSite+"/_api/search/query?querytext='"+searchString+"'",
      data: '',
      success: function (data) {         
        
         xmlDoc = $.parseXML(data),
         $xml = $( xmlDoc );
         var appendData="";
         var title="";
         var link="";
         var author="";
         var fileType="";
         var ValueType="";
        
         $($xml.find("d\\:query>d\\:PrimaryQueryResult>d\\:RelevantResults>d\\:Table>d\\:Rows>d\\:element>d\\:Cells>d\\:element")).each(function(){
                  var key=$(this).find("d\\:Key").text();
                  if(key=="Title"){                  
                    title=$(this).find("d\\:Value").text();
                 }
                 if(key=="Author"){                  
                     author=$(this).find("d\\:Value").text();               
                }
                  if(key=="Path"){                  
                     link=$(this).find("d\\:Value").text();                                     
                }
                if(key=="FileType"){                  
                     fileType=$(this).find("d\\:Value").text();
                     ValueType=$(this).find("d\\:ValueType").text();                                 
                }
                if(key=="SPWebUrl"){                       
                    var siteUrl=$(this).find("d\\:Value").text();  
                    if(siteUrl==rootSite)
                    {  
                        if(clicked_id=="all"){
                            var alink =fileType+ " <a href='"+link+"'>"+title+"</a>  by "+author+"</br>";
                            $("#result").append(alink);
                        }
                      
                        if(clicked_id=="documents" && fileType!="aspx"){
                            var alink =fileType+ " <a href='"+link+"'>"+title+"</a>  by "+author+"</br>";
                            $("#result").append(alink);
                        }
                      
                        if(clicked_id=="list" && ValueType=="Null"){
                            var alink =fileType+ " <a href='"+link+"'>"+title+"</a>  by "+author+"</br>";
                            $("#result").append(alink);
                        }                       
                    }
                }
              
         });                
        //document.getElementById('result').innerHTML=appendData;
      },    
      error:  function(){
      alert("Error");
    }
    });
}

</script>
</head>
<body>
<input type="text" style="font-size:18px;color:gray" id="txtSearch" value="">

    <div style="font-size:18px">
    <a href="#" id="all" onclick="SearchResult(this.id)">All</a>
    <a href="#" id="documents" onclick="SearchResult(this.id)">Document</a>
    <a href="#" id="list" onclick="SearchResult(this.id)">List</a>
    </div>
</br>
 <div id="result" style="font-size:18px">
 </div>
</body>
</html>

_____________________________________________________________________
SharePoint Call External REST API 
<html>
<head>
<script type="text/javascript" src="/sites/testing/SiteAssets/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function testws(){
    $.ajax({
      dataType: 'json',
      url: 'https://server/emberws/requestcheck.php',
      data: '',
      success: function (data) {       
        alert(data.pets[0].name);
      },     
      error:  function(){
      alert("Error");
    }
    });
}
function postMethod(){
     var name=$('#txtName').val();
    $.ajax({     
      type:'post',
      url: 'https://server/emberws/postcheck.php',
      data: {param:name},
      success: function (data) {       
        alert(data.resp);
      },     
      error:  function(){
      alert("Error");
    }
    });
}
$(document).ready(function (e){
    $("#uploadimage").on('submit',(function(e) {            
        e.preventDefault();                  
        $.ajax({
            url: "https://server/emberws/uploadcheck.php",
            type: "POST",
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData:false,
            success: function(data){
                $('#rimage').attr('src', data.resp);            
            }
        });         
    }));       
});

</script>
</head>

<body>
  <WebPartPages:SPWebPartManager runat="server"/>
  <form id="form1" runat="server"> 
  <!--GET and POST Method -->
    <input name="Button1" onclick="testws();" type="button" value="Get Method" />
    <br/>
    <input name="Text1" id="txtName"  type="text" />
    <input name="Button1" onclick="postMethod()" type="button" value="Post Method" />
 <br/> 
 </form>
  <!--Upload Image -->
  <form id="uploadimage" method="post" enctype="multipart/form-data">               
    <input type="file" name="image" id="image"/>
    <input type="submit" value="Upload" class="submit" />
</form>
<img src="" id="rimage"/>
</body>
</html>

_____________________________________________________________________
SharePoint Get and Create List Items using REST API 


<script type="text/javascript" src="/sites/testing/SiteAssets/jquery.min.js"></script>
<script type="text/javascript" src="/sites/testing/SiteAssets/jquery-1.9.1.min.js"></script>
<script type="text/javascript">

function onGetCustomer(id) {
   var requestUri = _spPageContextInfo.webAbsoluteUrl +
                "/_api/Web/Lists/getByTitle('AccessDataList')/items("+id+")";  
  $.ajax({ 
    url: requestUri,
    type: "GET",
    headers: { "ACCEPT": "application/json;odata=verbose" },
    success: function(data){    
     alert(data.d.Title);       
    },
    error:  function(){
      alert("Failed to get customer");
    }
  });
}

function CreateListItemWithDetails() {
    var itemType = GetItemTypeForListName("AccessDataList");
    var item = {
        "__metadata": { "type": itemType },
        "Name": "Test2"
    };

    $.ajax({
        url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('AccessDataList')/items",
        type: "POST",
        contentType: "application/json;odata=verbose",
        data: JSON.stringify(item),
        headers: {
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val()
        },
        success: function (data) {
            alert("Success");
        },
        error: function (data) {
            alert("Fail");
        }
    });
}

// Get List Item Type metadata
function GetItemTypeForListName(name) {
    return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}

</script>




_____________________________________________________________________
SharePoint Get Current Login User Name Using REST API

<script type="text/javascript" src="/SiteAssets/jquery-1.9.1.min.js"></script>
 

<script type="text/javascript">
var loginName = "";
var userid = _spPageContextInfo.userId;
GetCurrentUser();

function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";

var requestHeaders = { "accept" : "application/json;odata=verbose" };

$.ajax({
  url : requestUri,
  contentType : "application/json;odata=verbose",
  headers : requestHeaders,
  success : onSuccess,
  error : onError
  });
}

function onSuccess(data, request) {
    var loginName = data.d.LoginName;
    alert("Hello " + loginName);

    // to set the "hello username" into the page
    document.getElementById("id").innerHTML = "Hello " + loginName;
    }

function onError(error) {
  alert(error);
  }

</script>






Monday 13 February 2017

MS Access Databased Migration to Sharepoint and SQL Server

Two way of Access Database Migration:
  1. Using sharepoint Access web app.
  2. Using Microsoft SQL Server Migration Assistant v6.0 for Access Tools.
1. Using sharepoint Access web app: 
  • Login to O365 account.
  • Click on Site Contents
  • Click on Add an app
  • In the search control, perform a search for ‘Access   
  • Click on Access App
  • Once the App loads, Click on Settings (the Gear in the top right-hand corner)
  • Click on Customize in Acces
  • At the bottom of the Access screen, Click on Access (assuming your be is an Access database) from the Create a table from an existing data source menu  
  • Go to the File tab and click on Manage (under the Connections)
  • The following menu/dialog will appear.  Click on From Any Location, as well as, Enable Read-Write Connection.
  • Click on click on View Read-Write Connection Information.     
Reference : https://www.youtube.com/watch?v=4tpgX2tQDBE
                   http://www.devhut.net/2014/01/13/how-to-hybridize-your-ms-access-database-in-office-365-azure-database/


2. Using Microsoft SQL Server Migration Assistant v6.0 for Access Tools.
        SQL Server Migration Assistant (SSMA) for Access lets you quickly convert Access database objects to SQL Server or Azure SQL DB objects

 

Wednesday 8 February 2017

SharePoint Online: Authenticating .NET Client Object Model in Office 365

Below the sample code:
   You will need to reference the Microsoft.SharePoint.Client.dll and the Microsoft.SharePoint.Client.Runtime.dll assemblies in your project.

     static void Main(string[] args)
            {          
               Task<string> result = getWebTitle("https://<domain>/sites/testing");
                    result.Wait();
                    Response.Write(result.Result);
            }

      private static async Task<string> getWebTitle(string webUrl)
            {
              
                const string PWD = "******";
                const string USER = "username";
                const string RESTURL = "{0}/_api/web/lists/getbytitle('PictureLibrary')/items(2)/File";    
                var passWord = new SecureString();
                foreach (var c in PWD) passWord.AppendChar(c);
                var credential = new SharePointOnlineCredentials(USER, passWord);
               
                using (var handler = new HttpClientHandler() { Credentials = credential })
                {
                    Uri uri = new Uri(webUrl);
                    handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));
                    using (var client = new HttpClient(handler))
                    {
                        client.DefaultRequestHeaders.Accept.Clear();
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        HttpResponseMessage response = await client.GetAsync(string.Format(RESTURL, webUrl)).ConfigureAwait(false);
                        response.EnsureSuccessStatusCode();
                        string jsonData = await response.Content.ReadAsStringAsync();
                        return jsonData;
                    }
                }
            }

Tuesday 7 February 2017

Sharepoint online resize picture library images

Activate the following two features:
1.Go to Site Settings -> Site Collection Administrator -> Site Collection Feature->From this activate SharePoint Server Publishing Infrastructure feature.
2.Go to Site Settings -> Site Actions -> Manage Site Features->From that activate SharePoint Server Publishing feature.
Steps:
1.On the Site Settings page, in the Look and Feel section, click on Image Renditions link
2.On the Image Renditions page, choose Add new item
3.On the New Image Rendition page, in the Name box, enter a name for the rendition
4.In the Width and Height text boxes, enter the width and height, in pixels, of the rendition, and then choose Save.
5.Go to home page and Edit the page.
6.Insert tab, open the Picture group and select From SharePoint
7.Choose your file from picture library.
8.select image and click Image tab
9.Click on Pick Rendition in the Ribbon and choose <Your Rendition>.



Friday 3 February 2017

Customize SharePoint 2013 Search Navigation

1. Launch the Search Center site from the browser window
2. Select Site Settings
3. Under Site Collection Administration, select Search Result Sources
4. Select New Result Source
5. Provide a name for the new result source (ex: Legacy)
6. Under the Protocol section, select Local SharePoint
7. Under the Type section, select SharePoint Search Results
8. Under the Query Transform section, click Launch Query Builder
9. In the Query text box, type: {searchTerms} (contentclass:sts_listitem) path:http://<MySharePointsite> | OR use | {searchTerms} (IsDocument:"True" OR contentclass:"STS_ListItem") path:
http://<MySharePointsite>
Your screen should look similar to the following screenshot:
10. To validate the query, click Test Query (This should return relevant results in the preview pane.)
11. Select the TEST tab, and select Show more
12. To mimic what a user will see in the Search Center, type a query in the {searchTerms}: box
13. Click Test query (This should return a filtered result view based on the value provided in the searchTerms box.
14. Click OK to close the Build Query window
15. Click Save to close the Result Source window
16. Select Add a page from the Gear Icon
17. Provide a name for the page (ex: Legacy), then click Create
18. In the Search Results web part, select Edit Web Part
19. In the Web part properties, click Change query
20. In the Select a query section, select Legacy (Site Collection) from the dropdown menu
21. Click OK to close the Build Your Query window
22. Click OK to close the Web part properties window
23. Check in and publish the page
24. From Search Center, select Site Settings
25. Under Search, select Search Settings
26. Under Configure Search Navigation section, select Add Link
27. Provide a title (ex: Legacy) (This will appear on the Search Navigation as “Legacy”)
28. Select Browse
29. Select Pages, select Legacy.aspx, then click Insert
30. Click OK to close the Navigation Link window
31. Click OK to close the Search Settings window
32. To validate changes made to the Custom Search Navigation, navigate to the Search Center site
33. Type in a query string – notice the results displayed at the bottom of the ‘Everything’ tab.
Your custom navigation should look similar to this:

Thursday 2 February 2017

How to setup Enterprise Keywords in SharePoint

1. Add Enterprise Keywords to a  document library. In the ribbon, go to Library Tab, then click on Library Settings

2. click on Enterprise Metadata and Keywords Settings

3. Click the check box next to Add an Enterprise Keywords column to this list and enable Keyword synchronization. Click OK

4.  Go to Advanced Settings in the Library Control Panel and choose Yes next to Allow management of content types? radio button. Click OK.   
5. Not showing Enterprise Keywords Column, Go to modify the view and check the box next to Enterprise Keywords. Click OK.