Mittwoch, 8. Juli 2020

WARNING: Unable to resolve package source 'https://www.powershellgallery.com/api/v2/'.

Hi everybody,

recently I tried to download PowerShell modules inside my development-image in VirtualBox by using the save-module-cmdlet which leads to this errormessage:


PS C:\Windows\system32> save-module microsoftteams -path c:\temp
WARNING: Unable to resolve package source 'https://www.powershellgallery.com/api/v2/'.
PackageManagement\Save-Package : No match was found for the specified search criteria and module name
'microsoftteams'. Try Get-PSRepository to see all available registered module repositories.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:1561 char:21
+             $null = PackageManagement\Save-Package @PSBoundParameters
+                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Microsoft.Power...ets.SavePackage:SavePackage) [Save-Package], Exceptio
   n
    + FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.SavePackage


Trying to connect to the displayed https-url also failed while opening it in browser succeded:


PS C:\Windows\system32> invoke-webrequest https://www.powershellgallery.com/api/v2/
invoke-webrequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS
secure channel.


So after hours of checking all possible proxy/certificate/ssl-settings, I found the solution in powershell itself:

Because of reasons I had added the SharePoint-Powershell SnapIn to c:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1 which afterwards broke something so that all connections to https broke.

After commenting out the Add-PSSnapin "Microsoft.SharePoint.PowerShell" everything works like a charm.

If you encounter something similar, try this. And if you try to save changes to profile.ps1 ensure that you opened the file in your editor as administrator. You can test the successful save by adding a write-host-output to the screen. Finally don't forget to close the current and reopen a new PowerShell.

Dienstag, 4. Juli 2017

Restore deleted Form-WebParts (NewForm.aspx, EditForm.aspx, DispForm.aspx)

If a clever user hits on the idea to delete the form webpart from NewForm.aspx, EditForm.aspx or DispForm.aspx, this can be restored easily with PowerShell. No need to open SharePoint Designer.

Basically a new ListFormWebPart-object must be instanciated, connected with the list and added to the webpartzone of the page. That's it.

Have a look at the following code:

$site = New-Object Microsoft.SharePoint.SPSite -ArgumentList http://sitecollection/sites/site1
$web = $site.OpenWeb()

$list = $web.Lists["My Library"] #title of the regarding list

$webpart = new-object Microsoft.SharePoint.WebPartPages.ListFormWebPart

# assign list to webpart
$webpart.ListId = $list.ID

# possible pagetypes are PAGE_DISPLAYFORM, PAGE_EDITFORM, or PAGE_NEWFORM
# see: https://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webpartpages.listformwebpart.pagetype.aspx
$webpart.PageType = "PAGE_EDITFORM"

# use the absolute link to the form-aspx
$wpm = $web.GetLimitedWebPartManager("http://sitecollection/sites/site1/myLibrary/Forms/EditForm.aspx", [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

$wpm.AddWebPart($webpart, "Main", 1)

# dispose spweb-object in webpartmanager to avoid memory leaks
$wpm.Web.Dispose()

$web.Dispose()
$site.Dispose() 

Mittwoch, 10. September 2014

Adding ECB directly to document libraries

Recently I used to look for a possibility to change the SharePoint 2013 ECB (Edit Control Block) from CallOut-Popup back to direct call as known from SharePoint 2010.

I found this way as a quick work around:
http://www.learningsharepoint.com/2013/05/18/hide-callouts-in-a-sharepoint-2013-task-list/

But by this solution, the drag-and-drop area is not rendered anymore and the old-fashioned "Add new item"-link below the list returns.

So I spent a little more time with googeling and found this page which adds an additional icon to click which displays the ECB directly:

http://www.booden.net/DirectAccessToEcb.aspx

The site describes the How-To and provides a sandboxed-solution for directly adding to the solutions-gallery of the SiteCollection. After activating everything to do is finished.

As you can see, the standard behaviour is not touched but extended by a new functionality:



It depends to the customer's wish if the three-dots-button now should be hidden (needs some additional work) or both buttons should remain.


Dienstag, 8. Juli 2014

SPFile.Publish() writes 'System Account' to 'ModifiedBy'-column instead of current user

I had the following scenario:

Documents that are dragged&dropped in a documentlibrary should be enriched with additional metadata and after that they should be published.
The document library has versions enabled with minor versions.

All action takes place in a SPItemEventReceiver, the details for that I'll omit for now.

Now when it came to do spFile.Publish(), after that the "ModifiedBy"-Column has 'System Account' instead of the current user and there seemed no way to set it manually. Neither the Publish-Method had a parameter to set the current user, nor SPListItem.SystemUpdate or SPListItem.UpdateOverwriteVersion worked:

- SystemUpdate won't save changes to CreatedBy/Created or ModifiedBy/Modified-fields.
- UpdateOverwriteVersion would work but creates a minor version (1.1 in my case)

But then I found a solution here.

I couldn't believe that and tried it out and it really worked! The post said, the SPSite-Object should be opened by adding the SPUserToken to the constructor and then SPFile.Publish() will save the user as last modifier. To show a concrete minimal example:

using (SPSite spSite = new SPSite(properties.SiteId, properties.OriginatingUserToken)) {
 using (SPWeb spWeb = spSite.OpenWeb(serverRelativeWebUrl)) {
  SPListItem spListItem = spWeb.GetListItem(properties.Web.ServerRelativeUrl); // make sure, the file is checked in before or try to acces or you get a file-not-found-error here 
  SPFile spFile = spListItem.File; 
  ... add more data to spListItem... 
  spListItem.SystemUpdate(false); 
  ... check for enabled versions, etc... 
  spFile.Publish(); // writes the SPUser related to the SPUserToken from properties.OriginatingUserToken to 'ModifiedBy'-column, if SPSite is instantiated with new SPSite(properties.SiteId) only, 'System Account' is used
 }
}

properties is the default SPItemEventProperties-object from the SPItemEventReceiver.

Pay attention, the "Modified"-Column (DateTime) changes to DateTime.Now. But this was not in the focus of my requirement.

I always thought, using new SPSite(Guid) would open  the SPSite in current user's context but that's not true as a closer look by using Reflector shows. Have a look at two of the default constructors from SPSite-class:

public SPSite(System.Guid id) : this(id, SPFarm.Local, SPUrlZone.Default, SPSecurity.GetDefaultUserToken())


public SPSite(System.Guid id, SPUserToken userToken) : this(id, SPUrlZone.Default, userToken)

Do you note the difference? :-)   

Montag, 30. Juni 2014

Avoiding conflicts if Custom_AddDocLibMenuItems-function is implemented multiple

Today I found a really helpful tip how to add custom items to the SharePoint Edit Control Block (ECB) without getting in conflict with other used Custom_AddDocLibMenuItems-function-calls (for e.g. from another deployed wsp-solution or script added in a Content Editor WebPart (in SharePoint 2010) or ScriptEditor-WebPart (in SharePoint 2013).
You can find it here in Stuart Roberts' blog: http://www.stuartroberts.net/index.php/2014/01/21/quick-tip-19

Montag, 25. November 2013

A potentially dangerous Request.Form value was detected from the client (ctl00$PlaceHolderMain$...

Recently I got the following errormessage in SharePoint 2013 after trying to save an edited publishing page. Also it was not possible to add any webpart.
Some googling resultet in different web.config-modifications, some said to set requestValidationMode="4.0" to requestValidationMode="2.0" in <system.web>-node, others recommended to set validateRequest="false"in <pages>-node. In fact for it only worked after I did both changes. So search for

<system.web>
 <httpRuntime requestValidationMode="4.0" />
</system.web>

and set requestValidationMode to "2.0" and search for

<pages enableSessionState="false" enableViewState="true" enableViewStateMac="true" validateRequest="true" clientIDMode="AutoID" pageParserFilterType="Microsoft.SharePoint.ApplicationRuntime.SPPageParserFilter, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" asyncTimeout="7">
      <namespaces>
        <remove namespace="System.Web.UI.WebControls.WebParts" />
      </namespaces>
      <tagMapping>
        <add tagType="System.Web.UI.WebControls.SqlDataSource, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" mappedTagType="Microsoft.SharePoint.WebControls.SPSqlDataSource, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      </tagMapping>
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        <add tagPrefix="spsswc" namespace="Microsoft.Office.Server.Search.WebControls" assembly="Microsoft.Office.Server.Search, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      </controls>
    </pages>

and set validateRequest to "false".

Donnerstag, 2. Mai 2013

Get current versions for activated features (not feature definitions) in a web or site collection

Recently I wrote a PowerShell-Script which writes the current version-numbers of web-features specified by a name-filter into a file. These versions are not from the feature-definition but from the feature activated in a web.

An example for this could be the following:
On a SharePoint-server a feature named custom_feature_1 was installed which has a version of 3.0.0.0 because it's been updated a few times during the lifecycle of the appication.
Because the rootweb was created first, the feature's version is 1.0.0.0 there. A newer subweb below has been created after the feature was updated and there the feature's version is 2.0.0.0. Now, after the third update, another web will be created where the feature now has a version of 3.0.0.0.

So how can you easily get the version of the feature activated in one of these webs?

You can use this PowerShell-script to get all information about your features:

get-spweb http://customsitecollection/customweb |% {$_.Features} | where-object {$_.Definition -ne $null} | where-object {$_.Definition.DisplayName.StartsWith("custom")} |% {new-object psobject -Property @{Id = $_.DefinitionId; Version = $_.Version; DisplayName = ($_ | select -ExpandProperty Definition).DisplayName; Scope = ($_ | select -ExpandProperty Definition).Scope; }} | format-table -Property * -Autosize | Out-String -Width 120 | out-file custom_web_features.txt


Just copy these lines and replace the bold-marked parts by your own needs:
http://customsite/customweb - The full path to the web you want the feature-versions from
custom - The name that the features starts with in SharePoint-Root features-folder
custom_web_features.txt - The name of the file that's created with information

The content of the file should look like this:


You can reuse the script for site-scoped features too. Just replace get-spweb by get-spsite and a valid URL to a sitecollection.