Thursday, October 29, 2015

Monthly View Webpart with recurring events in SharePoint Calendar List

Development Steps 

Required JS
<!-- Reference jQuery on the Google CDN -->
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<!-- Reference SPServices on cdnjs (Cloudflare) -->
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js"></script>
<script type="text/javascript">
CAML Query
CAML query for Get current month events from Calendar List
CAMLQuery: "<Query>" +
            "<Where>" +
                "<DateRangesOverlap>" +
                    "<FieldRef Name='EventDate' />" +
                    "<FieldRef Name='EndDate' />" +
                    "<FieldRef Name='RecurrenceID' />" +
                    "<Value Type='DateTime'>" +
                        "<Month />" +
                    "</Value>" +
                "</DateRangesOverlap>" +
            "</Where>" +
            "<OrderBy>" +
                "<FieldRef Name='EventDate' />" +
            "</OrderBy>" +
        "</Query>",
    CAMLQueryOptions: "<QueryOptions>" +
            "<CalendarDate>" + startDate + "</CalendarDate>" +
            "<RecurrencePatternXMLVersion>v3</RecurrencePatternXMLVersion>" +
            "<ExpandRecurrence>TRUE</ExpandRecurrence>" +
        "</QueryOptions>",

Call SPServices
·         Using SPServices we can get items form Calendar list
·         We have to apply the above CAML query while get items from list
·         Based on list we will generate the table which has event info
·         Add the hyperlink for view full calendar view
<a
href="JavaScript:var options=SP.UI.$create_DialogOptions();
options.url='https://collaboration/sites/ENF/MicroCap/Lists/Calendar/calendar.aspx';
options.title = 'Monthly Calendar';
options.height = 500;
void(SP.UI.ModalDialog.showModalDialog(options))">Monthly View</a>

Implementation
Create CurrentMonthlyView.html which has the above info SPSevices call and place this into style libray
Create content editor webpart into home page and add the reference of CurrentMonthlyView.html file into it.

Verification Steps


·         Check display meeting events are associated to current month or not

Replace Text with Images in SharePoint List View using jQuery

“Project status” column is a lookup column and can contain the following values:
  • Good
  • Attention
  • Critical
I decided to use jQuery to do this. This is what I’ve come up with:
$('table[summary="Projects "] tbody tr td:nth-child(5)').each(function () {
if ($(this).find(">:first-child").text() == "Attention") {
$(this).html('<img alt="" src="/Images1/Cloud.png" width="24px" height="24px" />');
$(this).css("text-align", "center");
}
});

$('table[summary="Projects "] tbody tr td:nth-child(5)').each(function () {
if ($(this).find(">:first-child").text() == "Good") {
$(this).html('<img alt="" src="/Images1/Cloud-Sun.png" width="24px" height="24px" />');
$(this).css("text-align", "center");
}
});

$('table[summary="Projects "] tbody tr td:nth-child(5)').each(function () {
if ($(this).find(">:first-child").text() == "Critical") {
$(this).html('<img alt="" src="/Images1/Cloud-Thunder.png" width="24px" height="24px" />');
$(this).css("text-align", "center");
}
});

Ref Link : http://www.sharepointusecases.com/2014/04/replacing-strings-icons-list-view-jquery-sharepoint-2010/

Tuesday, October 20, 2015

CamlJs-Console Extension is available from Chrome Web Store.

Extension is available from Chrome Web Store.
Alternatively, you can install it manually from the source code.

  1. Download the source code archive from GitHub and unpack it to some folder
  2. Check the "Developer mode" checkbox on the extensions page
  3. Click [Load unpacked extension...] button
  4. Select folder with camljs-console source code
Ref : https://github.com/andrei-markeev/camljs-console

Sunday, October 18, 2015

Delete webpart from SharePoint Page using Powershell script


$mySiteTempURL = "http://contoso.com/"            
$siteUrl = $mySiteTempURL
$spWeb = Get-SPWeb $siteUrl -ErrorAction Stop

