Saturday, 17 October 2015

Clear People Picker SharePoint Using JQuery

Hi, this post describes how to clear the client side people picker.

 My client side People picker is as follows:

<SharePoint:ClientPeoplePicker ID="peoplePickerProjectManager" runat="server" AllowMultipleEntities="false" Required="true" ValidationEnabled="true" />

You can place it in any .aspx page. Use as follows:

First you need to know the People Picker Id generated by application. We can get this easily by using browser developer tool , observe the following image.




Here people picker Id is "ctl00_SPWebPartManager1_g_3a92cac2_9070_4c21_a117_8cb64a33bc5f_ctl00_peoplePickerProjectManager_TopSpan" , with this id we can clear the people picker using jquery function as follows:

function clearPeoplePicker(peoplePickerId) {
        var spclientPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerId];
        var ResolvedUsers = $(document.getElementById(spclientPeoplePicker.ResolvedListElementId)).find("span[class='sp-peoplepicker-userSpan']");
        $(ResolvedUsers).each(function (index) {
            spclientPeoplePicker.DeleteProcessedUser(this);
        });
    },

We need to pass the people picker id which is like as mention above.

That's all, I hope this helps you.

Thank You... 


Upload files into a folder of SharePoint Document Library - REST API - JQuery

Hi, this post explains how to upload the files in to the document library of SharePoint.

Let us take the following control is input file control.

<input type="file" name="attachment" id="inputFileUpload" class="input-file-control"/>


Now we can upload the files into the SharePoint library with following functions.
In the following function parameters values are like as follow:

fileInputControlId -- Id of input file controls , here it is : '#inputFileUpload' ;
webUrl -- Url of SharePoint Site.
documentLibraryName -- Name of the document library which is root folder of uploaded file.
folderName -- Name of the folder exist in the specified document library of SharePoint Site.

For uploading files , you just call the "uploadFiles" method with required parameters.

//Call this function to upload the files.
function uploadFiles(fileInputControlId, webUrl, documentLibraryName, folderName) {
        for (var i = 0; i < $(fileInputControlId)[0].files.length; i++) {
            var uploadFile = $(fileInputControlId)[0].files[i];
            var getFile = getFileBuffer(uploadFile);
            getFile.done(function (arrayBuffer) {
                uploadFileToFolder(webUrl, documentLibraryName, folderName, uploadFile.name, arrayBuffer, function (data) {
                  alert("File upload done successfully");
                }, function (data) {
                  alert("File uploading fail");
                });
            });
        }
    }

//Get the uploaded file buffer.
function getFileBuffer(uploadFile) {
        var deferred = jQuery.Deferred();
        var reader = new FileReader();
        reader.onloadend = function (e) {
            deferred.resolve(e.target.result);
        }
        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }
        reader.readAsArrayBuffer(uploadFile);
        return deferred.promise();
    }

//Upload files into SharePoint library with REST API
 function uploadFileToFolder(webUrl, documentLibraryName, folderName, fileName, arrayBuffer, success, failure) {
        //file added to the subfolder of Rootfolder.
        var apiUrl = webUrl + "/_api/web/lists/getByTitle('" + documentLibraryName + "')/RootFolder/folders('" + folderName + "')/files/add(url='" + fileName + "', overwrite=true)";

        $.ajax({
            url: apiUrl,
            type: "POST",
            data: arrayBuffer,
            processData: false,
            async:false,
            headers: {
                "accept": "application/json;odata=verbose",
                "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
            },
            success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
    }

With the above function we can upload the files into the folder exist in the document library.
If we need to upload files directly into document library you need to change the REST API cal as follows:

var apiUrl = webUrl+"/_api/web/lists/getByTitle('" + documentLibraryName + "')/RootFolder/files/add(url='" + fileName + "', overwrite=true)";

That's all, I hope this helps to you.

Thank You...

Client Side People Picker - SharePoint - Jquery

Hi, here I provide the code to handle the client side people picker from Jquery.

My client side People picker is as follows:

<SharePoint:ClientPeoplePicker ID="peoplePickerProjectManager" runat="server" AllowMultipleEntities="false" Required="true" ValidationEnabled="true" />

You can place it in any .aspx page. Use as follows:

First you need to know the People Picker Id generated by application. We can get this easily by using browser developer tool , observe the following image.





Here people picker Id is "ctl00_SPWebPartManager1_g_3a92cac2_9070_4c21_a117_8cb64a33bc5f_ctl00_peoplePickerProjectManager_TopSpan" , with this id we can retrieve from and resolve user to people picker using jquery.

With the following function we can get the resolved users details.

function getResolvedEmails(peoplePickerId) {
        var users = [];
        var resolvedUsers = JSON.parse($('#' + peoplePickerDivId + ' input[id*=peUser_TopSpan_HiddenInput]').val());

        if (resolvedUsers.length > 0) {
            $.each(resolvedUsers, function (key, value) {
                if (value.IsResolved)
                    user.push(value);
            });
        }
        return users;
    }

In the above function you need to pass the people picker id which is get from the developer tool, which is like what am consider from above image.

If we know the user Email or Id we resolve them into people picker by the following way.

With the following function we can resolve or bind the users into the people picker. Here bind the users to people picker by their emails. We can also bind with their Id's also. The difference among those is just getting the users from REST call. For emails we use "getByEmail" , for Ids we use "getById". After getting the users we need to pass those user objects to people picker to resolve by following function.

function getUsersByEmails(usersEmails){
     var users=[];
     var webUrl="http:stage.test.com/mysite/";
     $.each(usersEmals,function(index,email){
         var resourceUrl=webUrl+"/_api/web/siteusers/getbyemail('" + email+ "')";
         getData(resourceUrl, function (data) {
                users.push(data.d);
            }, function(data){
               alert('Fail to get user');
        });
     });
     return users;
}

//Rest Call to get data from sharepoint
function getData(resourceUrl,success,failure){
           $.ajax({
                url: resourceUrl,
                method: "GET",
                async: false,
                headers: { "Accept": "application/json; odata=verbose" },
                success: function (data) {
                success(data);
            },
            error: function (data) {
                failure(data);
            }
        });
}

function bindUsersToPeoplePickerByEmails(peoplePickerId,users){
        var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePikcerId];
        $.each(users,function(index,user){
             var usrObj = { 'Key': user.Title};
             peoplePicker.AddUnresolvedUser(usrObj, true);
        });
}

With the above function we can resolve the users into people picker.

That's all. I hope this helps you. 

Thank you.




Saturday, 3 January 2015


$skip not working in REST API - SharePoint:


Hi,

In REST API, $skip is not working properly in some cases.

Omg, What we do now...!!!

Hey cool we have a solution to this problem.

Use the following service for $skip working.

"/_vti_bin/ListDat.svc/ListName?$skip=2&$top=1&$orderby=id"

Here Listname is your sharepoint list name.

Sample URI for ajax call:

"http://organiztion.sharepoint.com/sites/testSite/_vti_bin/ListData.svc/myList?$select=Id,Title&$filter=$orderby=id&$skip=2&$top=1"


If you use the above uri you can achive paging also in REST API.


I hope thils help you... :)

Wednesday, 19 November 2014

Add values to the different types of Fields in the SharePoint List Pragramatically - C#


In SharePoint list we have different types of fields.

While we insert data into the field, use field names are internal name of the field, don't use display name.

In the following snippets show how to add values to different types of fields in the SharePoint list:

Field Type - Single Line Text :

    listItem["ColumnName1"] = "value1";    // here "value" is the  data into the field.

Field Type - Multiple Line Text :

    listItem["ColumnName2"] = "value2";

Field Type - Boolean:

    listItem["ColumnName"] = "Yes" / true / "No" / false ;    //insert one value only :)


Field Type - Choice:

    listItem["ColumnName3"] = list.Fields["ColumnName3"].GetFieldValue(myChoice);

Field Type - Number:

    listItem["ColumnName4"] = value4;

Field Type - Currency:

   listItem["ColumnName5"] = "value5";

Field Type - Date and Time:

   listItem["ColumnName6"] = "DateTimeValue";


Field Type - LookUp:

  var department = web.Lists["Department"].GetItemById(1); // Get the Reference record.

  var  employee = web.Lists["Employee"].Items.Add();

  empolyee["Department"] = new SPFieldLookupValue(department.ID, department.Title);
                                              // Set the lookUp value to the field.
  employee.Update();

(Or) Simply we can set as follows:
  
      employee["Department"] = "1";

Field Type - Person or Group:

   SPUser user = null;

   user = web.EnsureUser("Domain\Loginname");

   listitem["manager"] = user;

Field Type - Hyper link :

   SPFieldUrlValue hyperlink = new SPFiedlUrlValue();

   hyperlink.Description = "Sharepoint Light";

   hyperlink.Url = "http://sharepointbabu.blogspot.in/";

   listitem["HyperLink"] = hyperlink;

   (Or) Simply we can set as follows:

    listitem["HyperLink"] = "http://sharepointbabu.blogspot.in/, Sharepoint Light";

 

Field Type - Calculated :

   Calculated field value is set automatically based on the given formula based on the other fields data.


In the following code snippet, insert data into different SharePoint list fields using C#.

---------------------------------------------------------------------------------------------------------------------

using (SPSite site = new SPSite(SPContext.Current.Web.Url))
{
  using (SPWeb web = site.OpenWeb())
   {
      web.AllowUnsafeUpdates = true;

          SPUser manager = null;

              try
                {
                  SPList list = web.Lists.TryGetList("employe");

                   SPUser user = null;    // for people picker insertion

                   user = web.EnsureUser("Domain\Loginname");  // for people picker insertion

                  if (list == null)
                     throw new Exception(string.Format("List {0} can not be found", Constants.List_ADUserAccounts));

                  SPListItem listitem = list.Items.Add();
   
                   listItem["SinglelinetextColumn"] = "value";

                   listItem["MultilinetextColumn"] = "value";

                   listItem["BooleanColumn"] = true ;

                   listItem["ChoiceColumn"] = list.Fields["ChoiceColumn"].GetFieldValue(myChoice);

                   listItem["NumberColumn"] = value;

                   listItem["CurrencyColumn"] = "value";

                   listItem["DateTimeColumn"] = "DateTimeValue";

                   listitem["managerColumn"] = user;

                   listitem["HyperLinkColumn"] = "http://nagababua.blogspot.in/, Fix Your Code";

                   listitem.Update();

                }

            catch
            {
                 throw;
             }

           finally
           {
                 web.AllowUnsafeUpdates = false;
           }
      }
}

-----------------------------------------------------------------------------------------------------------------------


  



Get the User Profile in Auto Push Back event on people picker in SharePoint site programmatic.


The following description describes, programmatic how to get the user profile details automatically when the user is resolved in people picker field.

==> If you want to get user profile and show  automatically when resolve the user by people picker, do following steps:

Step 1:

Add the "AutoPushBack='true' " attribute to people picker control in SamplePage.aspx page.

Step 2:

Add the following code in your code behind (SamplePage.aspx.cs) file in the Page Load Event.


==> If you want to get the user profile after an any other event like click on some button, then directly place the following code in click event.


// Code snippent

==> using Microsoft.Office.Service.Userprofie  // add this reference first

==> In the following code snippet "spnLoginName" is the id of a label to display result and "peUser" is the people picker control Id, so replace it with what yours controls id's


try
   {
      using (SPSite site = new SPSite(SPContext.Current.Web.Url))
        {
          ServerContext context = ServerContext.GetContext(site);

          UserProfileManager   profileManager = new   UserProfileManager(context);

          PickerEntity   entity = (PickerEntity)peUser.ResolvedEntities[0];

          UserProfile   profile = profileManager.GetUserProfile(entity.Key);

          spnLoginName.InnerText = profile[PropertyConstants.SAMUserName].Value.ToString();
                 
         }
             
    }
 catch
     {
         throw;
      }


== > Through this code you get all the user profiles who are exited in you SharePoint Site.

Saturday, 8 November 2014

How to set Label width in CSS




While we are styling a label using CSS, remember one thing.

i.e. Label is not a block element, so the width property is not applicable to it directly.

Hey don't worry, We have a simple solution to this problem,  just make Label as block element
like as follows:

.mylabel{

         display: inline-block;
         width: 24px;
}