SharePoint Development: Speed up development with Visual Studio CKSDEV Keyboard Shortcuts

February 19, 2014 Leave a comment

Introduction

Firstly if you are not using the CKSDEV Visual Studio extensions for SharePoint. Then please do yourself a favour and download them NOW!

Wes Hackett and the team have been doing an amazing job to save us time when developing SharePoint solutions.

You can download the Visual studio extension via Visual Studio’s gallery.

Keyboard Shortcuts

I have to say that I was a little late to the 1.2 release which I updated to in November even though it was out in August! Anyway this release is the best yet for SharePoint 2013 and Visual Studio 2012. Finally it includes a SharePoint solution deployment profile to update/upgrade your solutions. Finally, I can throw away my version!

Anyway, I noticed that there were lots more keyboard shortcuts (I am pretty sure these have been there for a while) but I wanted to start making use of them as it really makes life much easier.

Fortunately the CKSDEV development team have a strategy for the shortcut conventions so remembering them is made a little easier.

To recycle a process then the two stage shortcut will always use Alt+R

To attach the debugger to a process then the two stage shortcut will always use Alt + A

So here are the shortcuts which I use the most:-

  • Recycle SharePoint Application Pools
    • Alt+R, A
  • Recycle SharePoint Timer Service
    • Alt R. T
  • Attach debugger to SharePoint Application Pools
    • Alt A, S
  • Attach debugger to SharePoint Timer Service
    • Alt A, T

    This makes life so much easier when you are in the code, debug, fix, code, debug, fix cycle!

Issue applying Workflow Associations to Content Types

November 21, 2013 2 comments

 

Introduction

 

First, let’s set the scene. We have built a solution for a customer with a site collection and within that site collection a sub-web which has a large number of document libraries in it.

For the next release we were looking to setup records management and use the out of the box disposition workflow to allow the customer to decide whether to delete the document or not. The workflow is triggered by an information policy.

The upgrade went well all the feature upgrades worked nicely however then we hit a snag setting up the workflows.

The process of applying a workflow to a content type is pretty straight forward and we did not have any problems with the development, staging or UAT environments. Of course its only when we go to setup in production did we hit a problem.

Applying the workflow to a content type was achieved by doing the following:-

  • Browse to the root of your site collection
  • Click on Site Content –> Settings
  • Click on Site Content Types
  • Click on your content type that you wish to configure
  • Click “Workflow Settings”
  • Click Add a Workflow which takes you into the following screen

addingworkflowtocontenttype

If you look at the image at the bottom of the page you will see the option “Update all content types”, so we set this and clicked Ok.

The page just hung there processing, we left it for a while but still it was hung there. Knowing SharePoint we thought that is fine we’ll leave it. Two hours later still nothing so we started to check the SharePoint Unified Logs and unfortunately we found an error

 