#Declare the absolute path to the SharePoint page
$pagePath = "/default.aspx"
$pageUrl = $siteUrl + $pagePath
write-host "Processing site: ", $siteUrl
write-host "Processing page: ", $pageUrl
#Initialise the Web part manager for the specified profile page.
$spWebPartManager = $spWeb.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
#List all the Webparts in the specified page
#foreach ($webpart in $spWebPartManager.WebParts)
#{
#    write-host $siteUrl +": Existing Web part - " + $webpart.Title + " : " + $webpart.ID
#}
#Remove the Share Documents Web part from that page
foreach ($webpart in ($spWebPartManager.WebParts | Where-Object {$_.Title -eq "Colleagues"}))
{
   write-host $siteUrl +": Existing Web part - " + $webpart.Title + " : " + $webpart.ID
   $webpart1 = $webpart
   break;
}

#Delete the existing webpart
$spWebPartManager.DeleteWebPart($spWebPartManager.WebParts[$webpart1.ID])
write-host "Deleted the existing Shared Document web part."
$spWeb.Dispose()

Update profile picture in SharePoint Online by using SharePoint hosted app, via JavaScript or jQuery

 <input id="uploadInput" type="file" />

 var fileInput = $('#uploadInput');

        for (var i = 0; i < fileInput[0].files.length; i++) {
            var file = fileInput[0].files[i];
            processprofilepic(file, '');
        }

        function processprofilepic(fileInput) {
            var reader = new FileReader();
            reader.onload = function (result) {
                var fileName = '',
                 libraryName = '',
                 fileData = '';

                var byteArray = new Uint8Array(result.target.result)
                for (var i = 0; i < byteArray.byteLength; i++) {
                    fileData += String.fromCharCode(byteArray[i])
                }

                // once we have the file perform the actual upload
                console.log("filename "+fileName);
                setprofilepic(fileData);

            };
            reader.readAsArrayBuffer(fileInput);
        }


        function setprofilepic(fileData) {


            url = shptService.appWebUrl + "/_api/SP.UserProfiles.PeopleManager/SetMyProfilePicture";


            // use the request executor (cross domain library) to perform the upload
            var reqExecutor = new SP.RequestExecutor(shptService.appWebUrl);
            reqExecutor.executeAsync({
                url: url,
                method: "POST",
                headers: {
                    "Accept": "application/json; odata=verbose",
                    "X-RequestDigest": fDigest
                },
                contentType: "application/json;odata=verbose",
                binaryStringRequestBody: true,
                body: fileData,
                success: function (x, y, z) {
                    alert("Success! Your file was uploaded to SharePoint.");
                },
                error: function (x, y, z) {
                    alert("Oooooops... it looks like something went wrong uploading your file.");
                }
            });
        }

Friday, October 16, 2015

Delete Field from SharePoint List using poweshell

#Load SharePoint User Profile assemblies
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.UserProfiles") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.PowerShell") | out-null
Add-PSSnapin Microsoft.Sharepoint.Powershell -ErrorAction:SilentlyContinue

#Global variables
$webUrl = "http://contoso:1515/"
#List Name
$ListName = "PollQuestions"
# Deleted Field Internal Name
$fieldName = "Test"

$spWeb = Get-SPWeb -Identity $webUrl
$list = $spWeb.Lists[$ListName]
$listFields = $list.Fields
$listFields.Delete($fieldName);
$list.Update();

Move Documents with version one site collection to another site collection



