If you migrated from OfficeDevPnP (SharePointPnPCoreOnline nuget package) to PnP.Framework you will need to rewrite code which adds SPFx web parts on modern pages. Old code which used OfficeDevPnP looked like that:
var page = ctx.Web.LoadClientSidePage(pageName);
var groupInfoComponent = new ClientSideComponent();
groupInfoComponent.Id = webPartId;
groupInfoComponent.Manifest = webPartManifest;
page.AddSection(CanvasSectionTemplate.OneColumn, 1);
var groupInfiWP = new ClientSideWebPart(groupInfoComponent);
page.AddControl(groupInfiWP, page.Sections[page.Sections.Count - 1].Columns[0]);
page.Save();
page.Publish();
But it won't compile with PnP.Framework because ClientSideWebPart became IPageWebPart. Also ClientSideComponent means something different and doesn't have the same properties. In order to add SPFx web part to the modern page with PnP.Framework the following code can be used:
var page = ctx.Web.LoadClientSidePage(pageName);
var groupInfoComponent = page.AvailablePageComponents().FirstOrDefault(c => string.Compare(c.Id, webPartId, true) == 0);
var groupInfoWP = page.NewWebPart(groupInfoComponent);
page.AddSection(CanvasSectionTemplate.OneColumn, 1);
page.AddControl(groupInfoWP, page.Sections[page.Sections.Count - 1].Columns[0]);
page.Save();
page.Publish();
Here we first get web part reference from page.AvailablePageComponents() and then create new web part using page.NewWebPart() method call. After that we add web part on a page using page.AddControl() as before. Hope it will help someone.
Some time ago PnP team announced that SharePointPnPCoreOnline nuget package became retired and we should use PnP.Framework now. Latest available version of SharePointPnPCoreOnline is 3.28.2012 and it won't be developed further. Based on that recommendation we performed migration from SharePointPnPCoreOnline to PnP.Framework. During migration there were several interesting issues and I'm going to write series of posts about these issues.
One of the issue was that one class SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2.OAuth2AccessTokenResponse was defined in 2 different assemblies in the same namespace:
SharePointPnP.IdentityModel.Extensions.dll
PnP.Framework
Compiler couldn't resolve this ambiguity and showed an error:
Since class name is the same and namespace is the same - in order to resolve this issue we need to use quite rarely used technique called extern aliases. At first in VS on referenced assembly's properties window we need to specify assembly alias. By default all referenced assemblies have "global" alias - so we need to change it on custom one:
Then in cs file which has ambiguous class name on the top of the file we need to define our alias and then add "using" with this alias:
SharePointPnPIdentityModelExtensions;
...
using SharePointPnPIdentityModelExtensions::SharePointPnP.IdentityModel.Extensions.S2S.Tokens;
After these steps compilation error has gone and solution has been successfully built.
public static bool WebExistsFullUrl(ClientRuntimeContext context, string webFullUrl)
{
bool exists = false;
try
{
using (ClientContext testContext = context.Clone(webFullUrl))
{
testContext.Load(testContext.Web, w => w.Title);
testContext.ExecuteQueryRetry();
exists = true;
}
}
catch (Exception ex)
{
if (IsUnableToAccessSiteException(ex) || IsCannotGetSiteException(ex))
{
// Site exists, but you don't have access .. not sure if this is really valid
// (I guess if checking if URL is already taken, e.g. want to create a new site
// then this makes sense).
exists = true;
}
}
return exists;
}
but now when we try to clone ClientContext in this line:
and webFullUrl corresponds to non-existent site collection from another managed path (e.g. if context was created from the root site collection http://example.com and we pass webFullUrl = http://example.com/sites/som-non-existent-url) it throws System.Exception (System.Net.WebException) now:
The remote server returned an error: (404) Not Found
while in earlier CSOM version it created ClientContext for the root site in this case. And as result WebExtensions.WebExistsFullUrl returns false as expected. So fortunately issue was fixed and we can call this method for checking existence of different site collections.
Recently we faced with the following problem in our Azure function app: after some time of functioning Azure functions got stuck and the only way to make them work again was to restart them manually from Azure portal UI. Research showed that problem was related with threads count: because of some reason threads count permanently grew to 6K thread after which Azure function app became unresponsive:
We reviewed our code, made some optimizations, change some async calls to sync equivalents, but it didn’t fix the problem. Then we continued troubleshooting and found the following: in the code we used OfficeDevPnP AuthenticationManager in order to get access token for communicating with Sharepoint Online like that:
using (var ctx = new OfficeDevPnP.Core.AuthenticationManager().GetAppOnlyAuthenticatedContext(url, clientId, clientSecret))
{
...
}
Note that in this example new instance of AuthenticationManager is created each time when above code was executed. In our case it was inside queue-triggered Azure function which was called quite frequently. Elio Struyf (we worked over this problem together so credits for this finding go to him ) tried to make AuthenticationManager static – i.e. only one instance was created for the whole Azure function worker process:
public static class Helper
{
private static OfficeDevPnP.Core.AuthenticationManager authMngr = new OfficeDevPnP.Core.AuthenticationManager();
public static void QueueTriggeredFunc()
{
using (var ctx = authMngr.GetAppOnlyAuthenticatedContext(url, clientId, clientSecret))
{
...
}
}
}
After that threads count got stabilized with avg 60 threads:
We reported this problem to OfficeDevPnP team and they confirmed that there is problem in AuthenticationManager which internally creates thread for monitoring access token’s lifetime, but this thread is not released when AuthenticationManager got recycled by garbage collector (also need to mention that AuthenticationManager itself was not disposable at the moment when this problem was found. We used OfficeDevPnP 3.20.2004.0 when found this problem). For now this workaround with making AuthenticationManager static was Ok and as far as I know currently OfficeDevPnP team works over correct fix for this problem. So hopefully it will be available soon globally.
Update 2020-06-15: from latest news I've got (thanks to Yannick Plenevaux :) ) OfficeDevPnP team addressed this issue in 202006.2 version and made AuthenticationManager disposable. So you may need to review your code in order to add using() around it.
Sharepoint PnP PowerShell library has many useful commands which simplify scripting against Sharepoint Online. One of them is Copy-PnPFile which allows to copy file from one document library to another. Source and target doclibs may be even located in different site collections in the same tenant.
One of example of Copy-PnPFile (basically 1st example) says that it is possible to copy single file like that:
Unfortunately currently it gives File not found error. Looks like there is a bug in Copy-PnPFile which prevents it from working correctly – it is also described in this StackOverflow thread which was created couple of days ago: Copy-PnPFile returns File Not Found.
The only working way which I’ve found so far is to copy whole root folder:
It will copy all files from Documents doclib to Documents doclib on another site collection /sites/otherproject. However it will also try to copy OTB list view AllItems.aspx as last file and it will give error that AllItems.aspx already exists in target doclib. In order to ignore this error I used the following solution:
Sharepoint PnP Powershell library (which is also available on Nuget) has own provisioning engine. It is quite powerful engine which allows to provision MUI sites (although it has own problems with stability). In order to do that you need to use several basic elements:
1. Have all literals which should be localized in resx file
2. Specify supported languages inside <pnp:SupportedUILanguages>…</pnp:SupportedUILanguages> section of PnP template. After provisioning these languages will be set in Site settings > Language settings > Alternate languages. You need to have resx file for each supported language in standard resources.xx-XX.resx format
3. Resx files with translations should be specified inside <pnp:Localizations>…</pnp:Localizations> section of PnP template. Note that PnP will provision all these languages to your site regardless of what alternate languages are set in Site settings > Language settings on the moment when this template is applied to target site
4. For localized strings use {resource:ResourceKey} format inside template
Here is example of how PnP template for MUI site provisioning may look like:
Recently we faced with the following problem: when tried to set DenyAddAndCustomizePages property of modern Sharepoint site to Disabled (which means that customizations will be enabled for that site) using PnP PowerShell:
Set-PnPTenantSite -Url $url -NoScriptSite:$false
the following error was thrown:
Error in proc_GetSitesAllowDenyList, no rowset returned
In order to fix it you have to call Connect-PnPOnline for tenat’s admin center (https://{tenant}-admin.sharepoint.com) not to target site itself. Also using CSOM version works more stable than shown Set-PnPTenantSite. Here is the final code:
Tenant storage entities (or tenant properties) allow to store tenant-wide properties which will be accessible from all site collections across tenant. It is often needed in installation PowerShell scripts to save some common settings to tenant storage entities. Also we may need to do that using app permissions i.e. using app id and secret instead of credentials of specific user. In this post I will show the method which may be used for that.
At first let’s try the most obvious way using PnP PowerShell cmdlets. There is overload of Connect-PnPOnline cmdlet which connects to Shrepoint Online using app id and secret instead of user credentials:
However it will give Access denied error even if app has FullControl permissions on tenant level:
Note that in this example I connected to the app catalog site for setting storage entity (below it is described why). But there will be also the same error if you will try to connect to the tenant’s root site or to tenant admin center.
Now let’s try use CSOM and OfficeDevPnP assemblies directly in PowerShell:
At first we load CSOM and OfficeDevPnP.Core assemblies. Then we need to connect to some existing site in our tenant and get app catalog url programmatically using CSOM. After that we create ClientContext using app catalog url and call Web.SetStorageEntity method. This is the trick because if you will try to call this method with any other web site you will get the same Access denied error. Also in this example we used great Load-CSOMProperties helper method from Gary Lapointe which allows to load object with properties using CSOM in PowerShell. It can be found here: https://gist.github.com/glapointe/cc75574a1d4a225f401b.
After you will run this code it will update tenant storage entity using app permissions.
In one of my previous posts I showed example how to create Azure AD groups with owners which were added right after group has been created: Create Azure AD group and set group owner using Microsoft Graph Client library. This approach works but on some tenants it may cause slowness and performance problems during group’s creation. You may have the following error when use this approach:
"code": "ResourceNotFound" "message": "Resource provisioning is in progress. Please try again."
This issue is also reported on github: After office 365 group is created, the group site provisioning is pending. Also if you will try to create group using PnP PowerShell or OfficeDevPnP library you may face with the same issue. PnP uses UnifiedGroupsUtility.CreateUnifiedGroup method to create groups. Let’s check it’s code:
public static UnifiedGroupEntity CreateUnifiedGroup(string displayName, string description, string mailNickname,
string accessToken, string[] owners = null, string[] members = null, Stream groupLogo = null,
bool isPrivate = false, int retryCount = 10, int delay = 500)
{
UnifiedGroupEntity result = null;
if (String.IsNullOrEmpty(displayName))
{
throw new ArgumentNullException(nameof(displayName));
}
if (String.IsNullOrEmpty(description))
{
throw new ArgumentNullException(nameof(description));
}
if (String.IsNullOrEmpty(mailNickname))
{
throw new ArgumentNullException(nameof(mailNickname));
}
if (String.IsNullOrEmpty(accessToken))
{
throw new ArgumentNullException(nameof(accessToken));
}
try
{
// Use a synchronous model to invoke the asynchronous process
result = Task.Run(async () =>
{
var group = new UnifiedGroupEntity();
var graphClient = CreateGraphClient(accessToken, retryCount, delay);
// Prepare the group resource object
var newGroup = new Microsoft.Graph.Group
{
DisplayName = displayName,
Description = description,
MailNickname = mailNickname,
MailEnabled = true,
SecurityEnabled = false,
Visibility = isPrivate == true ? "Private" : "Public",
GroupTypes = new List<string> { "Unified" },
};
Microsoft.Graph.Group addedGroup = null;
String modernSiteUrl = null;
// Add the group to the collection of groups (if it does not exist
if (addedGroup == null)
{
addedGroup = await graphClient.Groups.Request().AddAsync(newGroup);
if (addedGroup != null)
{
group.DisplayName = addedGroup.DisplayName;
group.Description = addedGroup.Description;
group.GroupId = addedGroup.Id;
group.Mail = addedGroup.Mail;
group.MailNickname = addedGroup.MailNickname;
int imageRetryCount = retryCount;
if (groupLogo != null)
{
using (var memGroupLogo = new MemoryStream())
{
groupLogo.CopyTo(memGroupLogo);
while (imageRetryCount > 0)
{
bool groupLogoUpdated = false;
memGroupLogo.Position = 0;
using (var tempGroupLogo = new MemoryStream())
{
memGroupLogo.CopyTo(tempGroupLogo);
tempGroupLogo.Position = 0;
try
{
groupLogoUpdated = UpdateUnifiedGroup(addedGroup.Id, accessToken, groupLogo: tempGroupLogo);
}
catch
{
// Skip any exception and simply retry
}
}
// In case of failure retry up to 10 times, with 500ms delay in between
if (!groupLogoUpdated)
{
// Pop up the delay for the group image
await Task.Delay(delay * (retryCount - imageRetryCount));
imageRetryCount--;
}
else
{
break;
}
}
}
}
int driveRetryCount = retryCount;
while (driveRetryCount > 0 && String.IsNullOrEmpty(modernSiteUrl))
{
try
{
modernSiteUrl = GetUnifiedGroupSiteUrl(addedGroup.Id, accessToken);
}
catch
{
// Skip any exception and simply retry
}
// In case of failure retry up to 10 times, with 500ms delay in between
if (String.IsNullOrEmpty(modernSiteUrl))
{
await Task.Delay(delay * (retryCount - driveRetryCount));
driveRetryCount--;
}
}
group.SiteUrl = modernSiteUrl;
}
}
#region Handle group's owners
if (owners != null && owners.Length > 0)
{
await UpdateOwners(owners, graphClient, addedGroup);
}
#endregion
#region Handle group's members
if (members != null && members.Length > 0)
{
await UpdateMembers(members, graphClient, addedGroup);
}
#endregion
return (group);
}).GetAwaiter().GetResult();
}
catch (ServiceException ex)
{
Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_ErrorOccured, ex.Error.Message);
throw;
}
return (result);
}
As you can see it basically uses the same approach: at first creates group and then adds owners/members using UpdateOwners/UpdateMembers methods.
Workaround for this problem is to not use Graph API client library and use plain REST calls and special OData bind syntax for owners and members like described here: Create a Group in Microsoft Graph API with a Owner
This approach works i.e. groups are created with owners and members from beginning and you don’t have to call another methods to add them separately. But is it possible to do the same with Graph API .Net client library (it would be good because it is more convenient to use client library than raw REST calls). The answer is yes it is possible and below it is shown how to do it.
Need to say that if you use only Graph API .Net client library classes it is not possible to do it. If you check property Group.Owners you will see that it has IGroupOwnersCollectionWithReferencesPage type:
In Graph API library there is only one class which implements this interface GroupOwnersCollectionWithReferencesPage and you can’t create instance of this class with owners specified and pass to Group.Owners property – it has to be used with Groups[].Request.Owners.References when you read group owners with pagination. So my first attempt was to create custom class which inherits IGroupOwnersCollectionWithReferencesPage interface which would allow list of user in constructor and then pass it’s instance to Group.Owners property before creation:
public class LightOwners : CollectionPage<DirectoryObject>, IGroupOwnersCollectionWithReferencesPage
{
public LightOwners()
{
}
public LightOwners(List<User> owners)
{
if (owners != null)
{
owners.ForEach(o => this.Add(o));
}
}
public void InitializeNextPageRequest(IBaseClient client, string nextPageLinkString)
{
}
public IGroupOwnersCollectionWithReferencesRequest NextPageRequest { get; }
}
This approach didn’t work: group object was serialized to JSON when client library made POST request to https://graph.microsoft.com/v1.0/groups for creating the group with property “owners” and all users’ properties were serialized as well – while we need "owners@odata.bind" and "https://graph.microsoft.com/v1.0/users/{id1}" string instead of fully serialized user object.
After that I tried another approach which worked: at first created new class GroupExtended which inherits Group class from Graph API library:
public class GroupExtended : Group
{
[JsonProperty("owners@odata.bind", NullValueHandling = NullValueHandling.Ignore)]
public string[] OwnersODataBind { get; set; }
[JsonProperty("members@odata.bind", NullValueHandling = NullValueHandling.Ignore)]
public string[] MembersODataBind { get; set; }
}
As you can see it adds 2 new properties OwnersODataBind and MembersODataBind which are serialized to "owners@odata.bind" and "members@odata.bind" respectively. Then I modified UnifiedGroupsUtility.CreateUnifiedGroup method to create groups with owners and members from beginning using single API call instead of adding them after group was created:
public static UnifiedGroupEntity CreateUnifiedGroup(string displayName, string description, string mailNickname,
string accessToken, string[] owners = null, string[] members = null, Stream groupLogo = null,
bool isPrivate = false, int retryCount = 10, int delay = 500)
{
UnifiedGroupEntity result = null;
if (String.IsNullOrEmpty(displayName))
{
throw new ArgumentNullException(nameof(displayName));
}
if (String.IsNullOrEmpty(description))
{
throw new ArgumentNullException(nameof(description));
}
if (String.IsNullOrEmpty(mailNickname))
{
throw new ArgumentNullException(nameof(mailNickname));
}
if (String.IsNullOrEmpty(accessToken))
{
throw new ArgumentNullException(nameof(accessToken));
}
try
{
// Use a synchronous model to invoke the asynchronous process
result = Task.Run(async () =>
{
var group = new UnifiedGroupEntity();
var graphClient = CreateGraphClient(accessToken, retryCount, delay);
// Prepare the group resource object
var newGroup = new GroupExtended
{
DisplayName = displayName,
Description = description,
MailNickname = mailNickname,
MailEnabled = true,
SecurityEnabled = false,
Visibility = isPrivate == true ? "Private" : "Public",
GroupTypes = new List<string> { "Unified" }
};
if (owners != null && owners.Length > 0)
{
var users = GetUsers(graphClient, owners);
if (users != null)
{
newGroup.OwnersODataBind = users.Select(u => string.Format("https://graph.microsoft.com/v1.0/users/{0}", u.Id)).ToArray();
}
}
if (members != null && members.Length > 0)
{
var users = GetUsers(graphClient, members);
if (users != null)
{
newGroup.MembersODataBind = users.Select(u => string.Format("https://graph.microsoft.com/v1.0/users/{0}", u.Id)).ToArray();
}
}
Microsoft.Graph.Group addedGroup = null;
String modernSiteUrl = null;
// Add the group to the collection of groups (if it does not exist
if (addedGroup == null)
{
addedGroup = await graphClient.Groups.Request().AddAsync(newGroup);
if (addedGroup != null)
{
group.DisplayName = addedGroup.DisplayName;
group.Description = addedGroup.Description;
group.GroupId = addedGroup.Id;
group.Mail = addedGroup.Mail;
group.MailNickname = addedGroup.MailNickname;
int imageRetryCount = retryCount;
if (groupLogo != null)
{
using (var memGroupLogo = new MemoryStream())
{
groupLogo.CopyTo(memGroupLogo);
while (imageRetryCount > 0)
{
bool groupLogoUpdated = false;
memGroupLogo.Position = 0;
using (var tempGroupLogo = new MemoryStream())
{
memGroupLogo.CopyTo(tempGroupLogo);
tempGroupLogo.Position = 0;
try
{
groupLogoUpdated = UnifiedGroupsUtility.UpdateUnifiedGroup(addedGroup.Id, accessToken, groupLogo: tempGroupLogo);
}
catch
{
// Skip any exception and simply retry
}
}
// In case of failure retry up to 10 times, with 500ms delay in between
if (!groupLogoUpdated)
{
// Pop up the delay for the group image
await Task.Delay(delay * (retryCount - imageRetryCount));
imageRetryCount--;
}
else
{
break;
}
}
}
}
int driveRetryCount = retryCount;
while (driveRetryCount > 0 && String.IsNullOrEmpty(modernSiteUrl))
{
try
{
modernSiteUrl = UnifiedGroupsUtility.GetUnifiedGroupSiteUrl(addedGroup.Id, accessToken);
}
catch
{
// Skip any exception and simply retry
}
// In case of failure retry up to 10 times, with 500ms delay in between
if (String.IsNullOrEmpty(modernSiteUrl))
{
await Task.Delay(delay * (retryCount - driveRetryCount));
driveRetryCount--;
}
}
group.SiteUrl = modernSiteUrl;
}
}
// #region Handle group's owners
//
// if (owners != null && owners.Length > 0)
// {
// await UpdateOwners(owners, graphClient, addedGroup);
// }
//
// #endregion
// #region Handle group's members
//
// if (members != null && members.Length > 0)
// {
// await UpdateMembers(members, graphClient, addedGroup);
// }
//
// #endregion
return (group);
}).GetAwaiter().GetResult();
}
catch (ServiceException ex)
{
//Log.Error(Constants.LOGGING_SOURCE, CoreResources.GraphExtensions_ErrorOccured, ex.Error.Message);
throw;
}
return (result);
}
private static List<User> GetUsers(GraphServiceClient graphClient, string[] owners)
{
if (owners == null)
{
return new List<User>();
}
var result = Task.Run(async () =>
{
var usersResult = new List<User>();
var users = await graphClient.Users.Request().GetAsync();
while (users.Count > 0)
{
foreach (var u in users)
{
if (owners.Any(o => u.UserPrincipalName.ToLower().Contains(o.ToLower())))
{
usersResult.Add(u);
}
}
if (users.NextPageRequest != null)
{
users = await users.NextPageRequest.GetAsync();
}
else
{
break;
}
}
return usersResult;
}).GetAwaiter().GetResult();
return result;
}
private static GraphServiceClient CreateGraphClient(String accessToken, int retryCount = 10, int delay = 500)
{
// Creates a new GraphServiceClient instance using a custom PnPHttpProvider
// which natively supports retry logic for throttled requests
// Default are 10 retries with a base delay of 500ms
var result = new GraphServiceClient(new DelegateAuthenticationProvider(
async (requestMessage) =>
{
if (!String.IsNullOrEmpty(accessToken))
{
// Configure the HTTP bearer Authorization Header
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
}
}), new PnPHttpProvider(retryCount, delay));
return (result);
}
And after that groups were created successfully with owners and members. At first code resolves specified users by their emails and then fills OwnersODataBind and MembersODataBind properties with strings like "https://graph.microsoft.com/v1.0/users/{id1}" (we need to resolve uses from Azure AD first in order to get their ids to build these strings). After that it creates group with single call and it contains specified owners and members. So this approach allows to create groups with owners and members set from beginning.
Some time ago we faced with the following problem: let’s say we have PowerShell script which does some actions on modern Sharepoint Online site collection. Among with other actions it sets property bag values on the root site of the target site collection:
It returns control quite quickly. The problem however that on practice effect from setting DenyAddAndCustomizePages to false has delay. I.e. if you will try to set property bag value using cmdlet shown above immediately after you set DenyAddAndCustomizePages to false – there won’t be any errors but value won’t be really saved into property bag.
As workaround I’ve added 60 seconds delay to the script with UI indication (dots are printed to output each second until there won’t be 60 dots in line):
Write-Host "Wait some time before changes will take effect..."
$i = 0
do
{
Write-Host "." -NoNewLine
Start-Sleep -s 1
$i++
}
while ($i -lt 60)
Write-Host
After this delay property bag values were saved successfully.
Modern Team and Communication sites can be created through PnP PowerShell cmdlet New-PnPSite. Here are examples how you may create these sites:
Team: New-PnPSite -Type TeamSite -Title Test -Alias test
Communication: New-PnPSite -Type CommunicationSite -Title Test -Url https://{tenant}.sharepoint.com/sites/test
Note that for Team site we use Alias parameter while for Communication site we use Url. It is mandatory to use relative url when you create Team site and absolute url when you create Communication site. If you will try to create Team site with absolute url:
Team: New-PnPSite -Type TeamSite -Title Test -Alias https://{tenant}.sharepoint.com/sites/test
you will get the following error:
Invalid value specified for property 'mailNickname' of resource 'Group'.
And if you will try to create communication site with relative url:
Communication: New-PnPSite -Type CommunicationSite -Title Test -Url test
there will be another error:
This operation is not supported for a relative URI.
(BTW with modern experience currently it is possible to create sub folders of only first level. If you want to create sub folders of deeper levels you have to switch to classic experience and create sub folder from there)
However if you will try to delete this folder you will get the following error:
Sorry, something went wrong
The server has encountered the following error(s):
Test
Access denied. You do not have permission to perform this action or access this resource.
In order to avoid this error you need to enable customizations of pages and scripts on the site. You may do it with the following PowerShell command:
When I checked in Fiddler request details of UpdateAsync() call I found that JSON representation of group object which is passed to HTTP PATCH method really has responseHeaders property:
Not sure why responseHeaders property is now added to the group object when it is first returned from graph. In order to avoid this error I used the following workaround: construct new Group object, specify group id and only those properties which should be updated. I.e. update object with minimal required specified properties:
var graphClient = CreateGraphClient(accessToken);
var existingGroup = await graphClient.Groups[groupId].Request().GetAsync();
var groupToUpdateMinimal = new Group();
groupToUpdateMinimal.Id = groupId;
bool updateGroup = false;
if (!string.IsNullOrEmpty(description) && existingGroup.Description != description)
{
groupToUpdateMinimal.Description = description;
updateGroup = true;
}
bool existingIsPrivate = existingGroup.Visibility == "Private";
if (isPrivate != null && existingIsPrivate != isPrivate.Value)
{
groupToUpdateMinimal.Visibility = isPrivate.Value ? "Private" : "Public";
updateGroup = true;
}
if (updateGroup)
{
await graphClient.Groups[groupId].Request().UpdateAsync(groupToUpdateMinimal);
}
In this case only id, description and visibility properties are passed to HTTP PATCH method:
Recently I faced with interesting problem with assembly binding redirect in PowerShell: in my script I needed to use the following versions of the assemblies (these exact versions were used in other components and I couldn’t add another versions because of number of reasons):
if (!("Redirector" -as [type]))
{
$source =
@'
using System;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
public class Redirector
{
public readonly string[] ExcludeList;
public Redirector(string[] ExcludeList = null)
{
this.ExcludeList = ExcludeList;
this.EventHandler = new ResolveEventHandler(AssemblyResolve);
}
public readonly ResolveEventHandler EventHandler;
protected Assembly AssemblyResolve(object sender, ResolveEventArgs resolveEventArgs)
{
Console.WriteLine("Attempting to resolve: " + resolveEventArgs.Name); // remove this after its verified to work
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var pattern = "PublicKeyToken=(.*)$";
var info = assembly.GetName();
var included = ExcludeList == null || !ExcludeList.Contains(resolveEventArgs.Name.Split(',')[0], StringComparer.InvariantCultureIgnoreCase);
if (included && resolveEventArgs.Name.StartsWith(info.Name, StringComparison.InvariantCultureIgnoreCase))
{
if (Regex.IsMatch(info.FullName, pattern))
{
var Matches = Regex.Matches(info.FullName, pattern);
var publicKeyToken = Matches[0].Groups[1];
if (resolveEventArgs.Name.EndsWith("PublicKeyToken=" + publicKeyToken, StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("Redirecting lib to: " + info.FullName); // remove this after its verified to work
return assembly;
}
}
}
}
return null;
}
}
'@
$type = Add-Type -TypeDefinition $source -PassThru
}
try
{
$redirector = [Redirector]::new($null)
[System.AppDomain]::CurrentDomain.add_AssemblyResolve($redirector.EventHandler)
}
catch
{
#.net core uses a different redirect method
Write-Warning "Unable to register assembly redirect(s). Are you on ARM (.Net Core)?"
}
And surprisingly this approach worked. It looks like a bug in PowerShell script-based assembly binding redirect. Hope it will help someone.
Suppose that we need to check whether site collection with specified absolute url exists or not using client side object model. In OfficeDevPnP library there is convenient extension method for ClientContext WebExtensions.WebExistsFullUrl:
Unfortunately this method works properly only within single site collection i.e. when client context (which is extended with this extension method) and url to check belong to the same managed path.
But if context and url to check belong to different managed path then it always returns true.
Example: context is created from the root site http://example.com and we call WebExistsFullUrl for some url which may belong to other site collection (e.g. which uses different managed path like http://example.com/teams/some-not-real-url. Suppose that at the moment of call we don't know whether this collection exists or not - we want to determine it by WebExistsFullUrl call). In this case WebExistsFullUrl returns true even if site collection with specified url doesn't exists.
When I analyzed the code I found the following. When we call this method with context and url which belong to the same managed path it throws exception like expected. But when it is called with context and url which belong to different managed paths exception is not thrown. Instead context is created for the root site http://example.com and method returns true and caller thinks that site exists. In order to fix this problem for different managed paths I applied the following fix in our local version:
public static bool WebExistsFullUrl(this ClientRuntimeContext context, string webFullUrl)
{
bool exists = false;
try
{
using (ClientContext testContext = context.Clone(webFullUrl))
{
testContext.Load(testContext.Web, w => w.Title, w => w.Url);
testContext.ExecuteQueryRetry();
exists = (string.Compare(testContext.Web.Url, webFullUrl, true) == 0);
}
}
catch (Exception ex)
{
if (IsUnableToAccessSiteException(ex) || IsCannotGetSiteException(ex))
{
// Site exists, but you don't have access .. not sure if this is really valid
// (I guess if checking if URL is already taken, e.g. want to create a new site
// then this makes sense).
exists = true;
}
}
return exists;
}
I.e. before to return true method also checks whether loaded url is the same as url to be checked. If they are different (which happens in scenario with different managed paths) it will return false like it should.
Described behavior was found when root site collection (http://example.com) was host-named site collection, but most probably it will also work same way for regular site collections.
Office 365 Developers Patterns and Practices library contains many useful methods for Sharepoint Online development. I would like to have some kind of reference page which would contain all methods from this doclib in one place so I can search them by Ctrl-F without pagination. In order to do such reference I used NDepend tool and built report from OfficeDevPnP.Core.dll v.2.22.1801.0 which is currently latest version for Sharepoint Online (note that for on-premise there is separate assembly). NDepend has useful feature called Code Query Linq (CQLinq) which allows you to make queries to the code in loaded assemblies, i.e. work with code as it would be data. E.g. for getting all methods with their parent classes I used the following Linq query:
In order to set composed look for Sharepoint site we may use SetComposedLookByUrl extension method from OfficeDevPnP library. According to documentation it does the following:
Retrieves the named composed look, overrides with specified palette, font, background and master page, and then recursively sets the specified values.
The problem is that on the real production environments this method may work very slow (we needed to set composed look on all sub sites, i.e. pass resetSubsitesToInherit = true and updateRootOnly = false). When apply it on the site with many sub sites (about 4000 sub site) it worked almost 15 hours and then was interrupted with network connectivity exception.
Another problematic moment is that method doesn’t show any progress indicator, i.e. you just have to wait watching black screen all that time. At the moment I see only 1 workaround which at least will allow to see progress of the work: iterate through sub sites in own external loop, print url of currently updated web and call SetComposedLookByUrl for each web site separately with resetSubsitesToInherit = false and updateRootOnly = true. If you know other solutions please share them in comments.