Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts

Wednesday, March 22, 2017

Finding Alias for SharePoint Email Enabled Lists

As usual, there are several ways to do this that can be readily found via a search

Powershell: Loop through each Web Application, Site Collection (SPSite), Subweb (SPWeb), List. Then look in the EmailAlias property for what you are searching. In large environments, I suspect that this would be very slow and resource intensive. Here is a Foreach-Object pipeline that would do the trick:

Get-SPWebApplication | ForEach-Object {$_.Sites} | ForEach-Object {$_.AllWebs} | ForEach-Object {$_.Lists} | Where-Object {$_.CanReceiveEmail -and $_.EmailAlias} | Format-Table EmailAlias, Title, ParentWebUrl -AutoSize


SQL: One way is to essentially do the above but via the content databases, but this one also seems resource intensive:

USE [Some_Content_DB]
SELECT tp_Title, tp_EmailAlias, FullUrl
  FROM [dbo].[AllLists] lists
  LEFT JOIN [dbo].[AllWebs] webs ON lists.tp_WebId = webs.Id
  WHERE tp_EmailAlias IS NOT NULL

SQL: I decided to see what the Microsoft SharePoint Foundation Incoming E-Mail timer job does (job-email-delivery) since the timer job should be quite fast. Looking at the code, I can see that it calls the proc_getEmailEnabledListByAlias stored procedure. Diving into that, I see that this may be a better query:

SELECT * FROM [SharePoint_Config].[dbo].[EmailEnabledLists] 


However, I did also run across a post mentioning that it is possible the Config database and the Content database can be out of sync. So, it may still be necessary to choose the correct method depending on the problem one is trying to tackle.

Wednesday, November 23, 2016

The field with Id {field-GUID} defined in feature {feature-GUID} was found in the current site collection or in a subsite.

One of my site collection features is failing to activate and throws this exception:

SPException thrown: Message: The field with Id {field-GUID} defined in feature {feature-GUID} was found in the current site collection or in a subsite.. Stack:   
 at Microsoft.SharePoint.Utilities.SPUtility.ThrowSPExceptionWithTraceTag(UInt32 tagId, ULSCat traceCategory, String resourceId, Object[] resourceArgs)    
 at Microsoft.SharePoint.Administration.SPElementDefinitionCollection.ProvisionFieldsAndContentTypes(SPFeaturePropertyCollection props, SPSite site, SPWeb web, SPFeatureActivateFlags activateFlags, Boolean fForce)    
 at Microsoft.SharePoint.Administration.SPElementDefinitionCollection.ProvisionElements(SPFeaturePropertyCollection props, SPWebApplication webapp, SPSite site, SPWeb web, SPFeatureActivateFlags activateFlags, Boolean fForce)    
 at Microsoft.SharePoint.SPFeature.Activate(SPSite siteParent, SPWeb webParent, SPFeaturePropertyCollection props, SPFeatureActivateFlags activateFlags, Boolean fForce)    
 at Microsoft.SharePoint.SPFeatureCollection.AddInternal(SPFeatureDefinition featdef, Version version, SPFeaturePropertyCollection properties, SPFeatureActivateFlags activateFlags, Boolean force, Boolean fMarkOnly)    
 at Microsoft.SharePoint.SPFeatureCollection.AddInternalWithName(Guid featureId, Int32 compatibilityLevel, String featureName, Version version, SPFeaturePropertyCollection properties, SPFeatureActivateFlags activateFlags, Boolean force, Boolean fMarkOnly, SPFeatureDefinitionScope featdefScope)    
 at Microsoft.SharePoint.WebControls.FeatureActivator.ActivateFeature(Guid featid, Int32 compatibilityLevel, SPFeatureDefinitionScope featdefScope)    
 at Microsoft.SharePoint.WebControls.FeatureActivatorItem.ToggleFeatureActivation()    
 at System.Web.UI.WebControls.Button.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)  


