Sunday 26 March 2017

Run executeQueryAsync() synchronously SharePoint 2013

In JSOM, to fetch the data from the server we make a call through executeQueryAsync(). This works asynchronously by default.We need to make executeQueryAsync() behave synchronously.

That means we have to make this function wait till the operation gets completed and should return some values , then proceed to the next function.

This can be done by using JavaScript callbacks and deferred/Promises.
The promises pattern significantly simplifies JavaScript code when you make an app, which has multiple, nested asynchronous calls and it makes it very powerful.



<script type="text/javascript">
    var camlValues;
    $(document).ready(function () {
             
        SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getItems);
    });
 
    function getItems() {
        getListItem('Test list').done(function()
{
        console.log(“Second Console Pass”);  
}).fail(function()
{
 console.log(“Second Console Fail”);  
});            
    }
 
    function getListItem(listTitle) {

      var deferred=$.Deferred();
        var clientContext = new SP.ClientContext.get_current();
        var olist = clientContext.get_web().get_lists().getByTitle(listTitle);
        var camlQuery = new SP.CamlQuery();
        ocamlItems = olist.getItems(camlQuery);
        clientContext.load(camlValues);
        clientContext.executeQueryAsync(
            Function.createDelegate(this, this.success),
            Function.createDelegate(this, this.failure)
        );

return deferred.promise();
    };
 
    function success(sender, args) {
        var listItemEnumerator = ocamlItems.getEnumerator();
        while (listItemEnumerator.moveNext()) {
            var olistItem = listItemEnumerator.get_current();
console.log(‘First Console Pass ‘);
             
deferred.resolve(olistItem );
        }
    }
 
    function onQueryFailed(sender, args) {
        console.log('An error occured while retrieving list items:' + args.get_message());

deferred.reject(olistItem );
    }
</script>





For the code given above, we will get the output, as shown below.

First Console Pass
Second Console Pass


Thanks.. Happy Coding..

Thursday 23 March 2017

Author(Created By) Managed Property having more than one user in Odata search results SharePoint 2013

Hi All,
 
In our project we faced an issue in search query. Our requirement is to show all the requests raised by the current user in a page. So Basically we need to use "Created By" field in Search Rest end point url. Initially we used the following Rest end point url to retrieve the requests.
 
<Site_URL>/_api/search/query?querytext='Author:"<Current User Login Name>"
 
Please Note that we have used the managed property "Author" as it is the internal name of "Created By". 
Later we got an issue that more than one user was able to see the same request . Logically "created by" will be only one user. The issue is because "Author" property has the user who created the item and also the user who last modified the item. So the item was visible for both creator and last modified user.
 
For this we found an other managed property AuthorOWSUSER which resolved our issue.
 
So the final rest end point url is
 
<Site_URL>/_api/search/query?querytext='AuthorOWSUSER:"<Current User Login Name>"

Thank You 
Happy Coding ☺

Wednesday 1 March 2017

Programmatically update the site title in SharePoint 2013

Hi All,

 Today I tried to update the Title of a Site in SharePoint.
I thought it will be as direct as spweb.Title="My new title";

But it was not so. U have to do the below code to update the Site title.

                    SPUserResource resource = oweb.TitleResource;
                    foreach (CultureInfo culture in oweb.SupportedUICultures)
                    {
                        resource.SetValueForUICulture(culture, txtTitle.Text);
                    }

This takes care of the multilingual behaviour of SharePoint and updates the Site Title in the browser.

Happy Coding

Monday 23 January 2017

Search not working properly SharePoint 2013

Hi,
 Last week I faced an issue and wanted to share the solution with u guys. I was using content search webpart to pull data from some pages and display. The issue I faced was the page content coming from the source site was displayed two times in our content search webpart configured page. After couple of hours of investigating the Query builder, search results, content sources, etc.. we found the setting that has to be done on the source site pages.



That setting is "hide physical urls from search". This is found in "Edit Properties" of every page. Hope this helps you :)

Friday 6 January 2017

Create Publishing Page using Custom PageLayout by PowerShell in SharePoint 2013

Hi - Today i will share the code for creating Publishing Page based on a custom Pagelayout using powershell


$siteUrl="ur site URL here"

$site = Get-spsite $siteUrl
$web = $site.OpenWeb()
$pubWeb =[Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
#Name of the page layout. It can also be your custom template
$pl = $pubWeb.GetAvailablePageLayouts() | Where { $_.Name -eq "BlankWebPartPage.aspx" }
$newPage = $pubWeb.AddPublishingPage("newpage.aspx", $pl)
$newPage.CheckIn("")
$newPage.ListItem.File.Publish("")
$web.Dispose()

Happy coding..

Friday 25 November 2016

remove a term from managed metadata column in Sharepoint




Hi All,

 Today I will share you the code for removing a single term from a Managed Metadata (- multivalue) column in a list.

Name of the List - "Todo List"
Name of the Managed metadata column - "TodoColumn"
Values it is holding at present - "Lesson 1" , "Lesson 2" , "Lesson 3" , "Lesson 4"
Value to be removed - "Lesson 1"

Now we will see the code :


   SPList list = oweb.Lists["Todo List"];
                    SPQuery oQuery = new SPQuery();
                    oQuery.Query = " <Where><Eq><FieldRef Name='TodoColumn' /><Value Type='TaxonomyFieldTypeMulti'>Lesson 1</Value></Eq></Where>";
                    SPListItemCollection collListItems = list.GetItems(oQuery);
                    foreach (SPListItem oListItem in collListItems)
                    {
                        TaxonomyFieldValueCollection tfc = oListItem["TodoColumn"] as TaxonomyFieldValueCollection;
                        tfc.Remove(tfc.Where(i => i.Label.Equals("Lesson 1")).FirstOrDefault());
                        oListItem["TodoColumn"] = tfc;
                        oListItem.Update();
                    }
                    list.Update()


Thats's it :)

Have a great day... Happy coding :))))

Friday 4 November 2016

SharePoint - Programmatically get Friendly URL of Publishing pages

Hi Guys - After so long time, I am posting this. I got so busy in my project. Finally I am getting some time to post this. I got his requirement of finding the Friendly URL of Publishing pages.

Code is given below. Hope this helps someone.



using (SPSite osite = new SPSite("site url"))
            {
                using (SPWeb oweb = osite.OpenWeb())
                {
                    SPList olist = oweb.Lists["Pages"];
                    foreach (SPListItem item in olist.Items)
                    {
                        var associatedTerms = TaxonomyNavigation.GetFriendlyUrlsForListItem(item, false);

                        string url = string.Empty;
                        if (associatedTerms.Count > 0)
                        {
                            url = associatedTerms[0].GetResolvedDisplayUrl(string.Empty);
                        }
                    }
                }
            }


Happy Coding :)