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

            }