Friday 25 December 2015

REST End point URLs - SharePoint 2013

Today I will be sharing the Service End point URLs for the SharePoint 2013. To access SharePoint resources using REST, construct a RESTful HTTP request, using the Open Data Protocol (OData) standard, which corresponds to the desired client object model.

Example :

List Name - Products

Columns - Title , Company , Products , Manager

In which Title , Company are Single Line of Text columns.
Company is a lookup column ( LookUp list - Company Names  and It is Looking up to the column Company name with Internal Name Title ) .
Manager is a people Picker Column.

Service call for accesssing the columns would be -

(Always use Internal names for the columns and Display names for the List)
https://halyardhealth.sharepoint.com/sites/SPDEV/_api/web/lists/getbytitle('Products')/items?$select=Title,Products,Company/Title,Manager/Title&$expand=Company,Manager

For Lookup and People picker colums we have to expand the column like above

For applying the filter on the above query -

https://halyardhealth.sharepoint.com/sites/SPDEV/_api/web/lists/getbytitle('Products')/items?$select=Title,Products,Company/Title,Manager/Title&$expand=Company,Manager&$filter=Products eq 'Product 1'

https://halyardhealth.sharepoint.com/sites/SPDEV/_api/web/lists/getbytitle('Products')/items?$select=Title,Products,Company/Title,Manager/Title&$expand=Company,Manager&$filter=Company/Title eq 'Company 1'

For applying multiple filters :

https://halyardhealth.sharepoint.com/sites/SPDEV/_api/web/lists/getbytitle('Products')/items?$select=Title,Products,Company/Title,Manager/Title&$expand=Company,Manager&$filter=((Products eq 'Product 1') and(Company/Title eq 'Company 1'))

From the next post onwards I will be providing the codes for CRUD operation on Sharepoint 2013 list using Rest api.

Happy Coding...

Wednesday 11 November 2015

All about "App Step" in SharePoint 2013

Impersonation Step workflow action had been deprecated in SharePoint Designer 2013. !!!
Yet , In SharePoint Designer 2013, you can choose the SharePoint 2010 Workflow platform during creation and still have all of those workflow actions available.

Even though we have the option to choose 2010 workflow and go for Impersonation Step, the best option is to leverage the App Step in 2013 workflows.

A SharePoint Designer workflow will run under the permissions of the user who started the workflow. Certain steps of the workflow may require the user to have more permissions than you intend to grant them. If elevated permissions are not used, the workflow will not work, and you will likely receive an access denied error or the workflow will not execute at all.

In 2010 workflow we had Impersonation Step to overcome this. when the workflow enters the Impersonation Step, it runs under User's account who published the workflow.

Drawback in Impersonation Step :

The one drawback of using an Impersonation Step is that the workflow could suddenly stop working if anything were to happen to the user account that created and published the workflow. The purpose of the Impersonation Step is to run any actions inside this step as the user who authored the workflow. If the account that creates and publishes the workflow is edited in some way, possibly with a permission change on the site or a password change, then you have a broken workflow.


This has been overcome in the 2013 SharePoint Designer's App step:

Any actions you now place within this App Step can read from and write to all items in the site. And this does not depend on the user's account who has published the workflow.

So the actions that runs under the App Step will run under "System Account".
To get more details about "System Account" in SharePoint , check my another post here.


To Enable App Step in workflow, follow the below procedures


  • Go to Site Settings.
  • In the Site Actions section, select Manage site features.
  • Locate the feature called Workflows can use app permissions, as shown in the figure, and then click Activate.


Now you can see App step in your 2013 designer workflow.

Happy SharePointing.....

Thursday 17 September 2015

Not able to create a Page Layout in SharePoint 2013 - Fixed

Hi All,

Recently I faced a weird problem while trying to create a new page layout from SharePoint Designer. Our environment got upgraded from 2010 to O365 recently.
Actually the error details were this:

When I tried to click on the Create New Page Layout link, I got "An unexpected error has occurred" message with a correlation ID. Even though we got the Correlation ID, it was not as easy as on-premises environment to go and check the logs.

So obviously I came for the help from Google and as usually it helped me in figuring it out.

