Thursday, October 15, 2015

Send email using SP.Utilities and Javascript

Use this below function to send an email to set people using JavaScript.

var toArr = new Array();
var ccArr = new Array();

function sendEmail() {
    debugger;
    var urlTemplate = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.Utilities.Utility.SendEmail";
    var formDigest = document.getElementById("__REQUESTDIGEST").value;
    jQuery.ajax({
        contentType: 'application/json',
        url: urlTemplate,
        type: 'POST',
        data: JSON.stringify({
            'properties': {
                '__metadata': { 'type': 'SP.Utilities.EmailProperties' },
                'From': from,
                'To': { 'results': toArr },
                'CC': { 'results': ccArr },
                'Subject': subject,
                'Body': body
            }
        }),
        headers: {
            "Accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "X-RequestDigest": formDigest
        },
        success: function (data) {
           
           //Success info..
        },
        error: function (err) {        
            console.log("sendEmail function : " + err);
        }
    });
}

Get the information form SharePoint list using REST ajax call

Add this below script into the Content Editor Webpart


(function ($) {
    $(document).ready(function () {
        // Ensure that the SP.js file is loaded before the custom code runs.
        SP.SOD.executeOrDelayUntilScriptLoaded(loadCompletedEventsData, 'SP.js');
    });

    /**************************************************************************************************
    * Function : loadCompletedEventsData                                                              *
    * Descritption : This function is used to get the data and assign the data to the respective table*
    **************************************************************************************************/
    //Get today Date and Year
    var curDate = new Date();
    curDate = curDate.getFullYear() + '-' + (curDate.getMonth() + 1) + '-' + curDate.getDate() + 'T00:00:00Z';
    function loadCompletedEventsData() {
        var CompletedEventListName = "Upcoming Events";
        jQuery.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + CompletedEventListName + "')/Items?$orderby=EventEndDate desc&$filter=EventEndDate lt datetime'" + curDate + "'",
            type: "GET",
            headers: { Accept: "application/json;odata=verbose" },
            success: function (data) {
                if (data.d.results.length > 0) {
                    var results = data.d.results;
                    var convertDate;
                    var cplMonthNames = ["January", "February", "March", "April", "May", "June", "July",
                                    "August", "September", "October", "November", "December"];
                    var uniqueYear = new Array();
                    var viewAllCompletedEvents = _spPageContextInfo.webAbsoluteUrl + "/Pages/Completed-Events.aspx";
                    var completedEventDisplayUrl;
                    var iCounter = 0;
                    var finalCounter = 4;
                    $.each(results, function (index, dataEvents) {
                        var completedEventID = dataEvents.Id;
                        var completedEventTopic = dataEvents.Title;
                        var completedEventDescription = dataEvents.EventDescription;
                        var completedEventImageUrl = dataEvents.Image;
                        var completedEventEndDate = dataEvents.EventEndDate;
                        var tblhddate = new Date(completedEventEndDate);
                        var cplStrItem = "";
                        var completedEventDisplayUrl = _spPageContextInfo.webAbsoluteUrl + "/Pages/Event-Details.aspx?ID=" + completedEventID + "&InitialTabId=Ribbon.Read";
                        if (completedEventEndDate != "") {
                            $("#tbl-EveAndHapCompletedEventsViewAllLink").html();
                            if (iCounter < finalCounter) {
                                // Create a table row dynamically based on the content from the list.
                                cplStrItem = "<tr>" +
                                                "<td>" +
                                                    "<h3 >" + cplMonthNames[tblhddate.getMonth()] + " " + tblhddate.getDate() + ", " + tblhddate.getFullYear() + "</h3>" +
                                                    "<a href='" + completedEventDisplayUrl + "' > " + completedEventTopic + "</a>" +
                                                "</td>" +
                                            "</tr>";
                                $("#tbl-EveAndHapCompletedEventsContents").append(cplStrItem);
                                iCounter++;
                            }
                            else {
                                $("#tbl-EveAndHapCompletedEventsViewAllLink").html("<a href='" + viewAllCompletedEvents + "' > View All </a>");
                                return false;
                            }
                        }
                    });
                }
                else {
                   
                    strItem = "<tr><td><div class='queryEmptyMsg'> There are currently no Completed Events available. </div></td></tr>";
                    $("#tbl-EveAndHapCompletedEvents").html(strItem);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                Console.log("completedEvents.js:loadCompletedEventsData:: " + textStatus);
            }
        });
    }
})(jQuery);

How to get current logged user information using SharePoint REST Ajax call

Add content editor webpart into the sharepoint Page

Add the below script into it.

(function ($) {
    $(document).ready(function () {
        // Ensure that the SP.UserProfiles.js file is loaded before the custom code runs.
        SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
    });

    function loadUserData() {
        jQuery.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",
            type: "GET",
            headers: { Accept: "application/json;odata=verbose" },
            success: function (data) {
                if (data.d.DisplayName != null)
                    $("#lbl-MyProfileName").html(data.d.DisplayName);

                $("#lbl-MyProfilePhoneNumberEmail").html(data.d.Email);

                $("#lbl-MyProfileDesignation").html(data.d.Title);

                if (data.d.PictureUrl != null) {
                    var encodedPictureURL = encodeURIComponent(data.d.PictureUrl);                  
                    $("#img-MyProfileImage").attr("src", "/_layouts/15/userphoto.aspx?size=L&url=" + encodedPictureURL);
                }
                if (data.d.UserProfileProperties != null) {
                    $.each(data.d.UserProfileProperties.results, function (index, value) {
                        if (value.Key == "WorkPhone") {
                            $("#lbl-MyProfilePhoneNumber").html(data.d.UserProfileProperties.results[index].Value);
                        }
                        else if (value.Key == "Office") {
                            $("#lbl-MyProfileLocation").html(data.d.UserProfileProperties.results[index].Value);
                        }
                    });
                }
            },
            error: function (jqxr, errorCode, errorThrown) {
                alert("Error: " + args.get_message());
            }
        });
    }
})(jQuery);

Tuesday, October 13, 2015

Play SWF file in SharePoint Page


1.       Add folder to the Document Library
·         Go to the document library where you want to add a folder
·         Using Windows Explorer view. Just navigate to the library, and click on the Windows Explorer View, then copy the folder you want to download, and paste it on your computer.


Copy folder from local drive to SharePoint library


Create a webpart page in Site Page Library

Add script Editor Webpart

·         On the Edit page, select the Insert Web Part tab from the Ribbon. From the Categories menu, select Media and Content and then Script Editor from the Parts menu:


Embedding Code to Your Site:
  • Once the Web Part has been successfully installed on your page, you will see a hyperlink button under the Script Editor labeled EDIT SNIPPET. Click the EDIT SNIPPET link to insert HTML/Script code:

Add code below code into the editor
<iframe width="740" height="499" src="http://wwblrsp2013:1515/sites/OldRC/Assets/Storyline%20output/story.swf"></iframe>
Change .swf file URL



Get the word file form SharePoint Library and convert to PDF using ASPOSE (CSOM)

We have a business requirement which is similar to word automation service but this requirement we have used ASPOSE and SharePoint CSOM.

 Requirement:


  • Get the document from SharePoint Library
  • Read the document data in the format of Byte[]
  • Get the data from workflow history List
  • Append the history data to document in the format of Table
  • Convert Word to PDF
  • Upload PDF to another SharePoint Library

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Aspose.Words;
using Aspose.Words.Saving;
using Microsoft.SharePoint.Client;
using ClientOM = Microsoft.SharePoint.Client;
using System.IO;

namespace DocumentToPDF
{
    class Program
    {
        static private void CopyStream(Stream source, Stream destination)
        {
            try
            {
                byte[] buffer = new byte[32768];
                int bytesRead;
                do
                {
                    bytesRead = source.Read(buffer, 0, buffer.Length);
                    destination.Write(buffer, 0, bytesRead);
                } while (bytesRead != 0);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }       

        static void Main(string[] args)
        {
            try
            {
                //Update this Info accordingly
                string siteUrl = "http://contoso:1515/sites/OldRC";
                string sourceLibraray = "Shared Documents";
                string targetLibrary = "http://contoso:1515/sites/OldRC/Shared%20Documents/";
                string tempFileDirectory = "F:/Nagaraju/Shared/";
                string workflowHistoryList = "PollQuestions";

                ClientContext clientContext =
                    new ClientContext(siteUrl);
                List sharedDocumentsList = clientContext.Web.Lists
                    .GetByTitle(sourceLibraray);
                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = @"<View>  
                                        <Query> 
                                           <Where><Eq><FieldRef Name='Status' /><Value Type='Choice'>2</Value></Eq></Where> 
                                        </Query> 
                                 </View>";
                ListItemCollection listItems = sharedDocumentsList.GetItems(camlQuery);
                clientContext.Load(sharedDocumentsList);
                clientContext.Load(listItems);
                clientContext.ExecuteQuery();
                foreach (ClientOM.ListItem item in listItems)
                //if (listItems.Count == 1)
                {
                    //ClientOM.ListItem item = listItems[0];
                    Console.WriteLine("FileLeafRef: {0}", item["FileLeafRef"]);
                    string fileName = item["FileLeafRef"].ToString();
                    Console.WriteLine("FileDirRef: {0}", item["FileDirRef"]);
                    Console.WriteLine("FileRef: {0}", item["FileRef"]);
                    Console.WriteLine("File Type: {0}", item["File_x0020_Type"]);
                    Console.WriteLine("File Name: {0}", item["FileRef"]);
                    FileInformation fileInformation =
                        ClientOM.File.OpenBinaryDirect(clientContext, (string)item["FileRef"]);
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        CopyStream(fileInformation.Stream, memoryStream);
                        Aspose.Words.Document DOC = new Aspose.Words.Document(memoryStream);
                        PdfSaveOptions saveOptions = new PdfSaveOptions();
                        saveOptions.Compliance = PdfCompliance.PdfA1b;

                        //Get Approvers info
                        //ClientContext clientContext = new ClientContext(siteUrl);
                        List approverList = clientContext.Web.Lists.GetByTitle(workflowHistoryList);
                        camlQuery.ViewXml = string.Format(@"<View>  
                                                <Query> 
                                                   <Where><Eq><FieldRef Name='ParentId' /><Value Type='Lookup'>{0}</Value></Eq></Where> 
                                                </Query> 
                                            </View>", item.Id.ToString());
                        ListItemCollection approverItems = approverList.GetItems(camlQuery);
                        clientContext.Load(approverList);
                        clientContext.Load(approverItems);
                        clientContext.ExecuteQuery();
                        ClientOM.ListItem approverItem = approverItems[0];
                        DocumentBuilder builder = new DocumentBuilder(DOC);

                        //First Table
                        // We call this method to start building the table.
                        builder.StartTable();
                        builder.InsertCell();
                        builder.Write("Header 1");

                        // Build the second cell
                        builder.InsertCell();
                        builder.Write("Header 2");
                        // Build the third cell
                        builder.InsertCell();
                        builder.Write("Header 3");                        
                        // Call the following method to end the row and start a new row.
                        builder.EndRow();

                        // Build the first cell of the second row - Update List column internal names.
                        builder.InsertCell();
                        builder.Write(item["FileLeafRef"].ToString());
                        // Build the second cell.
                        builder.InsertCell();
                        builder.Write(item["Title"].ToString());
                        // Build the third cell.
                        builder.InsertCell();
                        builder.Write(item["ID"].ToString());                        
                        builder.EndRow();

                        //Second Table
                        builder.MoveToDocumentEnd();
                        // We call this method to start building the table.
                        builder.StartTable();
                        builder.InsertCell();
                        builder.Write("Header 1");

                        // Build the second cell
                        builder.InsertCell();
                        builder.Write("Header 2");
                        // Build the third cell
                        builder.InsertCell();
                        builder.Write("Header 3");
                        // Build the fourth cell
                        builder.InsertCell();
                        builder.Write("Header 4");
                        // Call the following method to end the row and start a new row.
                        builder.EndRow();

                        // Build the first cell of the second row- Update List column internal names.
                        builder.InsertCell();
                        builder.Write(approverItem["Question"].ToString());
                        // Build the second cell.
                        builder.InsertCell();
                        builder.Write(approverItem["Answer1"].ToString());
                        // Build the second cell.
                        builder.InsertCell();
                        builder.Write(approverItem["Answer2"].ToString());
                        // Build the second cell.
                        builder.InsertCell();
                        builder.Write(approverItem["Answer3"].ToString());
                        builder.EndRow();

                        // Signal that we have finished building the table.
                        builder.EndTable();

                        DOC.Save(tempFileDirectory + fileName.Split('.')[0] + ".pdf", saveOptions);

                        FileStream fstream = System.IO.File.OpenRead(tempFileDirectory + fileName.Split('.')[0] + ".pdf");
                        byte[] content = new byte[fstream.Length];
                        fstream.Read(content, 0, (int)fstream.Length);
                        fstream.Close();
                        FileCreationInformation fi = new FileCreationInformation();
                        fi.Url = targetLibrary + fileName.Split('.')[0] + ".pdf";
                        fi.Content = content;
                        sharedDocumentsList.RootFolder.Files.Add(fi);
                        clientContext.ExecuteQuery();
                        Console.WriteLine("Document uploaded to SharePoint Library.");
                    }
                }
                //else
                //    Console.WriteLine("Document not found.");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

}

Thursday, October 8, 2015

Hide the Content Types based on Document Set Title in SharePoint Library Using JavaScript

Steps for Implementation
Create a Site Content Types Navigate Site Settings>>Site Content Types>>Click on Create
Click on OK Go to Library >> Library Settings >> Click on Document Set
Click on Document Set Settings and move HR Policy to Right side box
Click on OK then the content types will be added to library
So please add all other content types which is use for your business requirement using the above steps Hide the Relevant Content Types.
Get the Content Type ID from browser using the below screenshot

Add the below script into the page using Content Editor Webpart

<script type="text/javascript">
_spBodyOnLoadFunctionNames.push("hideContentType");
function hideContentType(){
$("a.ms-cui-ctl-a2 ").live('click', function (event) {
var documentSetTitle = $('div[id="idDocSetPropertiesWebPart"]').children()[0];
documentSetTitle = documentSetTitle.innerText;
$('li[class="ms-cui-menusection-items"]').css("display", "none");
if(documentSetTitle.indexOf("HR") > -1)
{
$('a[id="Ribbon.Document.All.NewDocument.Menu.ContentTypes.1-Menu32"]').parents('li').css("display", "");
$('a[id="Ribbon.Document.All.NewDocument.Menu.ContentTypes.0-Menu32"]').parents('li').css("display", "none");
$('a[id="Ribbon.Document.All.NewDocument.Menu.ContentTypes.5-Menu32"]').parents('li').css("display", "none");
}
if(documentSetTitle.indexOf("IT") > -1)
{
$('a[id="Ribbon.Document.All.NewDocument.Menu.ContentTypes.0-Menu32"]').parents('li').css("display", "");
$('a[id="Ribbon.Document.All.NewDocument.Menu.ContentTypes.5-Menu32"]').parents('li').css("display", "none");
$('a[id="Ribbon.Document.All.NewDocument.Menu.ContentTypes.1-Menu32"]').parents('li').css("display", "none");
}
if(documentSetTitle.indexOf("Operations") > -1)
{
$('a[id="Ribbon.Document.All.NewDocument.Menu.ContentTypes.5-Menu32"]').parents('li').css("display", "");
$('a[id="Ribbon.Document.All.NewDocument.Menu.ContentTypes.1-Menu32"]').parents('li').css("display", "none");
$('a[id="Ribbon.Document.All.NewDocument.Menu.ContentTypes.0-Menu32"]').parents('li').css("display", "none");
}
});
}
</script>