I found a lot of references out there saying to redeploy the solution or use Overwrite="TRUE" in the field definition. However, not satisfied with either, I dug deeper.

I put this powershell together to figure out where the fields are coming from:

$siteUrl = 'site-collection-url'
$fieldId = 'field-GUID'
$fieldInternalName = 'field-internal-name'

$site = Get-SPSite $siteUrl
$webFields = @()
foreach ($web in $site.AllWebs) {
  foreach ($field in $web.Fields) {
    $webField = New-Object PSObject -Property ([ordered]@{
      WebUrl = $web.Url
      FieldId = $field.Id
      FieldInternalName = $field.InternalName
      FieldTitle = $field.Title
    })
    $webFields += $webField
  }
}
$webFields | Where-Object {$_.FieldId -eq $fieldId -or $_.FieldInternalName -eq $fieldInternalName} | Format-Table -AutoSize

From the results, I found 2 subwebs that contained this same definition. It looks like these subwebs were migrated into that site collection. Is is possible that this was done before the site collection feature was activated. The migration process must have created the fields at the subweb level.

Going to each of the subwebs listed by the powershell, I was able to go to Site Settings->Site Columns, locate my field, and delete it, Once these were deleted, I was able to activate my site collection feature.






Throttled:Query exceeds lookup column threshold

One of my apps gets its data via lists.asmx. In a particular environment, no data was being returned and I found these entries in ULS:

Throttled:Query exceeds lookup column threshold. List item query elapsed time: 0 milliseconds, Additional data (if available): Query HRESULT: 80070093 List internal name, flags, and URL: {list-guid}, flags=0x0008000000c4108c, URL="web-url/_vti_bin/lists.asmx" Current User: {some-id} Query XML: "<Query><OrderBy><FieldRef Name="ContentType"/></OrderBy></Query>" SQL Query: "N/A"

The query cannot be completed because the number of lookup columns it contains exceeds the lookup column threshold enforced by the administrator.

Query exceeds lookup column threshold. List: {list-guid}, View: , ViewXml: <View Scope="RecursiveAll" IncludeRootFolder="True"><Query><OrderBy><FieldRef Name="ContentType" /></OrderBy></Query><ViewFields>... and a whole ton of <FieldRef> entries.


SOAP exception: Microsoft.SharePoint.SPQueryThrottledException: The query cannot be completed because the number of lookup columns it contains exceeds the lookup column threshold enforced by the administrator. ---> System.Runtime.InteropServices.COMException (0x80070093): The query cannot be completed because the number of lookup columns it contains exceeds the lookup column threshold enforced by the administrator.    


I found a few references to this, but it is not the more common 5000 item List View Threshold throttling. Instead this is the List View Lookup Threshold setting of 8 (12 in SharePoint 2013).

It turns out that my app is using the default view and not specifying which fields to return in the query. In fact, there is a Level=Medium ULS log entry that has my exact query. Putting this into powershell as follows, I was able to confirm the behaviour:

$webUrl = 'some-web-url'
$listName = '{list-guid}' # note: keep the curly braces

$credential = Get-Credential -Message "Enter your login for $($webUrl)"

$uri = [uri]"$($communityRoot)/_vti_bin/lists.asmx"

$contentType = 'text/xml'
$bodyString = @"
<?xml version="1.0" encoding="utf-8"?>
  <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
    <soap12:Body>
      <GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
        <listName>$($listName)</listName>
        <viewName></viewName>
        <rowLimit>5000</rowLimit>
        <query>
          <Query xmlns="">
            <OrderBy> <FieldRef Name="ContentType" /> </OrderBy>
          </Query>
        </query>
      <viewFields><ViewFields xmlns="" /></viewFields>
      <queryOptions>
        <QueryOptions xmlns="http://schemas.microsoft.com/sharepoint/soap/">
          <IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>
          <IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls>
          <ViewAttributes Scope='RecursiveAll' IncludeRootFolder='True' />
          <DateInUtc>TRUE</DateInUtc>
        </QueryOptions>
      </queryOptions>
    </GetListItems>
  </soap12:Body>