SharePoint Foundation   Database        fa46    High    at Microsoft.SharePoint.SPSqlClient.ExecuteQueryInternal(Boolean retryfordeadlock)     at Microsoft.SharePoint.SPSqlClient.ExecuteQuery(Boolean retryfordeadlock)     at Microsoft.SharePoint.Library.SPRequestInternalClass.GetListsWithCallback(String bstrUrl, Guid foreignWebId, String bstrListInternalName, Int32 dwBaseType, Int32 dwBaseTypeAlt, Int32 dwServerTemplate, UInt32 dwGetListFlags, UInt32 dwListFilterFlags, Boolean bPrefetchMetaData, Boolean bSecurityTrimmed, Boolean bGetSecurityData, Boolean bPrefetchRelatedFields, ISP2DSafeArrayWriter p2DWriter, Int32& plRecycleBinCount)     at Microsoft.SharePoint.Library.SPRequestInternalClass.GetListsWithCallback(String bstrUrl, Guid foreignWebId, String bstrListInternalName, Int32 dwBaseType, Int32 dwBaseTypeAlt, Int32 dwServerTemplate, UInt32 dwGetListFlags, UInt32 dwListFilterFlags, Boolean bPrefetchMetaData, Boolean bSecurityTrimmed, Boolean bGetSecurityData, Boolean bPrefetchRelatedFields, ISP2DSafeArrayWriter p2DWriter, Int32& plRecycleBinCount)     at Microsoft.SharePoint.Library.SPRequest.GetListsWithCallback(String bstrUrl, Guid foreignWebId, String bstrListInternalName, Int32 dwBaseType, Int32 dwBaseTypeAlt, Int32 dwServerTemplate, UInt32 dwGetListFlags, UInt32 dwListFilterFlags, Boolean bPrefetchMetaData, Boolean bSecurityTrimmed, Boolean bGetSecurityData, Boolean bPrefetchRelatedFields, ISP2DSafeArrayWriter p2DWriter, Int32& plRecycleBinCount)     at Microsoft.SharePoint.SPListCollection.EnsureListsData(Guid webId, String strListName)     at Microsoft.SharePoint.SPListCollection.GetListByName(String strListName, Boolean bThrowException)     at Microsoft.SharePoint.Workflow.SPWorkflowAssociation.EnsureUtilityList(SPWeb web, String workflowName, String listTitle, Guid Id, SPListTemplateType templateType, Boolean forceListCreation, String alternateNameRes, String descriptionRes)     at Microsoft.SharePoint.Workflow.SPWorkflowAssociation.EnsureTaskList(SPWeb web, String workflowName, String createTaskListTitle, Guid createTaskListGuid, Boolean forceListCreation)     at Microsoft.SharePoint.Workflow.SPWorkflowAssociationCollection.SetUtilityLists(SPWorkflowAssociation wa, Boolean forceUtilityListCreation)     at Microsoft.SharePoint.Workflow.SPWorkflowAssociationCollection.AddCore(SPWorkflowAssociation wa, Guid id, SPList list, Boolean forceUtilityListCreation)     at Microsoft.SharePoint.Workflow.SPContentTypeWorkflowAssociationCollection.AddCoreCT(SPWorkflowAssociation wa)     at Microsoft.SharePoint.Workflow.SPContentTypeWorkflowAssociationCollection.PushDownAssociation(SPWorkflowAssociation associationTemplate, Boolean bUpdateIfExisting, MethodBase mbChangeEntry)     at Microsoft.SharePoint.Workflow.SPContentTypeWorkflowAssociationCollection.UpdateOrAdd(SPWorkflowAssociation associationTemplate)     at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)     at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)     at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)     at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)     at Microsoft.SharePoint.SPChangeMonitor.ApplyChangesCore(Object ct, Boolean applyAll, Type typeFilter, Boolean bFilterInclude)     at Microsoft.SharePoint.SPContentType.PushDownWorkflowChangesToDerivedCTCore(SPContentType ct, Boolean fCloseWebAsNecessary)     at Microsoft.SharePoint.SPContentType.PushDownWorkflowChangesToListCTs(SPContentTypeCollection cts, IEnumerable`1 cids, Boolean throwOnSealedOrReadOnly)     at Microsoft.SharePoint.SPContentType.PushDownChanges(CodeToPushDownChangesToDerivedCT derivedCTPushdownCode, CodeToPushDownChangesToListCTs listDerivedCTsPushdownCode, Boolean throwOnSealedOrReadOnly, IList`1 exceptions)     at Microsoft.SharePoint.SPContentType.UpdateWorkflowAssociationsOnChildren(Boolean bGenerateFullChangeList, Boolean bPushdownDerivedCT, Boolean bPushdownListCTs, Boolean bThrowOnSealedOrReadOnly)     at Microsoft.SharePoint.WorkflowServices.ApplicationPages.WrkSetngPage.OnClick_Update(Object sender, EventArgs e)     at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)     at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)     at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)     at System.Web.UI.Page.ProcessRequest()     at System.Web.UI.Page.ProcessRequest(HttpContext context)     at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()     at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)     at System.Web.HttpApplication.PipelineStepManager.ResumeSteps(Exception error)     at System.Web.HttpApplication.BeginProcessRequestNotification(HttpContext context, AsyncCallback cb)     at System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)     at System.Web.Hosting.UnsafeIISMethods.MgdIndicateCompletion(IntPtr pHandler, RequestNotificationStatus& notificationStatus)     at System.Web.Hosting.UnsafeIISMethods.MgdIndicateCompletion(IntPtr pHandler, RequestNotificationStatus& notificationStatus)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)     at System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags)

 