Solution is as follows:


  • First check whether you are the Site Collection Administrator.
  • Then go to the Site Features, Disable SharePoint Server Publishing feature and go to the Site Collection features, Disable SharePoint Server Publishing Infrastructure feature
  • Then again Enable SharePoint Server Publishing Infrastructure in Site Collection Features . After that go to Site features and Enable SharePoint Server Publishing.


Now try to create a page layout. It works :)

Thanks for reading. Hope it helps..

Sunday 30 August 2015

How to programmatically get the Titles and Guids of all the lists in a Sharepoint site.

Hi all, Below code is used to get the details of all lists in the Site using CSOM.
I have logged the details in console. You can manipulate the data as per the requirement.

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext');
    retrieveAllListProperties();
});


function retrieveAllListProperties() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
    this.collList = oWebsite.get_lists();
    clientContext.load(collList);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),       Function.createDelegate(this, this.onQueryFailed));

}

function onQuerySucceeded() {

    var listInfo = '';
    var listEnumerator = collList.getEnumerator();
    while (listEnumerator.moveNext()) {
        var oList = listEnumerator.get_current();
        listInfo += 'Title: ' + oList.get_title() + ' Guid: ' + oList.get_id().toString() + '\n';
    }
    console.log(listInfo);
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}


Happy Coding :)

Sunday 26 July 2015

Get current user using javascript - SharePoint client object model

Hi All,

  In this post we will see about, getting the loggedin Username using Javascript only.
In Client object model , to get the value of the loggedin User, mostly everyone will go for $().SPServices.SPGetCurrentUser. SP Services ibrary has tons of uses and is very easier.
But we can do this without referencing a third party library, if your requirement is like so.

Below given is the code for it.

function getCurrentUser()
{
var context = new SP.ClientContext.get_current();
this.website = context.get_web();
this.currentUser = website.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}



function onQuerySucceeded(sender, args)
 {
 alert(currentUser.get_loginName());
 }



function onQueryFailed(sender, args)
{
alert('request failed ' + args.get_message() + '\n'+ args.get_stackTrace());
}

Hope this helps somewhere. Happy coding..

Wednesday 15 July 2015

Programmatically getting the values from a SharePoint list view

Hi,
 Today I will share the code for getting the values of the items in a particular view through Client Side Object Model.
For this we have to make 2 requests. First request is to get to know which view & view query and second would be for getting the values from that view.

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getItemsFromView);
});

// First request
function getItemsFromView()
{
    var context = new SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle('List Name');
    var view = list.get_views().getByTitle('View Name');
    context.load(view);
    context.executeQueryAsync(
        function (sender, args) { getItemsFromList('List Name', "<View><Query>" + view.get_viewQuery() + "</Query></View>") },
        function(sender, args) {alert("error: " + args.get_message());}
    );
}
//Second Request
function getItemsFromList(listTitle, queryText) {
    var context = new SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle(listTitle);
    var query = new SP.CamlQuery();
    query.set_viewXml(queryText);
    var items = list.getItems(query);
    context.load(items);
    context.executeQueryAsync(
        function () {
            var listItemInfo = '';
            var listEnumerator = items.getEnumerator();
            var i = 0;
            while (listEnumerator.moveNext())
            {
                i++;
            }
            alert("items retrieved: " + i);
         
        },
     
function (sender, args) { alert("error in inner request: " + args.get_message()); }
   );
}

Hope this helps. Happy Coding :)

Sunday 12 July 2015

Programmatically Send E-Mail using System.Net.Mail - SharePoint

Hi,
 There are some limitations while sending mails through SPUtility.SendEmail method as I have stated here.

1.   No attachment allowed
2.   Message body size cannot exceed 2048 characters.
3.   The from address will be the “Outbound Sender Address” configured in the central admin.


To Overcome these we are going to follow the below approach.

Using SmtpClient from System.Net.Mail namespace.

Namespaces required:

using System.Net.Mail;
using Microsoft.SharePoint.Administration;


Below is the code for sending Email:

SmtpClient smtpServer = new SmtpClient(webApp.OutboundMailServiceInstance.Server.Address);

MailMessage mail = new MailMessage();
mail.From = new MailAddress("fromEmail@abc.com");
mail.To.Add("toEmail@abc.com");
mail.Subject = "subject";
mail.Body = "body";
mail.BodyFormat = System.Web.Mail.MailFormat.Html;
System.Web.Mail.MailAttachment attachObj = new System.Web.Mail.MailAttachment("path of the attachment in SharePoint");
mail.Attachments.Add(attachObj);

smtpServer.UseDefaultCredentials = true;
smtpsmtpServer.Send(mail);


By Following this we can overcome the limitations faced in SPUtility.SendEmail method.

Have a good Day :)
Happy Coding :)

Programmatically Send E-Mail using SPUtility.SendEmail - SharePoint

Hi All,
 Today we will see about Email in SharePoint (programmatical approach)

If you want to Send E-mail through SharePoint, We can use the capabilities already provided by SharePoint. (i.e) SPUtility.SendEmail. This is basically SharePoint's native functionality for email delivery.

First you will need to be sure that outgoing mail settings are configured for SharePoint. After that you can easily send email from your custom SharePoint application using SharePoint’s native mail capabilities. You can do this in Central Administration.
Open Central Admin --> System Settings --> Configure Outgoing Email

Before attempting to send an email from your application, you can easily check to be sure that the outgoing email settings are configured.

bool blnIsEmailServerSet = SPUtility.IsEmailServerSet(web);

If this returns false, you should not bother trying to send the email. Instead, show an error message or notify the SharePoint administrator, to check the settings of the server. If it returns true, you are good to go:

To use this method we will require namespaces:

using Microsoft.SharePoint.Utilities;
using System.Collections.Specialized;

Code:

 Below given is the code.

            using (SPSite oSite = new SPSite("Site collection URL"))  //Site collection URL
            {
                using (SPWeb oSPWeb = oSite.OpenWeb("Subsite URL"))  //Subsite URL
                {
                    StringDictionary headers = new StringDictionary();

                    headers.Add("from", "senderEmail@domain.com");
                    headers.Add("to", "receiverEmail@domain.com");
                    headers..add("bcc","HiddenuserEmail@domain.com");
                    headers.Add("subject", "Send Email using SP Utility");
                    headers.Add("fAppendHtmlTag","True"); //To enable HTML format

                    System.Text.StringBuilder strMessage = new System.Text.StringBuilder();
                    strMessage.Append("body of the message that can include html tags also");
                 
                    strMessage.Append("<span style='color:red;'> HTML </span>");
                    SPUtility.SendEmail(oWeb, headers, strMessage.ToString());

                }
            }


Some Limitations for this method are :

1.   No attachment allowed
2.   Message body size cannot exceed 2048 characters.
3.   The from address will be the “Outbound Sender Address” configured in the central admin.

To overcome the limitations, use the System.Net.Mail class methods to send E-mail.
I have given details here.

Happy Coding :)

Monday 6 July 2015

Programmatically Diasable List Throttling for a specific List in SharePoint - Powershell

Hi All,

 Today we will see about "How to Diasable List Throttling for a specific List".

SP2010 introduces list throttling settings that allow us to specify how many items a user can query before the throttle kicks in and aborts the query. This applies to both the queries that retrieve through SharePoint UI and from custom code. Default limit is 5000 items per list. While exceeding this limit results in display of an error message. We can override it by calling RequestThrottleOverride on the SPQuery object. This will allow us to execute large unsafe queries.

SharePoint 2010 provides Administrators to control a limit of how many items to be retrieved from the lists at a time using User Interface or Object Model.

SharePoint by default set some limitation to your web application to make sure that performance is good even when data increasing. These limitations has been tested and carefully chosen by SharePoint Team and Microsoft does not recommend changing these value.


List Throttiling feature is webapplication level.
If we want to change the limits for the whole web app,
From Central Administration
1. Go to SharePoint 2010 Central Administration
2. Under Application Management, click "Manage Web Application"
3. Choose the web application that you want to change. On the ribbon click "General Settings" and then "Resource Throttling"
4. Change throttling settings and click OK.

To override the default throttling settings. just execute the below powershell to add list items more than the threshold limits.

web = Get-SPWeb -Identity http://mysite
$web.AllowUnsafeUpdates = $True
$list = $web.Lists["ListName"]
$list.EnableThrottling = $False
$list.Update()
$web.AllowUnsafeUpdates = $False
$web.Update()
$web.Dispose()

Thanks for your time.. Happy SharePointing..

Wednesday 1 July 2015

Everyone and Everyone except external users SharePoint Online - Boundaries and Limitations.

 Hi All,

Today we will see about SharePoint Online. Let's say you have been asked to share a content (file or site or anything). Now these two words come into picture "everyone" and "everyone except external users".

Want to get more details about "External Users" - Check here

When a user is added to Office 365, the user automatically becomes a member of Everyone except external users. The important thing we have to note is that, By default, the Everyone except external users group is added to the Members group on the SharePoint Team Site. It is automatically assigned a permission level of Contribute. This means all users who are added to Office 365 can view, add, update, and delete items from lists and libraries.

If you want to change the permission levels for this group, you can remove it from the Members group and then add it to a group that uses different permissions. For example, you might add the Everyone except external users to the SharePoint Visitors group. This automatically assigns a Read permission level to all users in the Everyone except external users group.


And there is a difference between "everyone" and "everyone except external users".

Everyone:

All users no matter whether they are authenticated to access the SharePoint Online. For example, you share a document with everyone, and then all users can anonymously access the document as if they have the document URL.

Everyone except external users:

All internal user accounts which can be recognized by SharePoint Online.

And we have some limitations while using these groups.


  • While sharing some content with either of these groups, you can't send invitation mail for them.


  • You can't remove a user from either of these groups. Say, you want to share a document with all the persons except some few people. You can't go and delete those specific users. For this situation you have to create a new SharePoint group and add all the users you want in that.

Share me your feedback :)
Have a good day :)

Sunday 7 June 2015

Programmatically Updating the Infopath forms and UDCX files after migration - SharePoint Powershell

Hi All,
 Today we will see about Infopath. We had a SharePoint migration in our company from 2010 to 2013. This Powershell cmdlet helped very much in reducing the manual time for updating the data connections in the Infopath forms.

 Once migration is done, the Infopath will be still pointing to the Old URLs in the data Connections.
Example: If the Old URL is something like "http://contoso2010.Company.com" and the New URL is like "http://contoso2013.Company.com", and after migration also the Data Connections will be pointing towards "http://contoso2010.Company.com". This includes the UDCX files also.

If there are only few forms, we can change it easily by following the below method.

For Updating in the forms : Just open the form in the Infopath designer, in the "DATA" tab click on "Data Connections". Check whether it is poinint towards our new URL. If not update the same and re-publish.

For Updating the UDCX files : Open the Data Connections Library and download the files to the Loca. Open the files in the notepad and change the "Web URL" and "List ID" parameters to the latest.

The above method will be helpful only if there are few forms. If there are more forms to be manually updated you can always go for the below PowerShell method.


The Update-SPInfoPathUserFileUrl cmd-let will upgrade form template and data connection files as per the parameter we give in the cmdlet. The update will access ALL files (except ASPX files) in any Data Connection library anywhere in the site and Update.

CMD-LET is

Get-SPWebApplication http://contoso2013 | Update-SPInfoPathUserFileUrl-find "http://contoso2010" -replace "http://contoso2013"

This example updates data connections in InfoPath form templates and universal data connection files, for all content under the Web application http://contoso2013. Data connections that reference http://contoso2010 are updated to reference http://contoso2013.

This also works for Admin approved Infopath forms :Update-SPInfoPathAdminFileURL -find "http://contoso2010" -replace "http://contoso2013".

The same method could be followed when moving the forms from Test to Production.

Thanks for Reading.. See you in the next post.. Happy Sharepointing..................



Sunday 15 March 2015

Odata querying 100 items only issue - SharePoint

Hi Coders,
 This post will be useful for the beginners, who has already started using Odata in SharePoint 2013. You might have faced this issue or you havent figured it out yet.

For Odata queries please refer this.

So based on the above link, for retrieving items from the list , we have to use the following syntax.
http://server/site/_api/web/lists('guid')/items?$select=Title
This provides you the "Title" column value of  the items in the list.

So, the tweak in this query is, by default it returns only 100 items..
This important point has been missed in most of the documentation..


FIX : 
So to fix this we have to use the "top" clause.
http://server/site/_api/web/lists('guid')/items?$select=Title$top=10000

We have to give a maximum value based on our application nature.

Hope this helps..

Have a good day. Meet you on the next post.
Happy Sharepointing......