string sourceSiteUrl = "http://contoso:100/doccntr/Docs/";
            string destSiteUrl = "http://contoso:100/sites/Archive/";
            string srcUrl = "http://contoso:100/doccntr/Docs/Design%20history.txt";

            using (SPSite siteSrc = new SPSite(sourceSiteUrl))
            using (SPSite siteDst = new SPSite(destSiteUrl))
            using (SPWeb webSrc = siteSrc.OpenWeb())
            using (SPWeb webDst = siteDst.OpenWeb())
            {
               
                SPFile fileSource = webSrc.GetFile(srcUrl);   //itmSource.File;

                //Get destination Lib instance
                SPList libDest = webDst.Lists[fileSource.Item.ParentList.Title];

                /*Here we'll get the created by and created on values from the source document.*/
                SPUser userCreatedBy = fileSource.Author;
                SPUser userModifiedBy = fileSource.ModifiedBy;
                /*Note we need to convert the "TimeCreated" property to local time as it's stored in the database as GMT.*/
                DateTime dateCreatedOn = fileSource.TimeCreated.ToLocalTime();
                //Get the versions
                int countVersions = fileSource.Versions.Count;
                /*This is a zero based array and so normally you'd use the < not <= but we need to get the current version too which is not in the SPFileVersionCollection so we're going to count one higher to accomplish that.*/
                for (int i = 0; i <= countVersions; i++)
                {
                    Console.Write("Item Vesrion no :  " + i);
                    Hashtable hashSourceProp;
                    Stream streamFile;
                    //SPUser userModifiedBy;
                    DateTime dateModifiedOn;
                    string strVerComment = "";
                    bool bolMajorVer = false;
                    if (i < countVersions)
                    {
                        /*This section captures all the versions of the document and gathers the properties we need to add to the SPFileCollection.  Note we're getting the modified information and the comments seperately as well as checking if the version is a major version (more on that later).  I'm also getting a stream object to the file which is more efficient than getting a byte array for large files but you could obviously do that as well.  Again note I'm converting the created time to local time.*/
                        SPFileVersion fileSourceVer = fileSource.Versions[i];
                        hashSourceProp = fileSourceVer.Properties;
                        userModifiedBy = (i == 0) ? userCreatedBy : fileSource.Author;
                        dateModifiedOn = fileSourceVer.Created.ToLocalTime();
                        strVerComment = fileSourceVer.CheckInComment;
                        bolMajorVer = fileSourceVer.VersionLabel.EndsWith(".0") ? true : false;
                        streamFile = fileSourceVer.OpenBinaryStream();
                    }
                    else
                    {
                        /*Here I'm getting the information for the current version.  Unlike in SPFileVersion when I get the modified date from SPFile it's already in local time.*/
                        userModifiedBy = fileSource.ModifiedBy;
                        dateModifiedOn = fileSource.TimeLastModified;
                        hashSourceProp = fileSource.Properties;
                        strVerComment = fileSource.CheckInComment;
                        bolMajorVer = fileSource.MinorVersion == 0 ? true : false;
                        streamFile = fileSource.OpenBinaryStream();
                    }
                    string urlDestFile = fileSource.Url.ToString();
                    /*Here I'm using the overloaded Add method to add the file to the SPFileCollection.  Even though this overload takes the created and modified dates for some reason they aren't visible in the SharePoint UI version history which shows the date/time the file was added instead, however if this were a Microsoft Word document and I opened it in Word 2010 and looked at the version history it would all be reflective of the values passed to this Add method.  I'm voting for defect but there could just be something I'm missing.*/
                    SPFile fileDest = libDest.RootFolder.Files.Add(
                                urlDestFile,
                                streamFile,
                                hashSourceProp,
                                libDest.ParentWeb.EnsureUser(userCreatedBy.LoginName),
                                libDest.ParentWeb.EnsureUser(userModifiedBy.LoginName),
                                dateCreatedOn,
                                dateModifiedOn,
                                strVerComment,
                                true);
                    if (bolMajorVer)
                    {
                        /*Here we're checking if this is a major version and calling the publish method, passing in the check-in comments.  Oddly when the publish method is called the passed created and modified dates are displayed in the SharePoint UI properly without further adjustment.*/
                        fileDest.Publish(strVerComment);
                        fileDest.Approve(strVerComment); ;
                    }
                    else
                    {
                        /*Setting the created and modified dates in the SPListItem which corrects the display in the SharePoint UI version history for the draft versions.*/
                        SPListItem itmNewVersion = fileDest.Item;
                        itmNewVersion["Created"] = dateCreatedOn;
                        itmNewVersion["Modified"] = dateModifiedOn;
                        itmNewVersion.UpdateOverwriteVersion();
                    }
                }

            }