The reason for this error was explained in the next log entry which was a little more concise:-

Getting Error Message for Exception System.Web.HttpException (0×80004005): Request timed out

 

So a bit of head scratching and we thought well we should really make this change via PowerShell but the problem is how to do that?

 

Solution

 

Well its funny some of the method calls you see on SharePoint objects. Obviously the guys at Microsoft have seen this issue before. When I was updating the SPContentType I remember seeing the function UpdateWorkflowAssociation() but then there was the much more useful UpdateWorkflowAssociationsOnChildren()!

Thanks to the team at Microsoft – that is just what we were looking for!

The fix was the following piece of PowerShell:-

 

$web = Get-SPWeb [your site collection root web url]; $contentTypeToUpdate = $web.ContentTypes | ?{$_.Name –eq “[Your Content Name Here]”}; $contentTypeToUpdate.UpdateWorkflowAssociationsOnChildren($true, $true, $true, $false);

I used ULSViewer to watch the function running SPSqlClient sessions to see that the process was working correctly and more importantly it wasn’t timing out!

 

To talk through the PowerShell we are doing the following:-

  • Getting the SharePoint web for the root of our site collection which contains the content type to update
  • Get the content type that we need to update
  • Call the UpdateWorkflowAssociationsOnChildrenUpdate()
    • mark all the content as changed = true
    • push down to all derived content types = true
    • push down to all content types that are associated to lists = true
    • throw an error if you encounter a read-only or sealed content type = false

Lessons Learned

 

When you are doing upgrades always try and use a similar sized data set as production!

When it does not work through the UI – bring on the PowerShell!

 

Anyway I hope that helps someone else get themselves out of trouble!

Experiences with SharePoint Disposition Approval Workflow

November 14, 2013 Leave a comment

 

Introduction

 

Recently I have been working on document lifecycle management project. One of the targets for the project was to try and use out of the box (OOB) SharePoint features rather than develop additional components. I am all for this, it reduces support and maintenance overhead and the technical debt of the solution.

The solution ended up implementing a multiple content types with information management policies for auditing and retention policies.

The retention policy had a number of stages which were:-

  • Created date + 1 day make the document into a record
  • Created date + X years execute the “Disposition Approval Workflow”

The number of years would vary depending on the type of document.

Before I go any further I should talk about the Disposition Approval Workflow, this is a workflow which has been in SharePoint since SharePoint 2007 and is made available using the Disposition Workflow feature.

The workflow when run against a document has one step. The step creates a task which presents the user with the option to either delete the document or retain it. The user can also provide comments.

What should happen is that if the user chooses to delete the document then the workflow will delete the document.

However, this fails if the document is declared as a record. Unfortunately the out of the box disposition approval workflow which has been designed to provide a mechanism to delete a document cannot delete a document if its a record.

The workflow displays the following error or words to the effect of “Cannot delete the document”

This was a little frustrating so what do we do?

 

Options

 

After some thought about the problem I came up with two approaches:-

  • redesign the Disposition Approval Workflow to work how we want it to
  • add a step to undeclare the document as a record

Thinking back to one of the key targets, keep the amount of custom development to a minimum, I decided to go for the second option.

Unfortunately, there is no expiration action which allows you to undeclare a record. So I looked at the options to create one.

Fortunately there are a couple of reasonable examples, they might be a little lacking in detail but there is enough to understand the process.

 

Solution

 

