Tuesday 9 October 2018

Office 365 - Current login User Details

I generally needs to go to google each time to get current login User details for Office 365. Here is post for general idea how you can get the details in Office 365:

Approach 1 - Use Graph API

If you want to use Graph api, follow below steps,

  • go to below URL
    https://developer.microsoft.com/en-us/graph/graph-explorer
  • Sign in with your O365 details. 

  • Once you are logged in, click on "my profile" and it will get all your details.

How to use this in code,  I will write another blog for same.


Approach 2 - Use browser Console


Some of the properties are available using "_spPageContextInfo". Like user display name, user email address and user login name.

  • user display name - _spPageContextInfo.userDisplayName
  • user email - _spPageContextInfo.userEmail
  • user login name - _spPageContextInfo.userLoginName
  • user Id - _spPageContextInfo.userId
Approach 3 - Use Rest API (Ajax request)

To get other details you need to use below ajax request:

function getCurrUsrImg(){

var siteurl = _spPageContextInfo.webAbsoluteUrl;
        Var usrId = _spPageContextInfo.userId;
var userURL = siteurl + "/_api/web/SiteUserInfoList/Items('"+usrId+"')";
$.ajax({
url: userURL,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
async: true,
success: function (data) {
getCurrUserIMGSuccess(data.d);
},
error: function (data) {
console.log("Error: "+ data);
}
});
}

function getCurrUserIMGSuccess(res){
//console.log("llll");

var uHTMLIMG = "";
if(res.Picture != null){
uHTMLIMG = "<img src='"+res.Picture["Url"]+"'>";
}

$('#divCuserimg').html("");
$('#divCuserimg').html(uHTMLIMG);
}

You can get below list of fields with this call:

  • Id
  • ContentTypeId
  • Title (full name - love thakker)
  • Name (domain name - i:0#.f|membership|love.thakker)
  • EMail
  • MobilePhone
  • SipAddress
  • Deleted (true / false)
  • Picture ( look up - expand with description and URL)       
  • Department       
  • JobTitle        
  • FirstName        
  • LastName
  • WorkPhone      
  • UserName        
  • GUID   
  • Modified      
  • Created       
  • AuthorId
  • EditorId

Approach 4 - Use People Manager api (Ajax request)
If you want even more details than this then you can use below service call

$.ajax({  
  
            url: _spPageContextInfo.siteAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetMyProperties",  
            headers: { Accept: "application/json;odata=verbose" },  
            success: function (data) {  
                try {  
                    //Get properties from user profile Json response  
                    userDisplayName = data.d.DisplayName;  
                    AccountName = data.d.AccountName;  
                    var properties = data.d.UserProfileProperties.results;  
                    for (var i = 0; i < properties.length; i++) {  

                        var property = properties[i];  
                        if (property.Key == "Office") {  
location = property.Value;
                        }  

                    }
                } catch (err2) {  
                  console.log('error');
                }  
            },  
            error: function (jQxhr, errorCode, errorThrown) {  
                alert(errorThrown);  
            }  
        });  
        

}

Below is list of columns that you will get when you use this:
  • AccountName
  • DisplayName
  • Email
  • ExtendedManagers
  • ExtendedReports
  • Peers
  • PersonalSiteHostUrl (-my.sharepoint.com)
  • PersonalUrl (my.sharepoint.com/personal/love_thakker)
  • PictureUrl
  • Title
  • UserProfileProperties
    • UserProfile_GUID
    • SID
    • ADGuid
    • AccountName
    • FirstName
    • SPS-PhoneticFirstName
    • LastName
    • SPS-PhoneticLastName
    • PreferredName
    • SPS-PhoneticDisplayName
    • WorkPhone
    • Department
    • Title
    • SPS-Department
    • Manager
    • AboutMe
    • PersonalSpace
    • PictureURL
    • UserName
    • QuickLinks
    • WebSite
    • PublicSiteRedirect
    • SPS-JobTitle
    • SPS-DataSource
    • SPS-MemberOf
    • SPS-Dotted-line
    • SPS-Peers
    • SPS-Responsibility
    • SPS-SipAddress
    • SPS-MySiteUpgrade
    • SPS-DontSuggestList
    • SPS-ProxyAddresses
    • SPS-HireDate
    • SPS-DisplayOrder
    • SPS-ClaimID
    • SPS-ClaimProviderID
    • SPS-LastColleagueAdded
    • SPS-OWAUrl
    • SPS-ResourceSID
    • SPS-ResourceAccountName
    • SPS-MasterAccountName
    • SPS-UserPrincipalName
    • SPS-O15FirstRunExperience
    • SPS-PersonalSiteInstantiationState
    • SPS-DistinguishedName
    • SPS-SourceObjectDN
    • SPS-LastKeywordAdded
    • SPS-ClaimProviderType
    • SPS-SavedAccountName
    • SPS-SavedSID
    • SPS-ObjectExists


Thursday 13 September 2018

Multi line column data Format issue in Document Library SharePoint

Recently, we need to show data from Document library to a classic view page. We get rest call. Get data. Display on page. Task done. Easy right? No. There was a multi line column which was showing data as row text. Also that column has 255 character limit. How can this be?

Analysis:
We got a tech net page which says multi line is not same in list and library. So we won't get rich text or enhance rich text option in that. Only plain text available.

Reference - https://social.msdn.microsoft.com/Forums/office/en-US/67a70245-cd03-48e1-b0fa-71bbb6a7744d/is-enhanced-rich-text-column-supported-by-document-library?forum=sharepointcustomizationlegacy

Solution:

So there were two issue. And below are solution for same:


  • Getting 255 character limit.
So open column and set settings to allow unlimited text. It will fix this issue.




  • Show multi line data as formatted.
For this you need to use "<Pre>"tag. It will show data in same way the text is entered in column.

Code sample:



$(document).ready(function(){
$.ajax({     
url:_spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getByTitle('Newsletter')/items?$select=DocIcon,EncodedAbsUrl,FileLeafRef,Editor/Title,Highlighted_x0020_Content&$expand=Editor&$orderby=FileLeafRef desc",
    type: "GET",  
    headers: {  
        "accept": "application/json;odata=verbose",  
        "content-Type": "application/json;odata=verbose"  
    },  
    success: function(data) {  
var html="";
for(i=0;i<data.d.results.length;i++){
var currentData = data.d.results[i];
var previewPath = _spPageContextInfo.webAbsoluteUrl +"/_layouts/15/getpreview.ashx?path="+ currentData.EncodedAbsUrl;
var highlightedContent = currentData.Highlighted_x0020_Content!= null ? currentData.Highlighted_x0020_Content:"";
var docType = currentData.DocIcon;
var imgdoc;
        html+="<div class='parentDiv'><div class='titleDiv'>"+currentData.FileLeafRef+"</div><div class='editDiv'></div><div class='contentDiv'><pre>"+highlightedContent +  "</pre></div></div>";
}
$("#NewsLetter").html(html);
    },  
    error: function(error) {  
        console.log(JSON.stringify(error));  
    }  
}); 
})

Friday 24 August 2018

List ribbon not load issue in Office 365

Issue:
Recently, we have a strange issue. The list was not showing ribbon tabs default. There are many reasons I found for this behavior, like

  • Permission issue - we have site collection access
  • custom script to stop ribbon load - we have checked there was no custom coding done.

Then we found a blog stating that even if you add any custom webpart in list / library page, the ribbon lost its focus from main webpart. So it won't show. Andd it was true. we have added a legal text in our list heading using content editor webpart.

Solution:

So what is solution to bring it back? Below is code sample that we added in our page for loading ribbon tab on page load.

Code:
window.onload = function(){
  var elem = document.getElementById("MSOZoneCell_WebPartWPQ2");
  if (elem != null) {
      var dummyevent = new Array();
      dummyevent["target"] = elem;
      dummyevent["srcElement"] = elem;
      elem.parentNode.click();
      WpClick(dummyevent);
   }
//code to click browse button
   document.getElementsByClassName("ms-cui-tt-span")[0].click();
   }

Wednesday 8 August 2018

HTML 5 Video tag

As always, I was working on a project which contains bugs. but this time a video was issue. Issue was video was playing in most of browser but not in Internet Explorer. As a part of analysis I found that client was using some third party browser to render video.

So I checked alternative for that. And what I get is HTML 5 video tag. Below is code that I used for testing:

<html>
<head>
</head>
<body>
<video controls autoplay loop>
  <source src="https://www.w3schools.com/tags/movie.mp4" type="video/m4v">
Your browser does not support the video tag.
</video>
</body>
</html>

Few things that it provides is very good. for example, below attributes

  • Autoplay - if you add this in video tag, video will start automatically. 
  • Loop - Provides a way to play video continuously.
You can check other attributes as well in reference link below.

Our client was using "M4a" format. But video tag supports below formats only. So we change our video format in "MP4"
  • MP4 - This only is supported in IE, Chrome and Firefox.
  • WebM
  • Ogg

Note: The video tag is not supported in Internet Explorer 8 and earlier versions.

As it solved my problem, I thought its worth sharing for my future reference and it my help you.

Reference:
https://www.w3schools.com/tags/tag_video.asp

Thursday 21 June 2018

SharePoint List useful details

Recently get change to go back to development and done some basic level of errors. So here is my knowledge for list level that I want to share:

I have a library with internal name "LiteracyResources" and the display name was updated to "Literacy Resources" (a space between two words). I need to bind documents to a grid and click on name I need to download it. Simple requirement.

The issue I face was when I try to get list I need to use name with space. And If I want to get any file url for download, I need to create it and that should use internal name of the list. Otherwise your download url won't work.

So to get internal name of list, I use "list.RootFolder.Name".

below is the code that I use for this:

Code:

SPList resourcelist = null;

 using (SPSite siteCol = new SPSite(SPContext.Current.Site.Url))
                {
                    SPWeb web = siteCol.RootWeb;
                    {
                        SPList list = web.Lists.TryGetList(Constants.LibNameLiteracy); // Here we need to //use library name with space 
                     
                        SPListItemCollection items = list.GetItems();
                        if (items.Count > 0)
                        {
                            dt = items.GetDataTable();
                            dt.Columns.Add(Constants.ColNameDocURL, typeof(string));
                            for (int itemcount = 0; itemcount < dt.Rows.Count; itemcount++)
                            {
                                if (web.Url.EndsWith("/"))
{ // here we use internal name 
                                    dt.Rows[itemcount][Constants.ColNameDocURL] = web.Url + list.RootFolder.Name + "/" + Convert.ToString(dt.Rows[itemcount][Constants.ColNameFileLeafRef]);
{
                                else {
                                    dt.Rows[itemcount][Constants.ColNameDocURL] = web.Url + "/" + list.RootFolder.Name + "/" + Convert.ToString(dt.Rows[itemcount][Constants.ColNameFileLeafRef]);
}
                                dt.AcceptChanges();
                            }
                        }
                    }
                }

                allYearsGrid.DataSource = dt;
                allYearsGrid.DataBind(); 

Tuesday 15 May 2018

Hidden Site Collections in SharePoint Online

Recently I was given a task to find site collections that were not visible in admin center but actually users were using them, and the it manager didn't have access on them.

I found two scenarios where this situation is possible. So here is my analysis on them:

  • Scenario I - ContentTypeHub
SharePoint online has a hidden site collection named "contenttypehub" (URL - /teams/contentTypeHub). You can host your content types here. They will be available in all the site collections. 
  • Scenario II- SharePoint Group Sites
If you have created Office365 groups, you will have a separate site collection of each group created where group members can share & collaborate. 

Thursday 3 May 2018

Nintex Form "RegisterAfterReady" load event

Few more tips on Nintex forms. If you have an action that you want to occur before nintex load page, what are the options? If you have asked me yesterday, I would have easily say document ready event. But today I have few more option. 

Here are the options:

  • NWF.FormFiller.Events.RegisterBeforeReady
  • NWF.FormFiller.Events.RegisterAfterReady
  • NWF$(document).ready
Well we all know 3rd option. Let me give some tips on 2nd option. We have a requirement that whenever we open any item, we need to show user what to do in the form. As the form was submitted at different level by approval process, we need to show different guide for different user. 

Document ready event was firing so quickly that we were not able to get all the information we need from form. So we used RegisterAfterReady event. so once the form is ready with our data filled in that, we can open a dialog showing our own page.

below is solution that we used:

Solution:

ShowInitialPop() {
    var widthValue = 600;    
    var options = {
        title: "",
        width: widthValue,
        height: 520,
        url: sr_siteUrl + "/SitePages/StartPopUp.aspx?IsDlg=1"
    };

    SP.UI.ModalDialog.showModalDialog(options);
    NWF$("#dialogTitleSpan").hide();
    NWF$("#dlgTitleBtns").hide();
}

NWF.FormFiller.Events.RegisterAfterReady(function () {
// your code
    ShowInitialPop();
    
});
Reference:

https://help.nintex.com/en-us/sdks/sdk2013/FormSDK/Topics/SDK_NF_CON_NF_Events.htm

Update item in Nintex form using SPService code

I am working on few forms developed in Nintex and need to do some CRUD operations. Here is sample code for update item.

Prerequisite:

You need to provide reference of jquery.SPServices-2014.01.NF.min.js file in your script file.

Solution:

function oData_SaveExitPendingHRO() {

//This line is used to get drop down value
    var closedStatusID = oData_GetIDFromDdl(NWF$('#' + jsCtrl_ddlClosedStatus).val());
    var closedStatus = oData_GetTextFromDdl(NWF$('#' + jsCtrl_ddlClosedStatus).val());

//This one is used to get textbox
    var actionComments = '';
if (typeof(jsCtrl_txtActionComments) != "undefined" && closedStatus !=""){
actionComments = NWF$('#' + jsCtrl_txtActionComments).val();
}

//This one is used to get date field. Then we convert it our required format
    var effectiveDate1 = NWF$('#' + jsCtrl_dtpEffectiveDate).val();
if (typeof(effectiveDate1) != "undefined" && effectiveDate1 != "empty") {effectiveDate1 = oData_ConvertToISOString(effectiveDate1);}

//This one is used to get people picker field.
var varHROSpecialist = NWF$('#' + jsCtrl_pickerHROSpecialist).val();

//This one is used to get id.
    var itemID = NWF$('#' + jsCtrl_txtID).val();

    var currentUserAccountName = NWF$('#' + jsCtrl_txtCurrentUserAccount).val();

// Special call to convert special character in html code
actionComments = encodeXMLSpecialChars(actionComments);

    if (!oData_IsNullOrEmpty(itemID)) {

        //Update Action Closure Section
        NWF$().SPServices({
            operation: 'UpdateListItems',
            async: false,
            listName: 'ListName',
            updates: '<Batch OnError="Continue">' +
            '<Method ID="1" Cmd="Update">' +
            '<Field Name="ID">' + itemID + '</Field>' +
            '<Field Name="ClosedStatus">' + closedStatus + '</Field>' +
            '<Field Name="ClosedStatusID">' + closedStatusID + '</Field>' +
'<Field Name="ActionComments">' + actionComments + '</Field>' +
'<Field Name="EffectiveDate">' + effectiveDate1 + '</Field>' +
'<Field Name="HROSpecialist">' + oData_ParsePeoplePickerValue(varHROSpecialist) + '</Field>' +
            '</Method>' +
            '</Batch>',
            completefunc: function (xData, Status) {
                var lowerStatus = Status.toLowerCase();
                if (lowerStatus != null && typeof (lowerStatus) != "undefined" && lowerStatus != "" && lowerStatus == "success") {                 
alert('Command success');

                    //Redirect after saving
        document.location.href = oData_siteUrl,true;
                }
                else {
                   alert('Command failure');
                }
            }
        });
       
    } else {
        alert('Error. Please contact the Administrator.');
    }
}

function oData_ConvertToISOString(eDateValue) {
    var isoDate = new Date(eDateValue);
    if (eDateValue != null && typeof (eDateValue) != "undefined" && eDateValue != "") {
        var day = isoDate.getDate();
        var mm = isoDate.getMonth() + 1;
        var yyyy = isoDate.getFullYear();
        isoDate = yyyy.toString() + "-" + ("0" + mm).slice(-2) + "-" + ("0" + day).slice(-2) + "T09:00:00Z";
    }

    return isoDate;
}

function oData_ParsePeoplePickerValue(eValue) {
    var pplValue = "";
    if (!oData_IsNullOrEmpty(eValue)) {
        pplValue = eValue.replace(";", "").replace("i:0#.w|", "-1;#");
    } else {
        pplValue = "";
    }

    return pplValue;
}


function encodeXMLSpecialChars(unsafe) {
    if (unsafe == null || typeof (unsafe) == "undefined" || unsafe == "") {
        unsafe = "";
    }

    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;");
}

Tuesday 17 April 2018

Nintex forms set dropdown value

I was working on Nintex forms and I faced a really interesting issue. I need to change default value bind to dropdown control. So easy? Not at all. Here are solution that worked for me:

If you want to set in Nintex forms or List settings -

https://ootbtutorials.com/2016/02/15/setting-field-default-values-in-nintex-forms/

If you want it dynamically changed using jquery-

https://community.nintex.com/thread/16997-how-to-set-default-value-some-option-in-drop-down-list-look-up-using-jquery-or-javascript


Monday 16 April 2018

SQL Server 2012 64 Bit installation issues

I was installing SQL server 2012 and I have to say it is not at all easy task. I got below issues and solutions:

Issue 1 - Not able to complete installation if you have visual studio 2012 / 2013 installed before.
Solution - make sure you install SQL server 2012 before installation of visual studio 2012 / 2013.
https://stackoverflow.com/questions/14162947/using-ssis-bids-with-visual-studio-2012-2013

If you have installed visual studio, the simplest way is go for SQL server 2014.


Issue 2 - No separate SQL server management studio installation.
Solution - You need to start installation again and run installation again.

Some blog will tell you to go with add feature in installation. but you need to go new installation if you are go with 64 bit.
https://stackoverflow.com/questions/11276167/how-to-install-sql-server-management-studio-2012-ssms-express

Friday 2 March 2018

How to change date format from "MM/DD/YYYY" (US) to "DD/MM/YYYY" (UK) in SharePoint?

Scenario:
As clients reside in different countries, we need to change date format as per their current use. Recently I was given task to change date format from "MM/DD/YYYY" (US) to "DD/MM/YYYY" (UK).

Note:
Generally my blog contains warning after solution. But as this one affects wide range of settings, I would prefer that you first get approval for this.

Solution:

So the simplest way to achieve this is to change regional settings and SharePoint automatically change the date format accordingly. As I have told in note section, this will change each and every date in system to selected region format. So please get approval first. It may affect other settings too. But I am still not fully got aware where else this can affect.

So follow below steps to change regional settings:


  • Log into your SharePoint Site as the Site Administrator
  • Click Site Actions then Site Settings

  • From the Site Administration section click Regional Settings

  • Select English (United Kingdom) from the Locale: drop down box.

  • Click OK.


Thursday 1 March 2018

Merge two column values using calculated column in SharePoint

Scenario:

I continuously work in SharePoint and get some experience. Today I got a task to get value of two columns and concatenate it and store it in third column. So I know I can do that using calculated column. I have heard about it. Didn't you? but how exactly it works?

Solution:

So I have google on calculated column and what I found was a hidden treasure. You can get it too by clicking reference link. Microsoft has documented each type of scenario on there. But as my part was only for concatenation of two string, I have used "&" operator in between two columns and it worked great. I have put option related my scenario below:

Column1 Column2 Formula Description (possible result)
Love Thakker =[Column1]&[Column2] Combines the two strings (LoveThakker)
Love Thakker =[Column1]&" "&[Column2] Combines the two strings, separated by a space (Love Thakker)
Love Thakker =[Column2]&", "&[Column1] Combines the two strings, separated by a comma and a space (Love, Thakker)
Love Thakker =CONCATENATE([Column2], ",", [Column1]) Combines the two strings, separated by a comma (Love,Thakker)


Reference:

As I mentioned earlier, you can go on below link and check other scenarios as well:

HTML Print Page functionality

Scenario:

We are getting some simpler task some days and we learn new things about technology or language which is always there, but we are never aware of it. We use it sometimes too but unaware how it is working until you need to develop it.

So we have a simple request that client wants print functionality in page. No big deal. JavaScript provides such functionality with simple command "window.print();". Just use below code and you are good to go:

Code:

<button onclick="window.print();">Print this page</button>


Note:

All browsers use their own way of printing. So the user experience will be different.

Reference:

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_print

Saturday 27 January 2018

Anonymous user dispalyed “authentication required” log in pop-up on downloading files

Issue:

We have a simple task recently and that was to enable anonymous access in a site. So easy right? but sometimes it happens if you are not aware how it works, it takes lot of time. Here is same scenario. As we have set up anonymous access, client uploaded some files in library and put it links on a public page. It works fine if you have edit/ full control for site. But if you are anonymous user, you are asked to login.


Solution:

As I said earlier, if you know how it works, you will be able to solve it easily. Only you need to make sure that items are published with major version. If that is done, anonymous user will be able to download files without any issue.

If you search google, you will find that you need to provide "Open item" access to items. If above solution do not solve the issue, below are links to set up open access: