Disable ItemUpdated Endless loop in Event Receiver

In one of my project, I had a requirement to build an event receiver which is for item updated.

The logic is when I update the document, programmatically my custom field will be updated with a value.

So I thought of adding event receiver for that and wrote below code:

public override void ItemUpdated(SPItemEventProperties properties)
{
    base.ItemUpdated(properties);
    SPListItem listItem = properties.ListItem;
    listItem["MyCustomField"] = "Okay, I’m updated!";
    listItem.Update();
}

When I ran this code with debugging,

listItem.Update();

fired and event receiver called again as item is being updated so my break-point started over from

base.ItemUpdated(properties);

It means again ItemUpdated event receiver will be called.

So this was like endless loop. There must be some workaround for this which is as follow: we need to write updating code in a way that it doesn’t trigger event receiver again.

So I have created below DisabledEventsScope class in the event receiver file.

class  DisabledEventsScope : SPItemEventReceiver, IDisposable
{
    // Boolean to hold the original value of the EventFiringEnabled property
    bool _originalValue;
    public DisabledEventsScope()
    {
        // Save off the original value of EventFiringEnabled
        _originalValue = base.EventFiringEnabled;

        // Set EventFiringEnabled to false to disable it
        base.EventFiringEnabled = false ;
    }
    public void Dispose()
    {
        // Set EventFiringEnabled back to its original value
        base.EventFiringEnabled = _originalValue;
    }
}

This class will turn off the firing of the event receiver by setting Boolean value of event receiver, run the code without endless loop. We need to implement this class in our code so that it disable event firing.

public override void ItemUpdated(SPItemEventProperties  properties)
{
    base.ItemUpdated(properties);
    using (DisabledEventsScope scope = new DisabledEventsScope ())
    {
        SPListItem listItem = properties.ListItem;
        listItem["MyCustomField"] = "Okay, I’m updated!";
        listItem.Update();
    }
}

Once this code is running, it won’t be firing endless loop of event receiver.

Happy SharePointing.!!

Search with Keyword Query in SharePoint OnPremise

In SharePoint 2013 on premise, I had a requirement to have a webpart, that does search each project site’s task list items to fetch the task assigned to logged in user which is not completed. All the project site has one task lists so to fetch the record so I have used KeywordQuery, which is comparatively faster than SPSiteDataQuery.
So below is the snippet to fetch the records.

using (SPSite site = new SPSite(pwaSiteUrl))
{
    SPUser _currUser = SPContext.Current.Web.CurrentUser;
    KeywordQuery keywordQuery = new KeywordQuery(site);
    keywordQuery.RowLimit = 500;
    keywordQuery.SelectProperties.Add("SiteTitle");
    keywordQuery.SelectProperties.Add("AssignedTo");
    keywordQuery.SelectProperties.Add("PercentCompleteOWSNMBR");
    keywordQuery.SelectProperties.Add("DueDateOWSDATE");
    keywordQuery.QueryText = "ContentClass:\"STS_ListItem_Tasks\" AND " +
                                "(PercentCompleteOWSNMBR<>1.0*) AND " +
                                "(DueDateOWSDATE:2*) AND " +
                                "AssignedTo:" + _currUser.Name;
    SearchExecutor searchExecutor = new SearchExecutor();

    ResultTableCollection resultTableCollection = searchExecutor.ExecuteQuery(keywordQuery);

    ResultTable resultTable = resultTableCollection.FirstOrDefault();
    DataTable dataTable = resultTable.Table;
    GetFormatedMyTasks(dataTable);
}

In QueryText, I have used multiple fitlers on managed properties.
1. All items must be task items. ContentClass:"STS_ListItem_Tasks"
2. Task must not be completed. PercentCompleteOWSNMBR<>1.0*
3. Due Date must not be empty. DueDateOWSDATE:2* (by default system date starts with year)
4. AssignedTo must be current user.

Note:
1. For DueDateOWSDATE I have used not empty filter. Date will always be starting from 2 (current year starting digit).
2. pwaSiteURL is my project root site in that I have all my project sites, so it will search for that context only.
3. By default my custom field will not appear in the result source, so I have to add my properties to results with: keywordQuery.SelectProperties.Add("AssignedTo");

Show All People in search result Webpart

In this blog post, I will explain how you can show all people by default when you load the page having search result webpart.

I assume in your publishing page you have added search result webpart. Now Edit webpart properties and click Change query

Search Result Webpart properties

Search Result Webpart properties

In Build Your Query dialog, select a query dropdown to Local People Results (System) and in Query text add following line:

contentclass:spspeople

Now click Test query.

Build Your Query Dialog

Build Your Query Dialog

Once you test the query, you will see the result in the right side Search Result Preview panel.

Search User Result Preview

Search User Result Preview

Now click OK and Save the page. You will now able to see all employee directory.

Happy SharePointing!!

SharePoint 2013 List Template IDs

Some important ListTemplateID for List for version SharePoint 2013:

  • 100 – Generic list
  • 101 – Document library
  • 102 – Survey
  • 103 – Links list
  • 104 – Announcements list
  • 105 – Contacts list
  • 106 – Events list
  • 107 – Tasks list
  • 108 – Discussion board
  • 109 – Picture library
  • 110 – Data sources
  • 111 – Site template gallery
  • 112 – User Information list
  • 113 – Web Part gallery
  • 114 – List template gallery
  • 115 – XML Form library
  • 116 – Master pages gallery
  • 117 – No-Code Workflows
  • 118 – Custom Workflow Process
  • 119 – Wiki Page library
  • 120 – Custom grid for a list
  • 130 – Data Connection library
  • 140 – Workflow History
  • 150 – Gantt Tasks list
  • 200 – Meeting Series list
  • 201 – Meeting Agenda list
  • 202 – Meeting Attendees list
  • 204 – Meeting Decisions list
  • 207 – Meeting Objectives list
  • 210 – Meeting text box
  • 211 – Meeting Things To Bring list
  • 212 – Meeting Workspace Pages list
  • 300 – Portal Sites list
  • 301 – Blog Posts list
  • 302 – Blog Comments list
  • 303 – Blog Categories list
  • 1100 – Issue tracking
  • 1200 – Administrator tasks list
  • 2002 – Personal document library
  • 2003 – Private document library

SharePoint Debugging: Attach Correct W3WP Process

Being a developer, debugging is necessity. To debug we many times, face that there are more than one W3WP processes in Process list. I was confused that which is the exact process to which I should be debugging.
This process doesn’t contain information about W3WP process like Application Pool details.

W3WP-list

To know more about that process, we need to follow below steps:

  1. Open Command prompt by administrator.
  2. Navigate to folder “C:\Windows\System32\inetsrv” by running following command:
    cd “C:\Windows\System32\inetsrv”
  3. Execute this command:
    appcmd.exe list wp
    It will list down the worker process with process id and application pool name.W3Wp-pool-list

We already have our application pool detail for the site we are debugging. From the above list we should note down the process id and then in Visual studio, attach the process only to that process with specific ID we noted.

Now we are done with “Attach to Process”.
Happy debugging!

Group & Sort by Month in List View Trick

Group by month is very simple task to achieve in SharePoint List View.
Simply create one computed column with formula:

=TEXT([Start Time],"mmmm")

Now Group by that view by this field to view in particular order ascending or descending.

SiteColumnView
As shown above, it will only order item by alphabetically for month keyword, but it will not order as per the month ordering.

So to achieve that add following formula:
=REPT(" ",13-MONTH([Start Time]))&TEXT([Start Time],"mmmm")

SortByMonth

What’s the trick? To force the order, we are adding a bunch of white spaces before the month name. The calculated Month actually contains the following values (each _ represents a white space):
____________January
___________February
__________March

__November
_December

Now, why don’t we see these spaces on the Web page? What makes the magic work is that when you insert multiple spaces in a Web page, the html specification says that

user agents should collapse input white space sequences

That’s it!

Set an Email alert for Document library or List for SharePoint 2013

In this post, I will explain how to add an alert on document library or list to get notified about item added, updated or deleted. Steps to follow for adding an alert:

1. First of all Open List or Library.
2. If it is library then open Documents, or it is List then open Lists ribbon tab. In my example I have taken Document Library.

LibraryTab
3. Now under Share & Track section, search Alert Me option. Click on Set alert on this library

Set Alert Link

4. A dialog box will appear with available options like Alert Title, Send Alerts To, Delivery Method, Change Type, Send Alerts for These Changes, When to Send Alerts.

Alert Dialog Options

5. Apply relevant configuration on dialog and then click OK. And you are done with setting alert.