So the following solution was built, the solution is made up of the following parts:-

  • A class which implements the IExpirationAction interface and perform the action to undeclare a document as a record
  • A feature which has a feature receiver which adds the IExpirationAction to the PolicyTemplates
    A class UndeclareRecordExpirationAction is created which implements the IExpirationAction interface as follows:-
    The IExpirationAction interface has a function OnExpiration which passes in the SPListItem to delete and the date that the document has expired on.
    The function implementation would be to check that the document is not already on hold and also that the document isn’t a record already.
    if the document is on hold then an exception is raised so that the process goes no further.

Two static functions were created which register / unregister the ExpirationPolicyAction with SharePoint.

 

A feature was created which implemented FeatureActivatation and FeatureDeactivation methods. These call into the appropriate static functions in the UndeclareRecordExpirationAction class.

 

Once the solution is installed and the feature activated then a new policy action appears here:

image

 

To configure the policy do the following:-

  • Browse to the site collection
  • Browse to the site settings page
  • Click Site Content Types
  • Click on the content type that you wish to apply the policy to
  • Click on “Information Management Policy settings”
  • Click “Define a policy..”
    • Click Ok
    • Click Enable Retention
    • Add a retention stage…

    The information policy was modified so that it has the following steps:-

    Created + 1 day = Declare record (reoccurrence 1 month)

 

    Created + 6 Years = Undeclare Record (reccurrence 1 year)

 

    Created + 6 Years = Start Workflow (reoccurence 1 year)

The option to specify how to manage retention on records was set that the same policy was used for both records and non-records.

I set the reoccurrence for the Declare record action to one month so that if a document was undeclared and then the record managers decided not to delete the document through the workflow it would then picked up again.

 

Testing the solution

The process of testing these expiration policies was a little tricky so I will cover the method that used. Information policies are applied by timer jobs. The following timer jobs are used:-

  • Information Management Policy Timer Job
  • Expiration Timer job

The expiration timer job does the actual work of applying/running the various steps of a retention policy. By default it runs once a week in SharePoint 2013.

To speed things up I did the following to test/debug the solution.

  • Compile the assembly hosting our UndeclareRecordExpirationAction class as a debug build.
  • Deploy the solution
  • Restart SharePoint Timer Service
  • Attach the Visual Studio debugger to the “owstimer.exe” process
  • From Central Admin, start the timer job through the monitoring->review job definintions
  • Browse to the Expiration Policy Job Definitions
  • Click on the “Expiration policy” link for the one associated to the Web Application where your application is hosted and click “Run now”
  • Wait for the visual studio debugger to hit the breakpoint

If you are having problems getting the debugger to hit the breakpoint then:-

  • Start the SharePoint Management Shell
  • From within the PowerShell session
  • restart the owstimer service using Restart-Service sptimerv4
  • restart IIS using iisreset

Improvements

 

The only thing that I may look to do is rather than have two stages for “Undeclare record” and “Starting a workflow” is merge them into two and have a “undeclare record and start workflow action” so that there is less delay with the processing.

 

Conclusion

 

I hope people find this useful, please let me know if you do.

 

Here are links to the code samples:-

ITSP.SP.Policy.UndeclareRecordAction.zip

PowerShell Script to Restart SharePoint 2013 Farm services

October 30, 2013 Leave a comment

 

Introduction

 

A while back I wrote a quick script to ‘Restart services on a SharePoint 2010 Farm’, this blog post can be found here.

 

Anyway, I have slightly updated it for SharePoint 2013. Its pretty much the same though I am also restarting the Search process too and also checking that the service exists on the server before restarting.

How you find it useful

 

The Script

 

Here is the script:-

 <pre>
param
(
    [Parameter(Mandatory=$false, HelpMessage='-ServiceNames Optional, provide a set of service names to restart.')]
    [Array]$ServiceNames=@("SharePoint Timer Service","SharePoint Administration", "SharePoint Server Search 15", "World Wide Web Publishing Service","IIS Admin Service")
);

