Monday, November 9, 2015

Date validation From and To using JavaScript


varFrom - ID of Form date control
varTo - ID of To date control


function isValidDate(varFrom, varTo)
 {
    var fromdate, todate, dt1, dt2, mon1, mon2, yr1, yr2, date1, date2;
    var chkFrom = document.getElementById(varFrom);
    var chkTo = document.getElementById(varTo);
    if (varFrom != null && varTo != null) {
      if (checkdate(chkFrom) != true) {
        chkFrom.value = '';
        chkFrom.focus();
        return false;
      }
      else if (checkdate(chkTo) != true) {
        chkTo.value = '';
        chkTo.focus();
        return false;
      }
      else {
        fromdate = chkFrom.value;
        todate = chkTo.value;
        date1 = new Date(fromdate);
        date2 = new Date(todate);

        if (date2 <= date1) {
          alert("To date Should be greater than From date");
          chkFrom.value = '';
          chkFrom.focus();
          return false;
        }
      }
    }
    return true;
  }

function checkdate(input)
 {
    var validformat = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/ //Basic check for format validity
    var returnval = true;
    if (input.value == '' || !validformat.test(input.value))
    {
      alert("Invalid Date Format. Please correct and submit again.")
      var returnval = false;
    }
    return returnval
  } 

Get the user information from people picker column using REST call

If you want to get the user information from the people picker column using REST call follow this one

Note: Here we have  used the expand keyword  in REST call for two people picker columns in sharepoint list

var listName = "Leave-WFH Request";
var restQuery = "LeaveCategory eq 'Holiday' and  From gt '11/03/2015' and To lt '21/03/2015'";  
 
        jQuery.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/Items?$select=Title,From,To,EmployeePhone,LeaveCategory,EmployeeLocation,EmployeeName/Title,Manager/Title&$expand=EmployeeName,Manager&$filter="+ restQuery,
            type: "GET",
            headers: { Accept: "application/json;odata=verbose" },
            success: function (data) {
}
error: function (jqXHR, textStatus, errorThrown) {
                Console.log("UpcomingEventsHomePage.js:loadEventsData:: " + textStatus);
            }
        });

If we have single column the query will be

    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/Items?$select=Title,From,To,EmployeePhone,LeaveCategory,EmployeeLocation,EmployeeName/Title&$expand=EmployeeName&$filter="+ restQuery,

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.");
                }
            });
        }