Upload files to SharePoint site using PowerShell

Steps to upload files from file share location to sharepoint library with relevant metadata

$webUrl  = "http://contoso.com";  http://contoso.com Replace with your Site Url

$docLibraryName = "Documents"; Documents - Replace with your library name

$docFolderName =  "SharePoint"; SharePoint - Replace with Folder name if you have sub folders in Library

$docNumber = "SeachDocument.docx"; SeachDocument.docx - Replace with File name which you will have in file share location

try
{

$inputRowCollection = Get-ChildItem $DocumentsRepositoryPath -Recurse | Where-Object {$_.Name -like $docNumber+ "*"}

if($inputRowCollection.Count -eq 0)
{
$row.IsMigrated = "File Missing"
}

if($inputRowCollection.Count -eq 1)
{
$row.IsMigrated = UploadFileInLibrary $webUrl  $docLibraryName $inputRowCollection.PSPath $docFolderName
}
elseif($inputRowCollection.Count -ge 1)
{
$row.IsMigrated = "Duplicate Documents"
}
}          
catch          
{
Write-Host "File Path : ($inputRowCollection.PSPath) - Error ($documentData): "$_.Exception -f Red;
Write-Output "File Path : ($inputRowCollection.PSPath) - Error ($documentData): "$_.Exception >> $ExceptionLogFile
$logData = $logData + "`tNA`t" + $_.Exception + "`tFail`tNA"  
}

#Function to upload Document into SharePoint library
function UploadFileInLibrary          
{
[CmdletBinding()]          
Param(          
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]          
[string]$webUrl,          
[Parameter(Mandatory=$true)]          
[string]$DocLibName,          
[Parameter(Mandatory=$true)]          
[string]$FilePath,            
[Parameter(Mandatory=$false)]          
[string]$FolderName
)              
       
 try
 {

#region Code for Migration
           
$spWeb = Get-SPWeb -Identity $webUrl

$List = $spWeb.Lists[$DocLibName]          
$folder = $List.RootFolder          
if($FolderName -ne "")
{
$folder = $list.RootFolder.SubFolders[$FolderName]
}
$FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)          
$File= Get-ChildItem $FilePath  
$fileExtension = ([System.IO.FileInfo] (Get-Item $File.FullName)).Extension
[Microsoft.SharePoint.SPFile]$spFile = $spWeb.GetFile($folder.Url + "/" + $docNumber+$fileExtension)          
$flagConfirm = 'y'          
if($spFile.Exists -eq $true)          
{          
#    $flagConfirm = Read-Host "File $FileName already exists in library $DocLibName, do you    want to upload a new version(y/n)?"          
return "Document Exist."
}          
         
if ($flagConfirm -eq 'y' -or $flagConfirm -eq 'Y')          
{
$spWeb.AllowUnsafeUpdates = $true;
 
$fileStream = ([System.IO.FileInfo] (Get-Item $File.FullName)).OpenRead()
$fileExtension = ([System.IO.FileInfo] (Get-Item $File.FullName)).Extension
   #Add file          
   write-host -NoNewLine -f yellow "Copying file " $File.Name " to " $folder.ServerRelativeUrl "..."          
   [Microsoft.SharePoint.SPFile]$spFile = $folder.Files.Add($folder.Url + "/" + $docNumber+$fileExtension, [System.IO.Stream]$fileStream, $true)          
   write-host -f Green "...Success!"          
   #Close file stream          
   $fileStream.Close()          
   write-host -NoNewLine -f yellow "Update file properties " $spFile.Name "..."

#Check the whether exists or not in site
$docContentType = $docContentType

if($docContentType -eq $IMS)
{
$docContentType = $List.ContentTypes[$docContentType]
$spFile.Item["ContentTypeId"] = $docContentType.Id;
$spFile.Item["Content Type"] = $docContentType.Name;
$spFile.Item["Name"] = $docNumber
$spFile.Item["Title"] = $docTitle  
$spFile.Item.Update()          
write-host -f Green "...Success!"
$spFile.CheckIn("Checked In By Administrator");
            Write-Host "$($spFile.Name) Checked In" -ForeGroundColor Green
}

$spWeb.AllowUnsafeUpdates = $false;
}
       
         
return "Uploaded";