Write-Host "Attempting to get SharePoint Servers in Farm" -ForegroundColor White;
$farm = Get-SPFarm;
$servers = $farm.Servers;
Write-Host "Found" $servers.Count "Servers in Farm (including database servers)" -ForegroundColor White;
foreach($server in $servers)
{
    if($server.Role -ne [Microsoft.SharePoint.Administration.SPServerRole]::Invalid)
    {
        Write-Host "Attempting to restart services on" $server.Name -ForegroundColor White;
        foreach($serviceName in $ServiceNames)
        {
            $serviceInstance = Get-Service -ComputerName $server.Name -Name $serviceName -ErrorAction SilentlyContinue;
            if($serviceInstance -ne $null)
            {
                Write-Host "Attempting to restart service" $serviceName ".." -ForegroundColor White -NoNewline;
                try
                {
                    $restartServiceOutput="";
                    Restart-Service -InputObject $serviceInstance;
                    Write-Host " Done!" -ForegroundColor Green;
                }
                catch
                {
                    Write-Host "Error Occured: " $_.Message;
                }
            }
        }
    }
}
</pre>

Download the script here: Restart-SPServices2013.zip

Building a SharePoint 2013 Search Refiner with Custom Intervals

September 27, 2013 18 comments

Introduction

SharePoint 2013 Search has really improved over its SharePoint 2010 predecessor. These improvements are down to the integration of the FAST search feature set into SharePoint 2013.

One of the nice features is the slider graph refiner which gives a visual representation of the results that can be filtered. However, unfortunately it doesn’t work well for custom managed properties.

Here is the refiner using the out of the box Last Modified Managed Property

clip_image002

Here is the refiner using a custom Date Time Managed Property called Timeline (this is the date of the document).

clip_image004

As you can see the date range is only for the last year, the numbers have commas in them and as the following image shows the descriptions for refining the data between the different intervals does not really make sense.

clip_image006

In a recent project this led to the decision to use a normal text refiner over the slider bar graph. However, the user base asked for the refinement options to be changed to a custom set of values. The out of the box date time refinement has the following options:-

· Last Year

· Last Six Months

· Last Month

· Last Week

· Last day

However the requirement was to have a custom set of refinements as shown below:-

timeline_datetime_refiner

Investigation

So to achieve the requirement above we need be able to do two things:-

· Configure how the refiner web part calculates the additional refiners

· Configure the text being used to display the refinement options to the user

How to configure the refinement calculations

The first thing that I did was have a look and see if there was anyone else who had tackled this issue and unfortunately I didn’t come up with much on MSDN or out there on the web.

The next step was to start looking at the customisation options for the web part.

By editing the web part properties and clicking on the “Choose Refiners” button you can decide which managed properties are going to be refinement options. Microsoft have given quite a lot of flexibility to custom the refiners but these options are not available for date/time data types . There are more options for the other data types such as text or number.

For example a managed property which is based on a number gives you the opportunity to create manual intervals to refine by.

clip_image007

However, a refiner based on a date/time data type doesn’t have much flexibility. This is probably easier to see via a screenshot.

clip_image009

There is an option to define the dates in the search schema but when that option is select then you get the following error message.

clip_image011

So this leads to the question what do I do now?

Quite often with web parts I start looking at the actual web part xml definition to try and workout if there are any appropriately named properties or values. So I exported the web part and opened up the web part in notepad.

After a lot of looking about I found the following web part property, “SelectedRefinementControlsJson”:-

clip_image013

This property contains a JSON string which defines the refinement control configuration. For each refiner that is selected a set of properties are stored within this string, these include properties such as

· sortBy

· sortOrder

· maxNumberOfRefinementItems

· DisplayTemplate

· etc

However, there were two properties which has interesting names and they were:-

clip_image015

clip_image017

I presumed that I could change the useDefaultDateIntervals to false and then provide some sort of JSON object for the intervals property. However, the difficult was trying to work out what the intervals structure would look like!

I started to debug the refiners using the Internet Explorer Developer Toolbar but didn’t really find much to help reverse engineer the process.

The approach that I quite often take is to examine the .NET code using a tool like Reflector. So it was time to reflect the appropriate web part. The refinement web part is of type:-

· Microsoft.Office.Server.Search.WebControls.RefinementScriptWebPart

After some searching I found the appropriate code.

The ResultScriptWebPart has a private method called GetRefinementControls() this instatiates another class called RefinementControl. A RefinementControl object is created for each Refinement Control JSON object and part of that object looks at the useDefaultDateIntervals property and if this has been set then the GetDefaultDateIntervalSpecString() is loaded.

clip_image019

The function GetDefaultDateIntervalSpecString() gives the clue of how the intervals parameter should be formatted.

clip_image021

So the intervals are basically an array of integers so the representation of this in JSON is the following:-

clip_image023

And of course to ensure that the custom intervals are loaded we need to change the useDefaultDateIntervals property to false.

clip_image025

So just to go back the intervals that have been set for the refiners are the number of days that should be removed from todays date to create the interval. The intervals -1065,-730,-365,-183,-30,-7, 0 translates to the less than 3+ years, 2-3 years, 1-2 years, 6 months to 1 year, 1-6 months, 1 week – 1 month and today.

So now we are able to control the refinement calculations, the next step is how to configure the labels displayed to the user.

If we don’t configure the labels we get the following being displayed to the user, which is obviously not good enough.

How to configure the refinement labels

Now I haven’t found a simpler solution for this but if anyone finds an alternative solution which for example overrides a particular web part property then please let me know.

The approach that I took in the end was to create my own filter display template. I haven’t covered display templates in my blog as yet. I am planning a post to discuss my findings with SharePoint 2013 Search development soon. However, the following articles provide some good information.

Anyway, display templates are found in the master page catalog document library which can be found at http://sharepoint/_catalogs/masterpage/displaytemplates. An alternate method to browse to this list is by going to the SharePoint site collection, click Site settings cog icon -> Site Settings->Master Pages and Page Layouts (under the Web Designer Galleries section).

All the out of box refinement filters can be found under the DisplayTemplates/Filters folder. I downloaded the Filter_Default.html file which is used as the standard out of the box text refinement filter. The file was renamed the file to Filter_CustomDateTime.html and edited in Visual Studio.

Here is an example of the contents of the Display Template

clip_image027

The <head> tag was updated to give a new title and then the following script was added which will go and set the labels presented to the end user. The JavaScript was added after all the default label data has been loaded, this was to ensure the custom configuration was not overwritten.

clip_image029

The display template was loaded back into SharePoint, I suggest that you put it in a custom folder and use a Module to deploy the file. In my example I am putting the filter in the following directory, Display Templates/iThinkSharePoint/.

Now we have the custom display template and we have configured our web part to use custom intervals there is one last step.

Can you guess what it is?

So we need to tell the web part to use our custom filter display template, this is another modification of the web part property, SelectedRefinementControlsJson. With some care look through the JSON string and find the refinement configuration for our custom Managed Property.

clip_image031

Now the web part configuration can be saved and uploaded into SharePoint as a new web part in the web part gallery.

Solution

So to recap the final solution has the following components:-

· Custom Web Part Configuration which includes the custom intervals, references the custom display template

· Custom Display Template for the Refinement control

This creates the following refiner:-

timeline_datetime_refiner

You can download the example Display Template and Web Part Configuration XML file from here:-

ITSPSearchRefineCustomIntervals.zip

If you find this useful please let me know and please ask if you need some more clarification.

SharePoint 2013 Search: Keep getting Search Results even when there is no query made

August 20, 2013 7 comments

Introduction

This is a quick one which caused me some problems on a project I have been working on.

So a quick introduction to SharePoint 2013 Search. SharePoint 2010 had a feature in search called “Search Scopes” this provided a way to select the content that you wanted to return results from based on certain criteria. For example if it had a certain Content Type or was found in a particular location.

In SharePoint 2013 Scopes have been replaced by Result Sources which provide the same feature plus some much more powerful selection criteria using tokens. For example you can retrieve the user performing the search and return content where the user is the author.

Problem

The problem is that I have a search page which has both the search query web part and a search results web part.

After setting up a custom Result Source query to refine the results down I would always get results displaying, even before a query had been submitted search.