</soap12:Envelope>
"@

$result = Invoke-WebRequest -Credential $credential -Method Post -Uri $uri -Body $bodyString -ContentType $contentType
$result.RawContent


To confirm the view and the number of lookup columns, I used this powershell:

$webUrl = 'some-web-url'

$web = Get-SPWeb $webUrl
$list = $web.Lists['Shared Documents']
$fields = $list.Fields
$defaultViewXml = [xml]$list.DefaultView.GetViewXml()
Write-Output "Default View: $($list.DefaultView.Title)"
$defaultViewXml.View.ViewFields.FieldRef | Format-Table @{l="Type"; e={$fields.GetField($_.Name).TypeDisplayName}}, Name -AutoSize -Wrap


Reference: This is a very well written article on GetListItems - https://msdn.microsoft.com/en-us/library/websvclists.lists.getlistitems(v=office.14).aspx





Wednesday, October 7, 2015

SPBasePermissions enumeration - values in Int64, Hexadecimal, and Name


$t = [type]'Microsoft.SharePoint.SPBasePermissions'
[enum]::GetValues($t) | ForEach-Object {Write-Host "$($_): $([int64]$_) (0x$([Convert]::ToString([int64]$_,16)))"}

Haven't figured out a way to use Format-Table for this, but good enough for now.

Saturday, July 4, 2015

A potentially dangerous Request.Path value was detected from the client (%)

Recently came across an issue with an error like the following:
Application error when access {some-url}, Error=A potentially dangerous Request.Path value was detected from the client (%).
at System.Web.HttpRequest.ValidateInputIfRequiredByConfig()
at System.Web.HttpApplication.PipelineStepManager.ValidateHelper(HttpContext context)

Looking more carefully at the URL, it turned out there was a %2520 in it. That is there was a space in the URL which was encoded into a %20, but then some errant code encoded it again into %2520.

What was tricky about this issue that I never saw my endpoint request actually get logged in ULS. Instead, it looked like this was caught by .NET. 

Tuesday, May 5, 2015

Hacking SPRoleDefinition SPRoleType in the database

If you are a Site Collection Administrator, SharePoint allows you to go to a Site Collection, Site Actions->Site Permissions->Permission Levels, then edit a permission level and delete it.

Some predefined Permission Levels (SPRoleDefinition) have a Type (SPRoleType) defined. This is not visible via the UI. However you can get this via Powershell as follows:

$web = Get-SPWeb your-web-url
$web.RoleDefinitions | Format-Table Id, Name, Type, Hidden -AutoSize

This gives output like the following:

        Id Name                       Type Hidden
        -- ----                       ---- ------
1073741829 Full Control      Administrator  False
1073741828 Design              WebDesigner  False
1073741827 Contribute          Contributor  False
1073741826 Read                     Reader  False
1073741825 Limited Access            Guest   True

Now, if you delete one of these such as the Contribute and then decide to recreate it, the type is now "None". There is no way to make the Type "Contributor".

This is all fine, but if you have some code that calls Microsoft.SharePoint.SPRoleDefinitionCollection.GetByType then your code is now broken.

To "resolve" (using the term very loosely as I do not know if there are any implications), I was able to restore this by hacking the database directly.

Essentially, I looked into the Roles table in the WSS_Content database, filtered on the WebId and RoleId and set the Type column directly in the database. Is it a good idea? Who knows? It seemed to work for me, but I do not know what I may have broken as a result of this.





Wednesday, November 5, 2014

The query cannot be completed because the number of lists in the query exceeded the allowable limit.

I have recently come across an error where our code is calling GetSiteData with a query and was returning this error:
The query cannot be completed because the number of lists in the query exceeded the allowable limit. For better results, limit the scope of the query to the current site or list or use a custom column index to help reduce the number of lists.
I then built the following powershell to mimic our code in order test it:

$web = Get-SPWeb some-url