#endregion

}
catch
{
Write-Host "File Path : ($inputRowCollection.PSPath) - Error in DocumentsMigration method : "$_.Exception -f Red;
Write-Output "File Path : ($inputRowCollection.PSPath) - Error in DocumentsMigration method: "$_.Exception >> $ExceptionLogFile
return "Error while uploading";
}
}

Check list for Designing and Implementing of SharePoint

Governance and Culture Planning Points
  • Can users access information via Web folder clients?
  • Can users create and manage their own Web sites?
  • Is the administration of mission critical data distributed?
  • How are records and documents described using metadata and is that consistent across departments, divisions and agencies?
  • Have you trained end-users on how to administrate sites before they need to manage them?
  • Have you decided on who will assign users and permissions in SharePoint?
  • Have you decided on who will create and approve content for portals?
  • Have you decide on who will be able to create new sites?
  • Have you decided on who will be able to publish content to web sites?
  • Have you decided on who will be able to customise sites?
Naming Conventions
  • Database Names?
  • URLs (host headers)?
  • Stand-alone site collection URLs?
  • Managed path names and if so what are they?
  • Document Library names?
  • Active Directory SharePoint accounts?
  • Content source names?
  • Scope names?
  • Server names?
  • Web application names?
  • Web application folder names?
  • E-mail enabled list names and aliases?
  • Have you ensured that names are kept relatively short, easy to remember and unique to avoid conflicts or confusion. Note that URL lengths including filename as are restricted to 260 characters
Extranet and Security Planning Needs
  • Have you considered and anticipated password and account support for nonemployees who access extranet sites?
  • Are there groups you need to deny at the Web application level?
  • Are there unique permission levels you need to apply to individuals or groups at the web policy level?
  • Are there unique or different authentication mechanisms you need to implement for extranet users?
  • Do you need additional Shared Service Providers to associate with your extranet Web applications?
Search and Indexing Planning Issues
  • Have you structured the content that needs to be indexed in terms of priority?
  • What information do you need to crawl and have placed in your index?
  • What content sources are needed to adequately crawl the information that needs to be placed in your index?
  • What will be the Full and incremental crawl schedules for each content source?
  • Do you have adequate server hardware to crawl all the content sources in your current schedule?
  • Do you have adequate bandwidth available between your index and your content sources?
  • For each content source, what rules, crawler settings and crawler impact rules are needed?
  • Who will troubleshoot failed crawls or information that does not appear in the index?
  • Who will evaluate the content sources so that the crawl criteria are configured efficiently?
  • What will be your search scope topology?
  • Do you need additional iFilters?
  • Do you need additional Protocol Handlers?
  • Do you need to add File Types to SharePoint?
  • Do you need to add icons to SharePoint?
  • Do you need to use OCR features?
  • Do you need special accounts to crawl certain content sources?
  • Do you need to create any Best Bets (2007 / 2010) / (Promoted Results 2013)?
  • Do you need to group any Crawled properties?
  • Do you need any special Server Name Mappings?
  • Have you established primary, secondary, tertiary and demoted sites for Relevance?
  • Have you ensured disks are optimised for Search?

Disaster Recovery Planning
  • Have you set deleted retention policies for the two-stage recycle bin in document libraries?
  • What are your plans for single site and site collection recovery?
  • What are your plans for server recovery?
  • What are your plans for farm recovery?
  • What are your plans for data-centre failover?

Staffing Needs
  • Do you have at least one architect who knows SharePoint at a granular level?
  • Do you have at least one developer who knows customisation at a granular level?
  • Have you provided excellent training materials and trainers for end user education?
  • For large indexing environments, have you considered a FTE for search and indexing?
  • To ensure robust taxonomy implementations, have you considered 1-N FTEs for content types?
  • To ensure robust customised scenarios and/or complex workflow, have you considered 1-N FTEs for application and workflow development?

Personalisation
  • Have you defined what Active Directory attributes you want to import from Active Directory to help build your profiles and audiences?
  • Have you defined what profile attributes you want to populate for the user’s profile?
  • What is the profile import schedule?
  • What is the Audience compilation schedule?

Document Library Planning Issues
  • How will you educate users to create document libraries based on a naming convention you propagate?
  • Where will you enable the require document check out for editing option?
  • Have you ensured that the number of documents in a view or folder are within best practice thresholds?

SharePoint Capacity Planning, Reporting and Monitoring
  • Have you run performance counters to establish a baseline of performance counters?
  • Have you accurately mapped your Web applications to your application pools?
  • Have you planned the managed paths for important web applications?
  • Have you estimated data requirements for SharePoint, ensuring you have enough disk space in your topology to accomodate growth?
  • Set database size limits by implementing Site Quotas plus Site Limits on the database
  • Have you established monitoring at the server, IIS, SharePoint and ASP levels and know what acceptable and unacceptable results are for each counter?
  • Have you considered using external tools for monitoring SharePoint and if so what are they?
  • Have you defined scheduled downtime periods for maintenance?
  • Have you communicated the procedure to report unscheduled downtimes?
  • Have you considered server redundancy, SQL clustering, Imaging and Windows Load Balancing if you need high availability on one or more SharePoint services?
Plan site quota templates
  • Have you defined auditing reports at the farm and site collection levels?
  • Have you established storage usage reports?
  • Have you established required activity reports?
  • Have you established SLAs for performance?

Branding and Consistency
  • Will you avoid making changes to site definitions when they can be made with features?
  • How will unique features be created?
  • What are the documented processes from which to create workflows?
  • What master pages will be needed for consistent navigation and branding?
  • What content types will be needed consistent metadata, site templates, and workflows across documents?
  • What rollup features, assemblies, and changes in solution deployment packages are needed?
Criteria for creating a web application

  • Does the group have unique security needs?
  • Does the group have unique information consumption needs?
  • Does the group have unique taxonomy needs?
  • Does the group have unique collaboration needs?
  • Does the group have personnel they can assign to site collection management?
  • Is creating the web application the right thing to do politically?
  • Does it make sense to create the new Web application?

How to Migrate SharePoint 2007 to Office 365 Standard Using Native Web Service and CSOM

This post talks about:
1)      How to migrate from SharePoint 2007 to Office 365 Standard with native web service and CSOM

2)      Issues you would face during the migration and alternatives

http://blogs.msdn.com/b/himanshukumar/archive/2012/05/22/how-to-migrate-sharepoint-2007-to-office-365-standard-using-native-web-service-and-csom.aspx

SharePoint – Calculation Column Cheat Sheet


Extracts one named parameter from the QueryString (URL)

Use this below function to get values from Query string

URL: http://domainname.com/page.aspx?parameter1=xxx&parameter2=yyy

function getQueryStringParameter(paramToRetrieve) {
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] == paramToRetrieve)
        return singleParam[1];
}

var value=getQueryStringParameter('parameter1');

Even Microsoft duplicates functionality:

(SP.init.js) SP.ScriptHelpers.getUrlQueryPairs

Even more SharePoint code that does the same
 var QS = SP.ScriptHelpers.getUrlQueryPairs(document.location.href)
 var value=QS['parameter1'];

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;
            }
        }
    }

}