Showing posts with label SharePoint 2013. Show all posts
Showing posts with label SharePoint 2013. Show all posts

Friday, 8 September 2017

Use Typescript for SharePoint 2013 Apps Development

Introduction

This article shows how to use Typescript in SharePoint 2013 while creating SharePoint Hosted app using Visual Studio 2015/2013. 

Prerequisite:

  • Learn Typescript. To know more about TypeScript - Click Here 
  • Create a SharePoint Hosted App project in Visual Studio. I have given project name as "TypeScriptApp


Let's Start

Let's complete this task in following steps:-   

  • Right click on Project name "TypeScriptApp". Select "Unload project" option.



  • Edit project file(TypescriptApp.csproj).





  • Mention following MSBuild properties in project file(TypeScriptApp.csproj) as shown below:


  <PropertyGroup Condition="'$(Configuration)' == 'Debug'">  
   <TypeScriptRemoveComments>false</TypeScriptRemoveComments>  
   <TypeScriptSourceMap>true</TypeScriptSourceMap>  
  </PropertyGroup>  
  <PropertyGroup Condition="'$(Configuration)' == 'Release'">  
   <TypeScriptRemoveComments>true</TypeScriptRemoveComments>  
   <TypeScriptSourceMap>false</TypeScriptSourceMap>  
  </PropertyGroup>  
  <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets')" />  



  • For more details on MSBuild properties and Compiler Options -  Click Here
  • Close the .csproj file. Right click on Project name. Select "Reload project" option.

  •  Right click on project Name and check properties of it. You will get to see TypeScript Build option with following configuration.
   


  • Create html table in Default.aspx to bind SharePoint "Sales" List data using Typescript and JSOM.

  • Install following typings from Nuget package Manager :-
    • jquery.TypeScript.DefinitelyTyped
    • sharepoint.TypeScript.DefinitelyTyped
    • microsoft-ajax.TypeScript.DefinitelyTyped

  • Set the Deployment Type property of all the typescript file as "No Deployment".
                                   

  • Add a new TypeScript File.I have created in script folder named it as "crudLogic.ts".
  • Set the Deployment Type property of "crudLogic.ts" file as "No Deployment".
  • Drag and Drop reference of  "SharePoint.d.ts" and "jquery.d.ts" on crudlogic.ts file.
  • Create a Class, name it as BasicOperations in crudlogic.ts file. Mention following properties:-
 class BasicOperations {  
   //Define properties with respect BasicOperations Class  
    _currentContext: SP.ClientContext;  
    _hostContext: SP.AppContextSite;  
    _web: SP.Web;  
    _colList: SP.ListCollection;  
    _list: SP.List;  
    _listItems: SP.ListItemCollection;  
    query: SP.CamlQuery;  
   constructor() {  
     let hostweburl = decodeURIComponent(this.getQueryStringParameter("SPHostUrl"));  
     this._currentContext = SP.ClientContext.get_current();  
     this._hostContext = new SP.AppContextSite(this._currentContext, hostweburl);  
     let appweburl = decodeURIComponent(this.getQueryStringParameter("SPAppWebUrl"));  
     this._web = this._hostContext.get_web();  
   }  
 }  

  • In the constructor of class get the Query String parameter value of SPHostUrl and SPAppWebUrl.

 private getQueryStringParameter(urlParameterKey: string) {  
     var params = document.URL.split('?')[1].split('&');  
     var strParams = '';  
     for (var i = 0; i < params.length; i = i + 1) {  
       var singleParam = params[i].split('=');  
       if (singleParam[0] == urlParameterKey)  
         return decodeURIComponent(singleParam[1]);  
     }  
   }  

  • Create a interface ICrudOperation. Define a method GetAllItems. This interface will be implemented in BasicOperations Class

 interface ICrudOperation {  
   GetAllItems(): void;  
 }  

  • Create a Logger interface. Define a method logError. This interface will be implemented in BasicOperations Class.
 interface ILogger {  
   logError(sender: any, e: SP.ClientRequestFailedEventArgs): void;  
 }  

  • Implement both interface ICrudOperation and Ilogger in BasicOperations class using "implement' keyword.
 class BasicOperations implements ICrudOperation, ILogger {  
 }  
  • Implement  GetAllItems and LogError method in BasicOperations class using JSOM.
  GetAllItems(): void {  
     this._list = this._web.get_lists().getByTitle("Sales");  
     this.query = new SP.CamlQuery();  
     this.query.set_viewXml('<View><RowLimit></RowLimit>12</View>');  
     this._listItems = this._list.getItems(this.query);  
     this._currentContext.load(this._list);  
     this._currentContext.load(this._listItems);  
     this._currentContext.executeQueryAsync(() => this.OnSuccess(), (sender: any, args: SP.ClientRequestFailedEventArgs) => this.logError(this, args));  
   }  
   private OnSuccess() {  
     var listItemEnumerator = this._listItems.getEnumerator();  
     while (listItemEnumerator.moveNext()) {  
       var currentItem = listItemEnumerator.get_current();  
       $(".SalesTable").append("<tr>"+"<td>"+"<b>" + currentItem.get_item('Month') + "</b>"+"</td>"+"<td>"+"<b>" + currentItem.get_item('Totalsales') + "</b>"+"</td>"+"</tr>");        
     }  
   }  
   logError(sender, args) {  
     $(".message").html("Request Failed: " + args.get_message());  
   }  

  • Use ExecuteOrDelayUntilScriptLoaded  method to call a pageLoad function after sp.js loads in  the browser
  • In the pageLoad function create a instance of BasicOperations Class and call GetAlItems() function. 
 'use strict';  
 ExecuteOrDelayUntilScriptLoaded(pageload, "sp.js");  
 function pageload() {  
   let foo: BasicOperations = new BasicOperations();  
   foo.GetAllItems();  
 }  
  •  Save 'crudLogic.ts' file.  Click on show all files icon from Solution Explorer. Transcript compiler will create crudLogic.js' (javaScript) and 'crudLogic.js.map' file in script folder. Include crudLogic.js in the project.



  • Set the Deployment Type property of crudLogic.js file to ElementFile.
  • Remove all the typescript file from the Elements.xml file(present in Scripts folder) and make sure crudLogic.js file is included in Script Module.




  • Include script link for crudLogic.js in Default.aspx  page.

  • Deploy SharePoint Hosted app. You will get to see expected result on "Default.aspx" page




  • It's Done. Hurray!!! 



Tuesday, 20 June 2017

Sync Outlook with Sharepoint Calendar List


Introduction

This article shows how to connect your Outlook with SharePoint Calendar List.

Prerequisite:

Outlook should be configured in your system.

Let's Start

Let's complete this task in following steps:-     

  •   Navigate to your SharePoint Calendar List you want to Connect it to Outlook.
  •   In CALENDAR tab select "Connect to Outlook"



  • A popup will open Select "Open URL:Outlook....." button.


  • Microsoft Outlook Popup will open to configure Calendar.



  • Click on "Advanced" button.
  • Provide description and select appropriate checkbox as required. 


  • You will able to view SharePoint Calendar events in Outlook calendar. 

  • Done!!!



  

Thursday, 13 October 2016

Add Attachment to a List Item using REST api in

SharePoint 2010/2013

Introduction

This article is about how to use REST api to attach file to a list item in SharePoint 2010/2013.

Let's Start

Create a JavaScript function named addFile . Pass ListName and ItemId  as a parameter to addFile function as show below:-

 function addFile(listName,itemId){  
      var allFiles = [];  
      var input = document.getElementById('file');  
      var file = input.files[0];  
      if (file != null && file.size > 0) {  
                          allFiles.push(file);  
      }  
      if (allFiles.length > 0) {                             
                          uploadFile(listName, itemId, allFiles);  
      }  
      else {  
           alert("Please select the Attachment");  
      }          
 }  

UploadFile function is going to attach file to a list item using REST api as show below:-

 function uploadFile(listName, id, file) {  
    var deferred = $.Deferred();  
    var fileName = file.name;  
    getFileBuffer(file).then(  
    function (buffer) {  
     var bytes = new Uint8Array(buffer);  
     var binary = '';  
     for (var b = 0; b < bytes.length; b++) {  
     binary += String.fromCharCode(bytes[b]);  
     }  
     var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";  
     console.log(' File size:' + bytes.length);  
     $.getScript(scriptbase + "SP.RequestExecutor.js", function () {  
     var createitem = new SP.RequestExecutor(_spPageContextInfo.webServerRelativeUrl);  
     createitem.executeAsync({  
      url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/GetByTitle('" + listName + "')/items(" + id + ")/AttachmentFiles/add(FileName='" + fileName + "')",  
      method: "POST",  
      binaryStringRequestBody: true,  
      body: binary,  
      success: fsucc,  
      error: ferr,  
      state: "Update"  
     });  
     function fsucc(data) {  
      console.log(data + ' uploaded successfully');  
      deferred.resolve(data);  
     }  
     function ferr(data) {  
      console.log(fileName + "not uploaded error");  
      deferred.reject(data);  
     }  
     });  
    },  
    function (err) {  
     deferred.reject(err);  
    }  
    );  
    return deferred.promise();  
   }  

  Convert file to stream of bytes using FileReader() Object .

 function getFileBuffer(file) {   
            var deferred = $.Deferred();   
            var reader = new FileReader();   
            reader.onload = function (e) {   
              deferred.resolve(e.target.result);   
            }   
            reader.onerror = function (e) {   
              deferred.reject(e.target.error);   
            }   
            reader.readAsArrayBuffer(file);   
            return deferred.promise();   
         }   

Monday, 19 September 2016

"Working on it..." Custom Dialog Box in SharePoint

 using Javascript/Jquery(JSOM)

Introduction

This article is about creating "Working on it" Custom Dialog Box  in SharePoint.

Let's Start


Define a global Variable 'waitDialog'.

 var waitDialog = null;  

   While calling a Save function using Rest API or any long Operation function, Call RequestStarted() function at the starting and just before the end of the Save function,  Call  RequestEnded() function.


 function RequestStarted() {  
   ExecuteOrDelayUntilScriptLoaded(ShowWaitScreen, "sp.js");  
   };  
  function RequestEnded() {  
   try {  
    waitDialog.close();  
    waitDialog = null;  
   } catch (ex) { }  
   };  
   function ShowWaitScreen() {  
   try {  
    if (waitDialog == null) {  
    //waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Processing...', 'Please wait while request is in progress.', 100, 380);  
    waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose(SP.Res.dialogLoading15);  
    }  
   } catch (ex) { }  
   }  



   Instead of "Working on it..." Dialog box ,For custom dialog box use following code:-

  waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Processing...', 'Please wait while request is in progress.', 100, 380);