$query = New-Object Microsoft.SharePoint.SPSiteDataQuery
$query.Webs = '<Webs Scope="Recursive">'
$query.Query = "<Where><And><Eq><FieldRef Name='_ModerationStatus' /><Value Type='Number'>0</Value></Eq><BeginsWith><FieldRef ID='{03e45e84-1992-4d42-9116-26f756012634}' /><Value Type='Text'>0x0110</Value></BeginsWith></And></Where><OrderBy><FieldRef Name='PublishedDate' Ascending='FALSE' /></OrderBy>"
$query.ViewFields = '<FieldRef Name="_ModerationStatus"/><FieldRef Name="Title"/><FieldRef Name="ID" /><FieldRef Name="Permalink"/><FieldRef Name="PublishedDate"/><FieldRef Name="Body"/><FieldRef Name="NumComments"/><FieldRef Name="Author"/><FieldRef Name="ContentType"/><FieldRef Name="ContentTypeId"/>'
$query.Lists = "<Lists BaseType='0'/>"
$query.RowLimit = [uint32]::MaxValue

$web.GetSiteData($query)


From what I have read about the call to GetSiteData, when SharePoint performs the query, it takes into consideration the lists that match the criteria passed in the query. It then returns a DataTable with a limit of RowLimit rows. However, since we have not set a MaxListLimit the query simply fails at 1000 lists (instead of giving you the first 1000). There is a parameter we can change in the code $query.Lists = "<Lists BaseType='0' MaxListLimit='0'>" which will allow the query to consider over 1000 lists, however, I am not sure about the performance impact.

References:
SPWeb.GetSiteData method
SPSiteDataQuery.Lists property - see description of MaxListLimit


Monday, November 3, 2014

SharePoint picture library not generating thumbnail and websize images

I recently came across a problem in a customer's site where the thumbnail and websize version of an image was not being generated. Typically when you upload an image to a picture library, a thumbnail and a websize version of that image are generated by SharePoint and saved into the /_t/ and /_w/ subfolders. For example, if upload an image to /Shared Pictures/image.jpg, then SharePoint also automatically generates /Shared Pictures/_t/image_jpg.jpg and /Shared Pictures/_w/image_jpg.jpg

For some reason, this was not happening. When you view the picture library with the default view, all the pictures were showing a blank image (since they use the thumbnail version).

Reaching out to Microsoft Support, it turns out that for these libraries, the parent SPWeb had the ParserEnabled property set to false.

The MSDN description of the SPWeb.ParserEnabled Property is quite useless.

Fortunately, I found a blog discussing this: http://neels-indites.blogspot.ca/2012/06/sharepoint-spweb-property-parserenabled.html. According to this blog, having ParserEnabled=false will cause the following:

  • Cannot search in document library using Office document properties
  • When you upload an image file, the thumbnail and websize images will not be generated
  • When you save a list template, you will not see it in the list template gallery.





Thursday, October 2, 2014

Lists.asmx GetListCollections and GetListItems example

I recently had to get all items of a list as well as all lists in a SPWeb. This involved calling Lists.asmx. For the service description of Lists.asmx just go to /_vti_bin/lists.asmx

Get all lists for some SPWeb

$webUrl = 'some-web-url'

$credential = Get-Credential -Message "Enter your login for $($webUrl)"

$uri = [uri]"$($webUrl)/_vti_bin/lists.asmx"

$contentType = 'text/xml'
$bodyString = @"
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<GetListCollection xmlns="http://schemas.microsoft.com/sharepoint/soap/" />
</soap12:Body>
</soap12:Envelope>
"@

$result = Invoke-WebRequest -Credential $credential -Method Post -Uri $uri -Body $bodyString -ContentType $contentType
$xml = [xml]$result.Content
$xml.Envelope.Body.GetListCollectionResponse.GetListCollectionResult.Lists.List

Get all list items for some list

$webUrl = 'some-web-url'
$listName = 'some-list-name'

$credential = Get-Credential -Message "Enter your login for $($webUrl)"

$uri = [uri]"$($webUrl)/_vti_bin/lists.asmx"

$contentType = 'text/xml'
$bodyString = @"
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<GetListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<listName>$($listName)</listName>
<viewName></viewName>
<rowLimit>5000</rowLimit>
<query>
<Query xmlns="">
<OrderBy> <FieldRef Name="ContentType" /> </OrderBy>
</Query>
</query>
<viewFields><ViewFields xmlns="" /></viewFields>
<queryOptions>
<QueryOptions xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>
<IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls>
<ViewAttributes Scope='RecursiveAll' IncludeRootFolder='True' />
<DateInUtc>TRUE</DateInUtc>
</QueryOptions>
</queryOptions>
</GetListItems>
</soap12:Body>
</soap12:Envelope>
"@

$result = Invoke-WebRequest -Credential $credential -Method Post -Uri $uri -Body $bodyString -ContentType $contentType
$xml = [xml]$result.Content
$xml.Envelope.Body.GetListItemsResponse.GetListItemsResult.listitems.data.ItemCount
$xml.Envelope.Body.GetListItemsResponse.GetListItemsResult.listitems.data.row | Format-Table ows_LinkFilename, ows_Author, ows_Created, ows_Modified -AutoSize

I could probably use New-WebServiceProxy and skip all the SOAP envelope stuff. However, this better mimics the code that I was trying to troubleshoot.


Monday, May 26, 2014

The solution cannot be deployed. The feature 'some-feature-id' uses the directory "some-directory" in the solution

I recently came across this error when trying to deploy a WSP:
The solution cannot be deployed.  The feature 'some-feature-id' uses the directory "some-directory" in the solution. However, it is currently installed in the farm to the directory "some-other-directory". Uninstall the existing feature before you install a new version of the solution.

Simple enough, I tried to do an Uninstall-SPFeature as well as Uninstall-SPFeature -Force both of which did not help. Finally someone tried stsadm -o uninstallfeature and then the subsequent WSP deploy worked. I guess Powershell and stsadm are not quite equivalent


Calling private member using reflection in Powershell

Often I have to put together some Powershell scripts for troubleshooting. These scripts are based on some c# code. Recently, I had to mimic the behaviour of a call to a private member overload of GetTags in the Microsoft.Office.Server.SocialData.SocialTagManager class.

$site = Get-SPSite my-site-url
$context = Get-SPServiceContext($site)
$socialTagManager = New-Object -TypeName Microsoft.Office.server.SocialData.SocialTagManager -ArgumentList $context

# Get the type definition
$type = [type]'Microsoft.Office.Server.SocialData.SocialTagManager'

# List the GetTags members
($socialTagManager | Get-Member GetTags).Definition.Replace("), ", ")`n")

This results in (just the public members):
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(Microsoft.Office.Server.UserProfiles.UserProfile user)
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(Microsoft.Office.Server.UserProfiles.UserProfile user, int maximumItemsToReturn)
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(Microsoft.Office.Server.UserProfiles.UserProfile user, int maximumItemsToReturn, int startIndex)
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(System.Uri url)


Now use Reflection

# Which methods to list
$bindingFlags = [Reflection.BindingFlags] "Default,NonPublic,Instance"

# List the methods
$type.GetMethods($bindingFlags) | Where-Object {$_.Name -eq 'GetTags'} | ForEach-Object {$_.GetParameters() | Select-Object Member -First 1}

This results in (both public and private members);
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(System.DateTime, System.DateTime)
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(System.DateTime, System.DateTime, Int32)
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(System.DateTime, System.DateTime, Int32, Int32)
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(System.Uri, Microsoft.Office.Server.UserProfiles.UserProfile, System.Nullable`1[System.DateTime], System.Nullable`1[System.DateTime])
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(System.Uri, Int32)
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(System.Uri, Int32, Microsoft.Office.Server.SocialData.SocialItemPrivacy)
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(Microsoft.SharePoint.Taxonomy.Term[], Int32, Microsoft.Office.Server.SocialData.SocialItemPrivacy)
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(Microsoft.Office.Server.UserProfiles.UserProfile, Int32, Int32, Boolean, System.Nullable`1[System.DateTime], System.Nullable`1[System.DateTime])
Microsoft.Office.Server.SocialData.SocialTag[] GetTags(Microsoft.Office.Server.UserProfiles.UserProfile, Int32, Int32, Boolean, System.Nullable`1[System.DateTime], System.Nullable`1[System.DateTime], System.Nullable`1[System.Guid])


Now to call a private member. Let's call: Microsoft.Office.Server.SocialData.SocialTag[] GetTags(System.DateTime, System.DateTime, Int32, Int32)


$startTime = [DateTime]'2014-05-01 00:00:00'
$endTime = [DateTime]'2014-05-31 00:00:00'
$maximumItemsToReturn = 1000
$startIndex = 0
$typeList = @([type]'DateTime', [type]'DateTime', [type]'Int32', [type]'Int32')
$method = $socialTagManager.GetType().GetMethod('GetTags', $bindingFlags, $null, $typeList, $null)
$terms = $method.Invoke($socialTagManager, [Object[]] @($startTime, $endTime, $maximumItemsToReturn, $startIndex))
$terms | Format-Table @{l='Term';e={$_.Term.Name}}, Title -AutoSize




Tuesday, April 1, 2014

SharePoint Timezone Settings

I recently had to troubleshoot some SharePoint Timezone issues. There are a bewildering number of places where this may be a factor:

These are nicely summarized at http://www.techgrowingpains.com/2012/05/sharepoint-time-zone-confusion-2/

  • Web Application Level
    • Central Administration->Manage Web Applications
    • Select your web application
    • Select General Settings
    • Default Time Zone: Select time zone
  • Site Collection Level
    • Go to your site collection
    • Site Actions->Site Settings->Regional Settings
    • Select time zone
  • User Level
    • Welcome menu (aka Personal menu, aka the menu with your name on it)->My Settings->My Regional Settings
    • Uncheck Always follow web settings (if checked)
    • Select time zone


There is also
  • Server time zone (across all farm servers)
  • Desktop time zone

Wednesday, June 5, 2013

0x80070002 when adding web part using Powershell

I was adding a webpart using this powershell:
$webpart = New-Object Microsoft.SharePoint.WebPartPages.SilverlightWebPart
$wpm = $web.GetLimitedWebPartManager($page.Uri.OriginalString, "Shared")
$wpm.AddWebPart($webpart, 'Header', 0)

... and got this error:

Exception calling "AddWebPart" with "3" argument(s): "<nativehr>0x80070002</nativehr><nativestack></nativestack>"
At line:1 char:16
+ $wpm.AddWebPart <<<< ($webpart, 'Header', 0)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException


It turns out that my $page was the wrong one which was not checked out nor editable at the time.

Listing a page's web part zones

I have been trying to figure out a way to list all of a page's web part zones. There is not much documentation out there on this. Here's what I have been able to figure out. It is for a publishing web, but the procedure should be pretty much the same.

$myweburl
$mylayouttitle
$web = Get-SPWeb $myweburl
$pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
$layout = $pWeb.GetAvailablePageLayouts() | Where-Object {$_.Title -eq $mylayouttitle}
$layout.ListItem.Properties['vti_cachedzones']


And to list the webparts on a page:
$pageurl
$wpm = $web.GetLimitedWebPartManager($pageurl, 'Shared'
$wpm.WebParts | Format-Table -AutoSize WebBrowsableObject, ZoneId, ZoneIndex


There's also a post Determine which webpartzones are on a webpartpage that uses reflection to get at a private member however I have not gotten it to work.



Thursday, November 15, 2012

UserProfileApplicationNotAvailableException System.TimeoutException

I have a service the frequently accesses the User Profile Service Application. Intermittently, I would get the following:
Error generating SyndicationItem for ActivityEvent 0B275DAC41FD141CB2382AAE5987540D  Microsoft.Office.Server.UserProfiles.UserProfileApplicationNotAvailableException: System.TimeoutException    
 at Microsoft.Office.Server.UserProfiles.ProfileDBCacheServiceClient.GetUserData(UserSearchCriteria searchCriteria)    
 at Microsoft.Office.Server.UserProfiles.UserProfileCache.GetUserData(UserProfileManager objManager, Nullable`1 recordId, Guid gAcct, String strAcct, Byte[] bSid, String strEmail, Boolean doNotResolveToMasterAccount)    
 at Microsoft.Office.Server.UserProfiles.UserProfile.RetrieveUser(String strAcct, Guid gAcct, Byte[] bSid, Nullable`1 recordId, Boolean doNotResolveToMasterAccount, Boolean loadFullProfile)    
 at Microsoft.Office.Server.UserProfiles.UserProfile..ctor(UserProfileManager objManager, Int64 recordId)    
 at Microsoft.Office.Server.UserProfiles.UserProfileManager.GetUserProfile(Int64 recordId)

I tried the following to confirm:
$app = Get-SPWebApplication
$site = Get-SPSite $app.Url
$context = Get-SPServiceContext $site
$upm = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$upm.UserExists('someuser')

... and it just hangs.

Since this is a demo machine, there could be many factors:
1. Not enough resources
2. Application pool crash
3. Database not responding
4. General UPA flakiness
5. All of the above (and possibly pointing to #1 as the root cause).

I tried stop/start on the UPS and UPSS, then an iisreset. This didn't fix the problem. However, a reboot did.

Further looking at the event logs, I do see the following events from MsiInstaller that might be suspicious:


Detection of product '{90140000-104C-0000-1000-0000000FF1CE}', feature 'PeopleILM', component '{1C12B6E6-898C-4D58-9774-AAAFBDFE273C}' failed.  The resource 'C:\Program Files\Microsoft Office Servers\14.0\Service\Microsoft.ResourceManagement.Service.exe' does not exist.
Detection of product '{90140000-104C-0000-1000-0000000FF1CE}', feature 'PeopleILM' failed during request for component '{9AE4D8E0-D3F6-47A8-8FAE-38496FE32FF5}'
Failed to connect to server. Error: 0x80070005
Detection of product '{90140000-104C-0000-1000-0000000FF1CE}', feature 'PeopleILM', component '{1C12B6E6-898C-4D58-9774-AAAFBDFE273C}' failed.  The resource 'C:\Program Files\Microsoft Office Servers\14.0\Service\Microsoft.ResourceManagement.Service.exe' does not exist.
Detection of product '{90140000-104C-0000-1000-0000000FF1CE}', feature 'PeopleILM' failed during request for component '{1681AE41-ADA8-4B70-BC11-98A5A4EDD046}'
Failed to connect to server. Error: 0x80070005

... followed by one from FIMSynchronizationService:

The management agent "MOSS-3692cc7e-f3bf-4090-ae09-a552d3c61b7e" completed run profile "MOSS_DELTAIMPORT_4adf3894-708b-4ae2-ab9f-60438a49cae1" with a delta import or delta synchronization step type. The rules configuration has changed since the last full import or full synchronization.
 
User Action
To ensure the updated rules are applied to all objects, a run with step type of full import and full synchronization should be completed.

It was patch Tuesday a couple of days ago, perhaps that had a factor since I have auto updates enabled (which curiously did not install).

Monday, August 20, 2012

Locating unghosted pages

I recently came across a page that was giving me this error:
The control type '...' is not allowed on this page. The type is not registered as safe.

The obvious solution is to add a <SafeControl> tag to the web.config, but checking with my developer, he said it was not necessary and he does not have that declaration on his test server.

This led me to hypothesize that a custom branding we had was causing the problem to which my developer corroborated that unghosted master pages will cause problems.

So how to locate the unghosted pages? This led me to the following post: Ghosts in the Machine? However, this is for SharePoint 2007 so taking a leap of faith, I modified the SQL script provided and came up with this:

SELECT TOP 1000 
      [DirName]
      ,[LeafName]
      ,[SetupPath]
      ,[SetupPathUser]
  FROM [WSS_Content].[dbo].[AllDocs]
  where ([AllDocs].[Type] = 0)
  AND ([AllDocs].SetupPath IS NOT NULL)
  AND ([AllDocs].DocFlags & 64 = 64) 


Checking the reference for the AllDocs Table this query seemed to make sense.

Thursday, July 26, 2012

SharePoint Timer Service not starting up

I recently discovered that on one of my farms my SharePoint Timer Service would continuously start up and crash.
There are numerous entries like the following 2 in the System log:

The SharePoint 2010 Timer service terminated unexpectedly.  It has done this 2965 time(s).  The following corrective action will be taken in 30000 milliseconds: Restart the service.

and

The timer service could not initialize its configuration, please check the configuration database.  Will retry later.


The following is found in ULS:

SPTimerStore.InitializeTimer: SPConfigurationDatabase.RefreshCache returned SPConstants.InvalidRowVersion
and
The timer service could not initialize its configuration, please check the configuration database.  Will retry later.


I verified that my service's user context had the correct username and password.

I also cleared the timer cache (and, yes, I emptied the GUID folder and instead of deleting it).

There were a couple of DCOM 10016 errors which seemed irrelevant to this issue, but I fixed those anyway (as per http://sajiviswam.wordpress.com/2011/04/15/the-machine-default-permission-settings-do-not-grant-local-activation-permission-for-the-com-server-application-with-clsid-000c101c-0000-0000-c000-000000000046-sharepoint-2010/)

I'm still getting the same problem.

I started looking at the Fusion log as described in http://soerennielsen.wordpress.com/2009/01/14/fixing-the-timer-service-when-everything-breaks-down/ but think I'm in too deep.

What's curious is that the Timer Service stopped functioning around the time the web application was extended in order to support HTTPS and there are some new files in C:\windows\assembly\GAC_MSIL. However, I am unable to make any connection. As far as I can tell, my assemblies in the GAC are not corrupted since all other functions appear to be working.


Thursday, June 7, 2012

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

I just setup my SharePoint 2010 instance to run under SSL. I have a Powershell script that creates users and does a bunch of other setup things. One of the steps is to load some SharePoint pages which I do with something like this:


$Page = $WebClient.DownloadString($URL)


This was working fine when the default zone was HTTP but now that I am on HTTPS, I get the following error:

Exception calling "DownloadString" with "1" argument(s): "The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
At line:1 char:34
+ $Page = $WebClient.DownloadString <<<< ($URL)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException     + FullyQualifiedErrorId : DotNetMethodException

I am using a commercially signed certificate and triple checked that the CA root certificates are in the right places. 

Doing some research I came across this thread on SSL/TLS Trust Relationship. Simply overriding the server certificate validation callback to blindly accept everything did the trick:

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

Not feeling totally comfortable with that, I decided to do more research and found a post about Managing Trusted Root Authorities for Claims Authentication in SharePoint 2010 Central Admin. This led me to try the following:

  1. Central Administration->Manage Trust
  2. New (trust relationship)
I added my Root Authority Certificate and now I don't have any more trust issues. Well, my Powershell script doesn't - I still don't trust anybody :-) 

Wednesday, June 6, 2012

System.IO.FileLoadException thrown on managing service application from Central Administration

I had just extended my web application to allow for SSL access. In order to do some configuration, I needed to go into Central Administration->Manage Service Applications. I was unable to manage some applications because Central Administration was throwing the following exception:

System.IO.FileLoadException: The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)  

Not much more available in ULS.

It looks like just a simple iisreset did the trick. It probably has to do with the fact my demo server has Central Administration on the same server as the Service Application (just like the issue with the User Profile Application being on the same machine as Central Administration).