The Result Source is configured by:-

  • Browsing to the Site Collection
  • Click on the Site Settings Icon
  • Choose Site Settings->Site Collection Administration->Search Result Sources
  • Create a New Result Source
  • Part of the setup is to create the Query Transform, this brings up the window below

Here is what was setup:-ThisQueryAlwaysReturnsResults

The query always returns search results. Normally results only appear when you click on the Test tab, providing the search query and click Test Query.

This is a problem as because the search will always execute as the user goes on the page and is just plain messy.

So I spent sometime trying to work out what was going on.

Solution

I have to say the solution took sometime and it was only after re-reading the following Technet article http://technet.microsoft.com/en-us/library/dn186229.aspx#BKMK_How_does_query_transform_affect_query the section at the bottom “Narrowing search results by using a Query Transform” gave me the answer.

The key to all of this is that my query is not waiting for the search term before executing the search, it just always executes the search.

The example that the article provides is this:-

{?{searchTerms} ContentClass=urn:content-class:SPSPeople}

So that gave me the solution, the important thing is that if you want the query to wait for search terms to be filled in then wrap your query with curly brackets.

So the problem query goes from this:-

{searchTerms} (IsDocument=True AND (ContentTypeId:0x0101009CA89B0104F04692A106A1F88E847F7D*))

to this:-

{?{searchTerms} (IsDocument=True AND (ContentTypeId:0x0101009CA89B0104F04692A106A1F88E847F7D*))}

When I use the query above with the Query Transform this is the result, note the query returns no results.

ThisQueryWaitsforQueryBeforeReturnsResults

The query that I have will take any query and ensure that only search results that are documents that have a ContentTypeId which starts with a particular value.

I hope that helps someone!

PowerShell to Restart SharePoint Farm Windows Services

April 19, 2013 1 comment

Introduction

One of the steps that I suggest when deploying upgrades to SharePoint solutions is before you do a Solution upgrade restart all the SharePoint related services.

So in a SharePoint 2010 Farm that would be:-

  • SharePoint Administration Service
  • SharePoint Timer Service
  • World Wide Web Publishing Service
  • IIS Admin Service
  • Web Analytics Service
    The reason is that certain processes (i.e. SharePoint Timer Service) can lock assemblies and cause solution deployment to fail.

However this step is a pain in the ass when you have a more than one server!

To help ease the pain here is a PowerShell script which will loop through all the servers on the farm (ignore the database servers) and restart the appropriate services.

The great thing about this script is it will also ensure that services that are required to be running are also running such as the SharePoint Administration Service!

The Script

param
(
	[Parameter(Mandatory=$false, HelpMessage='-ServiceNames Optional, provide a set of service names to restart.')]
	[Array]$ServiceNames=@("SharePoint 2010 Timer","SharePoint 2010 Administration","IIS Admin Service","World Wide Web Publishing Service")
);

Write-Host "Attempting to get SharePoint Servers in Farm" -ForegroundColor White;
$farm = Get-SPFarm;
$servers = $farm.Servers;
Write-Host "Found" $servers.Count "Servers in Farm (including database servers)" -ForegroundColor White;
foreach($server in $servers)
{
	if($server.Role -ne [Microsoft.SharePoint.Administration.SPServerRole]::Invalid)
	{
		Write-Host "Attempting to restart services on" $server.Name -ForegroundColor White;
		foreach($serviceName in $ServiceNames)
		{
			$serviceInstance = Get-Service -ComputerName $server.Name -Name $serviceName -ErrorAction SilentlyContinue;
			if($serviceInstance -ne $null)
			{
				Write-Host "Attempting to restart service" $serviceName ".." -ForegroundColor White -NoNewline;
				try
				{
					$restartServiceOutput="";
					Restart-Service -InputObject $serviceInstance;
					Write-Host " Done!" -ForegroundColor Green;
				}
				catch
				{
					Write-Host "Error Occured: " $_.Message;
				}
			}
		}
	}
}

Notice you can extend the Services that are restarted by adding/removing service names to the array parameter $ServiceNames.

Hope that helps.

%d bloggers like this: