Exemple #1
0
 protected override void ExecuteCmdlet()
 {
     CurrentWeb.CreatePublishingImageRendition(Name, Width, Height);
 }
Exemple #2
0
        protected override void ExecuteCmdlet()
        {
            List list = null;

            if (List != null)
            {
                list = List.GetList(CurrentWeb);
            }
            if (list != null)
            {
                var item = Identity.GetListItem(list);
                if (item != null)
                {
                    item.EnsureProperties(i => i.HasUniqueRoleAssignments);
                    if (item.HasUniqueRoleAssignments && InheritPermissions.IsPresent)
                    {
                        item.ResetRoleInheritance();
                    }
                    else if (!item.HasUniqueRoleAssignments)
                    {
                        item.BreakRoleInheritance(!ClearExisting.IsPresent, true);
                    }
                    else if (ClearExisting.IsPresent)
                    {
                        item.ResetRoleInheritance();
                        item.BreakRoleInheritance(!ClearExisting.IsPresent, true);
                    }

                    if (SystemUpdate.IsPresent)
                    {
                        item.SystemUpdate();
                    }
                    else
                    {
                        item.Update();
                    }

                    ClientContext.ExecuteQueryRetry();

                    if (ParameterSetName == "Inherit")
                    {
                        // no processing of user/group needed
                        return;
                    }

                    Principal principal = null;
                    if (ParameterSetName == "Group")
                    {
                        if (Group.Id != -1)
                        {
                            principal = CurrentWeb.SiteGroups.GetById(Group.Id);
                        }
                        else if (!string.IsNullOrEmpty(Group.Name))
                        {
                            principal = CurrentWeb.SiteGroups.GetByName(Group.Name);
                        }
                        else if (Group.Group != null)
                        {
                            principal = Group.Group;
                        }
                    }
                    else
                    {
                        principal = CurrentWeb.EnsureUser(User);
                        ClientContext.ExecuteQueryRetry();
                    }
                    if (principal != null)
                    {
                        if (!string.IsNullOrEmpty(AddRole))
                        {
                            var roleDefinition         = CurrentWeb.RoleDefinitions.GetByName(AddRole);
                            var roleDefinitionBindings = new RoleDefinitionBindingCollection(ClientContext)
                            {
                                roleDefinition
                            };
                            var roleAssignments = item.RoleAssignments;
                            roleAssignments.Add(principal, roleDefinitionBindings);
                            ClientContext.Load(roleAssignments);
                            ClientContext.ExecuteQueryRetry();
                        }
                        if (!string.IsNullOrEmpty(RemoveRole))
                        {
                            var roleAssignment         = item.RoleAssignments.GetByPrincipal(principal);
                            var roleDefinitionBindings = roleAssignment.RoleDefinitionBindings;
                            ClientContext.Load(roleDefinitionBindings);
                            ClientContext.ExecuteQueryRetry();
                            foreach (var roleDefinition in roleDefinitionBindings.Where(roleDefinition => roleDefinition.Name == RemoveRole))
                            {
                                roleDefinitionBindings.Remove(roleDefinition);
                                roleAssignment.Update();
                                ClientContext.ExecuteQueryRetry();
                                break;
                            }
                        }
                    }
                    else
                    {
                        WriteError(new ErrorRecord(new Exception("Principal not found"), "1", ErrorCategory.ObjectNotFound, null));
                    }
                }
            }
        }
        protected override void ExecuteCmdlet()
        {
            if (ParameterSpecified(nameof(Batch)))
            {
                var list = List.GetList(Batch);
                list.EnsureProperties(l => l.Id, l => l.Fields.LoadProperties(f => f.Id, f => f.Title, f => f.InternalName, f => f.TypeAsString));

                var values = ListItemHelper.GetFieldValues(list, null, Values, ClientContext);
                if (ContentType != null)
                {
                    var contentType = ContentType.GetContentType(Batch, list);
                    values.Add("ContentTypeId", contentType.StringId);
                }
                list.Items.AddBatch(Batch.Batch, values, Folder);
            }
            else
            {
                List list = List.GetList(CurrentWeb);
                ListItemCreationInformation liCI = new ListItemCreationInformation();
                if (Folder != null)
                {
                    // Create the folder if it doesn't exist
                    var rootFolder   = list.EnsureProperty(l => l.RootFolder);
                    var targetFolder =
                        CurrentWeb.EnsureFolder(rootFolder, Folder);

                    liCI.FolderUrl = targetFolder.ServerRelativeUrl;
                }
                var item = list.AddItem(liCI);

                bool systemUpdate = false;
                if (ContentType != null)
                {
                    var ct = ContentType.GetContentType(list);

                    if (ct != null)
                    {
                        item["ContentTypeId"] = ct.EnsureProperty(w => w.StringId);
                        item.Update();
                        systemUpdate = true;
                        ClientContext.ExecuteQueryRetry();
                    }
                }

                if (Values?.Count > 0)
                {
                    ListItemHelper.SetFieldValues(item, Values, this);
                }

                if (!String.IsNullOrEmpty(Label))
                {
                    IList <Microsoft.SharePoint.Client.CompliancePolicy.ComplianceTag> tags = Microsoft.SharePoint.Client.CompliancePolicy.SPPolicyStoreProxy.GetAvailableTagsForSite(ClientContext, ClientContext.Url);
                    ClientContext.ExecuteQueryRetry();

                    var tag = tags.Where(t => t.TagName == Label).FirstOrDefault();

                    if (tag != null)
                    {
                        item.SetComplianceTag(tag.TagName, tag.BlockDelete, tag.BlockEdit, tag.IsEventTag, tag.SuperLock);
                    }
                    else
                    {
                        WriteWarning("Can not find compliance tag with value: " + Label);
                    }
                }

                if (systemUpdate)
                {
                    item.SystemUpdate();
                }
                else
                {
                    item.Update();
                }
                ClientContext.Load(item);
                ClientContext.ExecuteQueryRetry();
                WriteObject(item);
            }
        }
Exemple #4
0
        protected override void ExecuteCmdlet()
        {
            var group = Identity.GetGroup(CurrentWeb);

            ClientContext.Load(group,
                               g => g.AllowMembersEditMembership,
                               g => g.AllowRequestToJoinLeave,
                               g => g.AutoAcceptRequestToJoinLeave,
                               g => g.OnlyAllowMembersViewMembership,
                               g => g.RequestToJoinLeaveEmailSetting);
            ClientContext.ExecuteQueryRetry();

            if (SetAssociatedGroup != AssociatedGroupType.None)
            {
                switch (SetAssociatedGroup)
                {
                case AssociatedGroupType.Visitors:
                {
                    CurrentWeb.AssociateDefaultGroups(null, null, group);
                    break;
                }

                case AssociatedGroupType.Members:
                {
                    CurrentWeb.AssociateDefaultGroups(null, group, null);
                    break;
                }

                case AssociatedGroupType.Owners:
                {
                    CurrentWeb.AssociateDefaultGroups(group, null, null);
                    break;
                }
                }
            }
            if (!string.IsNullOrEmpty(AddRole))
            {
                var roleDefinition         = CurrentWeb.RoleDefinitions.GetByName(AddRole);
                var roleDefinitionBindings = new RoleDefinitionBindingCollection(ClientContext);
                roleDefinitionBindings.Add(roleDefinition);
                var roleAssignments = CurrentWeb.RoleAssignments;
                roleAssignments.Add(group, roleDefinitionBindings);
                ClientContext.Load(roleAssignments);
                ClientContext.ExecuteQueryRetry();
            }
            if (!string.IsNullOrEmpty(RemoveRole))
            {
                var roleAssignment         = CurrentWeb.RoleAssignments.GetByPrincipal(group);
                var roleDefinitionBindings = roleAssignment.RoleDefinitionBindings;
                ClientContext.Load(roleDefinitionBindings);
                ClientContext.ExecuteQueryRetry();
                foreach (var roleDefinition in roleDefinitionBindings.Where(roleDefinition => roleDefinition.Name == RemoveRole))
                {
                    roleDefinitionBindings.Remove(roleDefinition);
                    roleAssignment.Update();
                    ClientContext.ExecuteQueryRetry();
                    break;
                }
            }

            var dirty = false;

            if (!string.IsNullOrEmpty(Title))
            {
                group.Title = Title;
                dirty       = true;
            }
            if (!string.IsNullOrEmpty(Description))
            {
                var groupItem = CurrentWeb.SiteUserInfoList.GetItemById(group.Id);
                CurrentWeb.Context.Load(groupItem, g => g["Notes"]);
                CurrentWeb.Context.ExecuteQueryRetry();

                var groupDescription = groupItem["Notes"]?.ToString();

                if (groupDescription != Description)
                {
                    groupItem["Notes"] = Description;
                    groupItem.Update();
                    dirty = true;
                }

                var plainTextDescription = PnP.Framework.Utilities.PnPHttpUtility.ConvertSimpleHtmlToText(Description, int.MaxValue);
                if (group.Description != plainTextDescription)
                {
                    //If the description is more than 512 characters long a server exception will be thrown.
                    group.Description = plainTextDescription;
                    dirty             = true;
                }
            }
            if (ParameterSpecified(nameof(AllowRequestToJoinLeave)) && AllowRequestToJoinLeave != group.AllowRequestToJoinLeave)
            {
                group.AllowRequestToJoinLeave = AllowRequestToJoinLeave;
                dirty = true;
            }

            if (ParameterSpecified(nameof(AutoAcceptRequestToJoinLeave)) && AutoAcceptRequestToJoinLeave != group.AutoAcceptRequestToJoinLeave)
            {
                group.AutoAcceptRequestToJoinLeave = AutoAcceptRequestToJoinLeave;
                dirty = true;
            }
            if (ParameterSpecified(nameof(AllowMembersEditMembership)) && AllowMembersEditMembership != group.AllowMembersEditMembership)
            {
                group.AllowMembersEditMembership = AllowMembersEditMembership;
                dirty = true;
            }
            if (ParameterSpecified(nameof(OnlyAllowMembersViewMembership)) && OnlyAllowMembersViewMembership != group.OnlyAllowMembersViewMembership)
            {
                group.OnlyAllowMembersViewMembership = OnlyAllowMembersViewMembership;
                dirty = true;
            }
            if (RequestToJoinEmail != group.RequestToJoinLeaveEmailSetting)
            {
                group.RequestToJoinLeaveEmailSetting = RequestToJoinEmail;
                dirty = true;
            }
            if (dirty)
            {
                group.Update();
                ClientContext.ExecuteQueryRetry();
            }


            if (!string.IsNullOrEmpty(Owner))
            {
                Principal groupOwner;

                try
                {
                    groupOwner  = CurrentWeb.EnsureUser(Owner);
                    group.Owner = groupOwner;
                    group.Update();
                    ClientContext.ExecuteQueryRetry();
                }
                catch
                {
                    groupOwner  = CurrentWeb.SiteGroups.GetByName(Owner);
                    group.Owner = groupOwner;
                    group.Update();
                    ClientContext.ExecuteQueryRetry();
                }
            }
        }
Exemple #5
0
        protected override void ExecuteCmdlet()
        {
            var dirty = false;

            foreach (var key in MyInvocation.BoundParameters.Keys)
            {
                switch (key)
                {
                case nameof(SiteLogoUrl):
                    CurrentWeb.SiteLogoUrl = SiteLogoUrl;
                    dirty = true;
                    break;

                case nameof(AlternateCssUrl):
                    CurrentWeb.AlternateCssUrl = AlternateCssUrl;
                    dirty = true;
                    break;

                case nameof(Title):
                    CurrentWeb.Title = Title;
                    dirty            = true;
                    break;

                case nameof(Description):
                    CurrentWeb.Description = Description;
                    dirty = true;
                    break;

                case nameof(MasterUrl):
                    CurrentWeb.MasterUrl = MasterUrl;
                    dirty = true;
                    break;

                case nameof(CustomMasterUrl):
                    CurrentWeb.CustomMasterUrl = CustomMasterUrl;
                    dirty = true;
                    break;

                case nameof(QuickLaunchEnabled):
                    CurrentWeb.QuickLaunchEnabled = QuickLaunchEnabled.ToBool();
                    dirty = true;
                    break;

                case nameof(MembersCanShare):
                    CurrentWeb.MembersCanShare = MembersCanShare.ToBool();
                    dirty = true;
                    break;

                case nameof(NoCrawl):
                    CurrentWeb.NoCrawl = NoCrawl.ToBool();
                    dirty = true;
                    break;

                case nameof(HeaderLayout):
                    CurrentWeb.HeaderLayout = HeaderLayout;
                    dirty = true;
                    break;

                case nameof(HeaderEmphasis):
                    CurrentWeb.HeaderEmphasis = HeaderEmphasis;
                    dirty = true;
                    break;

                case nameof(NavAudienceTargetingEnabled):
                    CurrentWeb.NavAudienceTargetingEnabled = NavAudienceTargetingEnabled.ToBool();
                    dirty = true;
                    break;

                case nameof(MegaMenuEnabled):
                    CurrentWeb.MegaMenuEnabled = MegaMenuEnabled.ToBool();
                    dirty = true;
                    break;

                case nameof(DisablePowerAutomate):
                    CurrentWeb.DisableFlows = DisablePowerAutomate.ToBool();
                    dirty = true;
                    break;

                case nameof(CommentsOnSitePagesDisabled):
                    CurrentWeb.CommentsOnSitePagesDisabled = CommentsOnSitePagesDisabled.ToBool();
                    dirty = true;
                    break;
                }
            }

            if (dirty)
            {
                CurrentWeb.Update();
                ClientContext.ExecuteQueryRetry();
            }
        }
Exemple #6
0
 protected override void ExecuteCmdlet()
 {
     CurrentWeb.ActivateFeature(new Guid("E87CA965-5E07-4A23-B007-DDD4B5AFB9C7"));
 }
Exemple #7
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSetName == ParameterSet_ASFILE)
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
                if (string.IsNullOrEmpty(NewFileName))
                {
                    FileName = System.IO.Path.GetFileName(Path);
                }
                else
                {
                    FileName = NewFileName;
                }
            }

            var folder  = EnsureFolder();
            var fileUrl = UrlUtility.Combine(folder.ServerRelativeUrl, FileName);

            string targetContentTypeId = null;

            // Check to see if the Content Type exists. If it doesn't we are going to throw an exception and block this transaction right here.
            if (ContentType != null)
            {
                CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl);
                var list = CurrentWeb.GetListByUrl(folder.ServerRelativeUrl.Substring(CurrentWeb.ServerRelativeUrl.TrimEnd('/').Length + 1));
                if (list is null)
                {
                    throw new PSArgumentException("The folder specified does not have a corresponding list", nameof(Folder));
                }
                targetContentTypeId = ContentType?.GetIdOrThrow(nameof(ContentType), list);
            }

            // Check if the file exists
            if (Checkout)
            {
                try
                {
                    var existingFile = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(fileUrl));

                    existingFile.EnsureProperty(f => f.Exists);
                    if (existingFile.Exists)
                    {
                        CurrentWeb.CheckOutFile(fileUrl);
                    }
                }
                catch
                { // Swallow exception, file does not exist
                }
            }
            Microsoft.SharePoint.Client.File file;
            if (ParameterSetName == ParameterSet_ASFILE)
            {
                file = folder.UploadFile(FileName, Path, true);
            }
            else
            {
                file = folder.UploadFile(FileName, Stream, true);
            }

            bool updateRequired = false;
            var  item           = file.ListItemAllFields;

            if (Values != null)
            {
                ListItemHelper.SetFieldValues(item, Values, this);
                updateRequired = true;
            }

            if (ContentType != null)
            {
                item["ContentTypeId"] = targetContentTypeId;
                updateRequired        = true;
            }

            if (updateRequired)
            {
                item.SystemUpdate();
            }
            if (Checkout)
            {
                CurrentWeb.CheckInFile(fileUrl, CheckinType.MajorCheckIn, CheckInComment);
            }

            if (Publish)
            {
                CurrentWeb.PublishFile(fileUrl, PublishComment);
            }

            if (Approve)
            {
                CurrentWeb.ApproveFile(fileUrl, ApproveComment);
            }

            ClientContext.Load(file);
            ClientContext.ExecuteQueryRetry();
            WriteObject(file);
        }
Exemple #8
0
        protected override void ExecuteCmdlet()
        {
            string configOutput = string.Empty;

            switch (Scope)
            {
            case SearchConfigurationScope.Web:
            {
                configOutput = CurrentWeb.GetSearchConfiguration();
                break;
            }

            case SearchConfigurationScope.Site:
            {
                configOutput = ClientContext.Site.GetSearchConfiguration();
                break;
            }

            case SearchConfigurationScope.Subscription:
            {
                if (!ClientContext.Url.ToLower().Contains("-admin"))
                {
                    throw new InvalidOperationException(Resources.CurrentSiteIsNoTenantAdminSite);
                }

                SearchObjectOwner owningScope = new SearchObjectOwner(ClientContext, SearchObjectLevel.SPSiteSubscription);
                var config = new SearchConfigurationPortability(ClientContext);
                ClientResult <string> configuration = config.ExportSearchConfiguration(owningScope);
                ClientContext.ExecuteQueryRetry();

                configOutput = configuration.Value;
            }
            break;
            }

            if (Path != null)
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
                System.IO.File.WriteAllText(Path, configOutput);
            }
            else
            {
                if (OutputFormat == OutputFormat.CompleteXml)
                {
                    WriteObject(configOutput);
                }
                else if (OutputFormat == OutputFormat.ManagedPropertyMappings)
                {
                    StringReader sr  = new StringReader(configOutput);
                    var          doc = XDocument.Load(sr);
                    var          mps = GetCustomManagedProperties(doc);

                    foreach (var mp in mps)
                    {
                        mp.Aliases  = new List <string>();
                        mp.Mappings = new List <string>();

                        var mappings = GetCpMappingsFromPid(doc, mp.Pid);
                        mp.Mappings = mappings;
                        var aliases = GetAliasesFromPid(doc, mp.Pid);
                        mp.Aliases = aliases;
                    }
                    WriteObject(mps);
                }
            }
        }
Exemple #9
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSetName == ParameterSet_ALLBYLOCATION)
            {
                if (Tree.IsPresent)
                {
                    NavigationNodeCollection navigationNodes = null;
                    if (Location == NavigationType.SearchNav)
                    {
                        navigationNodes = CurrentWeb.Navigation.GetNodeById(1040).Children;
                    }
                    else if (Location == NavigationType.Footer)
                    {
                        navigationNodes = CurrentWeb.LoadFooterNavigation();
                    }
                    else
                    {
                        navigationNodes = Location == NavigationType.QuickLaunch ? CurrentWeb.Navigation.QuickLaunch : CurrentWeb.Navigation.TopNavigationBar;
                    }
                    if (navigationNodes != null)
                    {
                        var nodesCollection = ClientContext.LoadQuery(navigationNodes);
                        ClientContext.ExecuteQueryRetry();
                        WriteObject(GetTree(nodesCollection, 0));
                    }
                }
                else
                {
                    NavigationNodeCollection nodes = null;
                    switch (Location)
                    {
                    case NavigationType.QuickLaunch:
                    {
                        nodes = CurrentWeb.Navigation.QuickLaunch;
                        break;
                    }

                    case NavigationType.TopNavigationBar:
                    {
                        nodes = CurrentWeb.Navigation.TopNavigationBar;
                        break;
                    }

                    case NavigationType.SearchNav:
                    {
                        nodes = CurrentWeb.Navigation.GetNodeById(1040).Children;
                        break;
                    }

                    case NavigationType.Footer:
                    {
                        nodes = CurrentWeb.LoadFooterNavigation();
                        break;
                    }
                    }
                    if (nodes != null)
                    {
                        ClientContext.Load(nodes);
                        ClientContext.ExecuteQueryRetry();
                        WriteObject(nodes, true);
                    }
                }
            }
            if (ParameterSpecified(nameof(Id)))
            {
                var node = CurrentWeb.Navigation.GetNodeById(Id);
                ClientContext.Load(node);
                ClientContext.Load(node, n => n.Children.IncludeWithDefaultProperties());
                ClientContext.ExecuteQueryRetry();
                if (Tree.IsPresent)
                {
                    WriteObject(GetTree(new List <NavigationNode>()
                    {
                        node
                    }, 0));
                }
                else
                {
                    WriteObject(node);
                }
            }
        }
Exemple #10
0
        private string GetServerRelativeUrl(string url)
        {
            var serverRelativeUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl);

            return(UrlUtility.Combine(serverRelativeUrl, url));
        }
        protected override void ExecuteCmdlet()
        {
            TaxonomyItem taxItem;
            Field        field;

            if (ParameterSetName == "Path")
            {
                taxItem = ClientContext.Site.GetTaxonomyItemByPath(TermSetPath, TermPathDelimiter);
            }
            else
            {
                var taxSession = ClientContext.Site.GetTaxonomySession();
                var termStore  = taxSession.GetDefaultKeywordsTermStore();
                try
                {
                    taxItem = termStore.GetTermSet(TaxonomyItemId);
                }
                catch
                {
                    try
                    {
                        taxItem = termStore.GetTerm(TaxonomyItemId);
                    }
                    catch
                    {
                        throw new Exception($"Taxonomy Item with Id {TaxonomyItemId} not found");
                    }
                }
                taxItem.EnsureProperty(t => t.Id);
            }

            if (Id == Guid.Empty)
            {
                Id = Guid.NewGuid();
            }

            var fieldCI = new TaxonomyFieldCreationInformation()
            {
                Id               = Id,
                InternalName     = InternalName,
                DisplayName      = DisplayName,
                Group            = Group,
                TaxonomyItem     = taxItem,
                MultiValue       = MultiValue,
                Required         = Required,
                AddToDefaultView = AddToDefaultView
            };

            if (ParameterSpecified(nameof(FieldOptions)))
            {
                fieldCI.FieldOptions = FieldOptions;
            }

            if (List != null)
            {
                var list = List.GetList(CurrentWeb);
                field = list.CreateTaxonomyField(fieldCI);
            }
            else
            {
                field = CurrentWeb.CreateTaxonomyField(fieldCI);
            }
            WriteObject(ClientContext.CastTo <TaxonomyField>(field));
        }
Exemple #12
0
        protected override void ExecuteCmdlet()
        {
            string hostUrl;

            if (ParameterSpecified(nameof(WebUrl)) && !string.IsNullOrWhiteSpace(WebUrl))
            {
                hostUrl = WebUrl;
            }
            else
            {
                CurrentWeb.EnsureProperty(w => w.Url);
                hostUrl = CurrentWeb.Url;
            }

            WriteVerbose($"Site scripts will be applied to site {hostUrl}");

            IEnumerable <InvokeSiteScriptActionResponse> result = null;

            switch (ParameterSetName)
            {
            case ParameterSet_SCRIPTCONTENTS:
                if (ParameterSpecified(nameof(WhatIf)))
                {
                    WriteVerbose($"Provided Site Script through {nameof(Script)} will not be executed due to {nameof(WhatIf)} option being provided");
                }
                else
                {
                    WriteVerbose($"Executing provided script");
                    result = PnP.PowerShell.Commands.Utilities.SiteTemplates.InvokeSiteScript(HttpClient, AccessToken, Script, hostUrl).GetAwaiter().GetResult().Items;
                }
                break;

            case ParameterSet_SITESCRIPTREFERENCE:
                // Try to create an admin context from the current context
                var tenant  = new Tenant(ClientContext);
                var scripts = Identity.GetTenantSiteScript(tenant);

                if (scripts == null || scripts.Length == 0)
                {
                    throw new PSArgumentException($"No site scripts found matching the identity provided through {nameof(Identity)}", nameof(Identity));
                }

                // Execute each of the Site Scripts that have been found
                foreach (var script in scripts)
                {
                    script.EnsureProperties(s => s.Content, s => s.Title, s => s.Id, s => s.Version, s => s.Description, s => s.IsSiteScriptPackage);

                    if (ParameterSpecified(nameof(WhatIf)))
                    {
                        WriteVerbose($"Site script '{script.Title}' ({script.Id}) will not be executed due to {nameof(WhatIf)} option being provided");
                    }
                    else
                    {
                        WriteVerbose($"Executing site script '{script.Title}' ({script.Id})");
                        result = PnP.PowerShell.Commands.Utilities.SiteTemplates.InvokeSiteScript(HttpClient, AccessToken, script, hostUrl).GetAwaiter().GetResult().Items;
                    }
                }
                break;
            }

            // Only if there are results, show them
            if (result != null)
            {
                WriteVerbose($"Site script result: {result.Count(r => r.ErrorCode == 0)} actions successful, {result.Count(r => r.ErrorCode != 0)} failed");
                WriteObject(result, true);
            }
        }
 protected override void ExecuteCmdlet()
 {
     CurrentWeb.ReIndexWeb();
 }
Exemple #14
0
        protected override void ExecuteCmdlet()
        {
            var serverRelativeUrl = string.Empty;

            var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl);

            if (!Url.ToLower().StartsWith(webUrl.ToLower()))
            {
                serverRelativeUrl = UrlUtility.Combine(webUrl, Url);
            }
            else
            {
                serverRelativeUrl = Url;
            }

            File file;

            file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl));

            ClientContext.Load(file, f => f.Exists, f => f.Versions.IncludeWithDefaultProperties(i => i.CreatedBy));
            ClientContext.ExecuteQueryRetry();

            if (file.Exists)
            {
                var versions = file.Versions;

                switch (ParameterSetName)
                {
                case ParameterSetName_ALL:
                {
                    if (Force || ShouldContinue("Remove all versions?", Resources.Confirm))
                    {
                        versions.DeleteAll();
                        ClientContext.ExecuteQueryRetry();
                    }
                    break;
                }

                case ParameterSetName_BYID:
                {
                    if (Force || ShouldContinue("Remove a version?", Resources.Confirm))
                    {
                        if (!string.IsNullOrEmpty(Identity.Label))
                        {
                            if (Recycle.IsPresent)
                            {
                                versions.RecycleByLabel(Identity.Label);
                            }
                            else
                            {
                                versions.DeleteByLabel(Identity.Label);
                            }
                            ClientContext.ExecuteQueryRetry();
                        }
                        else if (Identity.Id != -1)
                        {
                            if (Recycle.IsPresent)
                            {
                                versions.RecycleByID(Identity.Id);
                            }
                            else
                            {
                                versions.DeleteByID(Identity.Id);
                            }
                            ClientContext.ExecuteQueryRetry();
                        }
                    }
                    break;
                }
                }
            }
            else
            {
                throw new PSArgumentException("File not found", nameof(Url));
            }
        }
        protected override void ExecuteCmdlet()
        {
            var requiresWebUpdate = false;

            if (ParameterSpecified(nameof(SiteLogoUrl)))
            {
                WriteVerbose($"Setting site logo image to '{SiteLogoUrl}'");

                var stringContent = new StringContent("{\"relativeLogoUrl\":\"" + SiteLogoUrl + "\",\"type\":0,\"aspect\":1}");
                stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                CurrentWeb.EnsureProperties(p => p.Url);
                var result = GraphHelper.PostAsync(HttpClient, $"{CurrentWeb.Url.TrimEnd('/')}/_api/siteiconmanager/setsitelogo", AccessToken, stringContent).GetAwaiter().GetResult();
                WriteVerbose($"Response from setsitelogo request: {result.StatusCode}");
            }

            if (ParameterSpecified(nameof(LogoAlignment)))
            {
                WriteVerbose($"Setting site logo alignment to '{LogoAlignment}'");
                CurrentWeb.LogoAlignment = LogoAlignment;
                requiresWebUpdate        = true;
            }

            if (ParameterSpecified(nameof(HeaderLayout)))
            {
                WriteVerbose($"Setting header layout to '{HeaderLayout}'");
                CurrentWeb.HeaderLayout = HeaderLayout;
                requiresWebUpdate       = true;
            }

            if (ParameterSpecified(nameof(HeaderEmphasis)))
            {
                WriteVerbose($"Setting header emphasis to '{HeaderEmphasis}'");
                CurrentWeb.HeaderEmphasis = HeaderEmphasis;
                requiresWebUpdate         = true;
            }

            if (ParameterSpecified(nameof(HideTitleInHeader)))
            {
                WriteVerbose($"Setting hide title in header to '{HideTitleInHeader}'");
                CurrentWeb.HideTitleInHeader = HideTitleInHeader;
                requiresWebUpdate            = true;
            }

            if (ParameterSpecified(nameof(HeaderBackgroundImageUrl)) || ParameterSpecified(nameof(HeaderBackgroundImageFocalX)) || ParameterSpecified(nameof(HeaderBackgroundImageFocalY)))
            {
                var setSiteBackgroundImageInstructions = new List <string>();

                if (ParameterSpecified(nameof(HeaderBackgroundImageUrl)))
                {
                    WriteVerbose($"Setting header background image to '{HeaderBackgroundImageUrl}'");
                    setSiteBackgroundImageInstructions.Add("\"relativeLogoUrl\":\"" + UrlUtilities.UrlEncode(HeaderBackgroundImageUrl) + "\"");
                }
                else
                {
                    WriteVerbose($"Setting header background image isFocalPatch to 'true'");
                    setSiteBackgroundImageInstructions.Add("\"isFocalPatch\":true");
                }
                if (ParameterSpecified(nameof(HeaderBackgroundImageFocalX)))
                {
                    WriteVerbose($"Setting header background image focal point X to '{HeaderBackgroundImageFocalX.ToString().Replace(',', '.')}'");
                    setSiteBackgroundImageInstructions.Add("\"focalx\":" + HeaderBackgroundImageFocalX.ToString().Replace(',', '.'));
                }
                if (ParameterSpecified(nameof(HeaderBackgroundImageFocalY)))
                {
                    WriteVerbose($"Setting header background image focal point Y to '{HeaderBackgroundImageFocalY.ToString().Replace(',', '.')}'");
                    setSiteBackgroundImageInstructions.Add("\"focaly\":" + HeaderBackgroundImageFocalY.ToString().Replace(',', '.'));
                }

                if (setSiteBackgroundImageInstructions.Count > 0)
                {
                    var stringContent = new StringContent("{" + string.Join(",", setSiteBackgroundImageInstructions) + ",\"type\":2,\"aspect\":0}");
                    stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    CurrentWeb.EnsureProperties(p => p.Url);
                    var result = GraphHelper.PostAsync(HttpClient, $"{CurrentWeb.Url.TrimEnd('/')}/_api/siteiconmanager/setsitelogo", AccessToken, stringContent).GetAwaiter().GetResult();
                    WriteVerbose($"Response from setsitelogo request: {result.StatusCode}");
                }
            }

            if (requiresWebUpdate)
            {
                WriteVerbose("Updating web");
                CurrentWeb.Update();
                ClientContext.ExecuteQueryRetry();
            }
        }
 protected override void ExecuteCmdlet()
 {
     CurrentWeb.ResetFileToPreviousVersion(ServerRelativeUrl, CheckinType, CheckInComment);
 }
        protected override void ExecuteCmdlet()
        {
            List list = null;

            if (List != null)
            {
                list = List.GetList(CurrentWeb);
            }
            if (list != null)
            {
                // Try to get an instance to the folder
                var folder = Identity.GetFolder(CurrentWeb);

                // Ensure the folder has been found
                if (folder == null)
                {
                    WriteError(new ErrorRecord(new Exception("Folder not found"), "1", ErrorCategory.ObjectNotFound, null));
                }

                // Ensure we have access to the ListItemAllFields property of the folder
                folder.EnsureProperty(f => f.ListItemAllFields);

                // Validate that the ListItemAllFields contains the Id which represents the ListItem ID equivallent for this folder
                if (folder.ListItemAllFields.Id <= 0)
                {
                    WriteError(new ErrorRecord(new Exception("ListItemId on folder not found"), "1", ErrorCategory.InvalidData, null));
                }

                // Get the list item which is the equivallent of the folder
                var item = list.GetItemById(folder.ListItemAllFields.Id);

                // Perform the permission operations on the listitem belonging to the folder
                item.EnsureProperties(i => i.HasUniqueRoleAssignments);
                if (item.HasUniqueRoleAssignments && InheritPermissions.IsPresent)
                {
                    item.ResetRoleInheritance();
                }
                else if (!item.HasUniqueRoleAssignments)
                {
                    item.BreakRoleInheritance(!ClearExisting.IsPresent, true);
                }
                else if (ClearExisting.IsPresent)
                {
                    item.ResetRoleInheritance();
                    item.BreakRoleInheritance(!ClearExisting.IsPresent, true);
                }

                if (SystemUpdate.IsPresent)
                {
                    item.SystemUpdate();
                }
                else
                {
                    item.Update();
                }
                ClientContext.ExecuteQueryRetry();
                if (ParameterSetName == "Inherit")
                {
                    // no processing of user/group needed
                    return;
                }

                Principal principal = null;
                if (ParameterSetName == "Group")
                {
                    if (Group.Id != -1)
                    {
                        principal = CurrentWeb.SiteGroups.GetById(Group.Id);
                    }
                    else if (!string.IsNullOrEmpty(Group.Name))
                    {
                        principal = CurrentWeb.SiteGroups.GetByName(Group.Name);
                    }
                    else if (Group.Group != null)
                    {
                        principal = Group.Group;
                    }
                }
                else
                {
                    principal = CurrentWeb.EnsureUser(User);
                    ClientContext.ExecuteQueryRetry();
                }
                if (principal != null)
                {
                    if (!string.IsNullOrEmpty(AddRole))
                    {
                        var roleDefinition         = CurrentWeb.RoleDefinitions.GetByName(AddRole);
                        var roleDefinitionBindings = new RoleDefinitionBindingCollection(ClientContext)
                        {
                            roleDefinition
                        };
                        var roleAssignments = item.RoleAssignments;
                        roleAssignments.Add(principal, roleDefinitionBindings);
                        ClientContext.Load(roleAssignments);
                        ClientContext.ExecuteQueryRetry();
                    }
                    if (!string.IsNullOrEmpty(RemoveRole))
                    {
                        var roleAssignment         = item.RoleAssignments.GetByPrincipal(principal);
                        var roleDefinitionBindings = roleAssignment.RoleDefinitionBindings;
                        ClientContext.Load(roleDefinitionBindings);
                        ClientContext.ExecuteQueryRetry();
                        foreach (var roleDefinition in roleDefinitionBindings.Where(roleDefinition => roleDefinition.Name == RemoveRole))
                        {
                            roleDefinitionBindings.Remove(roleDefinition);
                            roleAssignment.Update();
                            ClientContext.ExecuteQueryRetry();
                            break;
                        }
                    }
                }
                else
                {
                    WriteError(new ErrorRecord(new Exception("Principal not found"), "1", ErrorCategory.ObjectNotFound, null));
                }
            }
        }
        protected override void ExecuteCmdlet()
        {
            CurrentWeb.EnsureProperty(w => w.Url);
            ProvisioningTemplate provisioningTemplate;

            FileConnectorBase fileConnector;

            if (ParameterSpecified(nameof(Path)))
            {
                bool   templateFromFileSystem = !Path.ToLower().StartsWith("http");
                string templateFileName       = System.IO.Path.GetFileName(Path);
                if (templateFromFileSystem)
                {
                    if (!System.IO.Path.IsPathRooted(Path))
                    {
                        Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                    }
                    if (!System.IO.File.Exists(Path))
                    {
                        throw new FileNotFoundException($"File not found");
                    }
                    if (!string.IsNullOrEmpty(ResourceFolder))
                    {
                        if (!System.IO.Path.IsPathRooted(ResourceFolder))
                        {
                            ResourceFolder = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path,
                                                                    ResourceFolder);
                        }
                    }
                    var fileInfo = new FileInfo(Path);
                    fileConnector = new FileSystemConnector(fileInfo.DirectoryName, "");
                }
                else
                {
                    Uri fileUri         = new Uri(Path);
                    var webUrl          = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, fileUri);
                    var templateContext = ClientContext.Clone(webUrl.ToString());

                    var library = Path.ToLower().Replace(templateContext.Url.ToLower(), "").TrimStart('/');
                    var idx     = library.IndexOf("/", StringComparison.Ordinal);
                    library = library.Substring(0, idx);

                    // This syntax creates a SharePoint connector regardless we have the -InputInstance argument or not
                    fileConnector = new SharePointConnector(templateContext, templateContext.Url, library);
                }

                // If we don't have the -InputInstance parameter, we load the template from the source connector

                Stream stream           = fileConnector.GetFileStream(templateFileName);
                var    isOpenOfficeFile = FileUtilities.IsOpenOfficeFile(stream);
                XMLTemplateProvider provider;
                if (isOpenOfficeFile)
                {
                    var openXmlConnector = new OpenXMLConnector(templateFileName, fileConnector);
                    provider = new XMLOpenXMLTemplateProvider(openXmlConnector);
                    if (!String.IsNullOrEmpty(openXmlConnector.Info?.Properties?.TemplateFileName))
                    {
                        templateFileName = openXmlConnector.Info.Properties.TemplateFileName;
                    }
                    else
                    {
                        templateFileName = templateFileName.Substring(0, templateFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";
                    }
                }
                else
                {
                    if (templateFromFileSystem)
                    {
                        provider = new XMLFileSystemTemplateProvider(fileConnector.Parameters[FileConnectorBase.CONNECTIONSTRING] + "", "");
                    }
                    else
                    {
                        throw new NotSupportedException("Only .pnp package files are supported from a SharePoint library");
                    }
                }

                if (ParameterSpecified(nameof(TemplateId)))
                {
                    provisioningTemplate = provider.GetTemplate(templateFileName, TemplateId, null, TemplateProviderExtensions);
                }
                else
                {
                    provisioningTemplate = provider.GetTemplate(templateFileName, TemplateProviderExtensions);
                }

                if (provisioningTemplate == null)
                {
                    // If we don't have the template, raise an error and exit
                    WriteError(new ErrorRecord(new Exception("The -Path parameter targets an invalid repository or template object."), "WRONG_PATH", ErrorCategory.SyntaxError, null));
                    return;
                }

                if (isOpenOfficeFile)
                {
                    provisioningTemplate.Connector = provider.Connector;
                }
                else
                {
                    if (ResourceFolder != null)
                    {
                        var fileSystemConnector = new FileSystemConnector(ResourceFolder, "");
                        provisioningTemplate.Connector = fileSystemConnector;
                    }
                    else
                    {
                        provisioningTemplate.Connector = provider.Connector;
                    }
                }
            }

            else
            {
                provisioningTemplate = InputInstance;

                if (ResourceFolder != null)
                {
                    var fileSystemConnector = new FileSystemConnector(ResourceFolder, "");
                    provisioningTemplate.Connector = fileSystemConnector;
                }
                else
                {
                    if (Path != null)
                    {
                        if (!System.IO.Path.IsPathRooted(Path))
                        {
                            Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                        }
                    }
                    else
                    {
                        Path = SessionState.Path.CurrentFileSystemLocation.Path;
                    }
                    var fileInfo = new FileInfo(Path);
                    fileConnector = new FileSystemConnector(System.IO.Path.IsPathRooted(fileInfo.FullName) ? fileInfo.FullName : fileInfo.DirectoryName, "");
                    provisioningTemplate.Connector = fileConnector;
                }
            }

            if (Parameters != null)
            {
                foreach (var parameter in Parameters.Keys)
                {
                    if (provisioningTemplate.Parameters.ContainsKey(parameter.ToString()))
                    {
                        provisioningTemplate.Parameters[parameter.ToString()] = Parameters[parameter].ToString();
                    }
                    else
                    {
                        provisioningTemplate.Parameters.Add(parameter.ToString(), Parameters[parameter].ToString());
                    }
                }
            }

            var applyingInformation = new ProvisioningTemplateApplyingInformation();

            if (ParameterSpecified(nameof(Handlers)))
            {
                applyingInformation.HandlersToProcess = Handlers;
            }
            if (ParameterSpecified(nameof(ExcludeHandlers)))
            {
                foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers)))
                {
                    if (!ExcludeHandlers.Has(handler) && handler != Handlers.All)
                    {
                        Handlers = Handlers | handler;
                    }
                }
                applyingInformation.HandlersToProcess = Handlers;
            }

            if (ExtensibilityHandlers != null)
            {
                applyingInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList();
            }

            applyingInformation.ProgressDelegate = (message, step, total) =>
            {
                if (message != null)
                {
                    var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));
                    progressRecord.Activity          = $"Applying template to {CurrentWeb.Url}";
                    progressRecord.StatusDescription = message;
                    progressRecord.PercentComplete   = percentage;
                    progressRecord.RecordType        = ProgressRecordType.Processing;
                    WriteProgress(progressRecord);
                }
            };

            var warningsShown = new List <string>();

            applyingInformation.MessagesDelegate = (message, type) =>
            {
                switch (type)
                {
                case ProvisioningMessageType.Warning:
                {
                    if (!warningsShown.Contains(message))
                    {
                        WriteWarning(message);
                        warningsShown.Add(message);
                    }
                    break;
                }

                case ProvisioningMessageType.Progress:
                {
                    if (message != null)
                    {
                        var activity = message;
                        if (message.IndexOf("|") > -1)
                        {
                            var messageSplitted = message.Split('|');
                            if (messageSplitted.Length == 4)
                            {
                                var current = double.Parse(messageSplitted[2]);
                                var total   = double.Parse(messageSplitted[3]);
                                subProgressRecord.RecordType        = ProgressRecordType.Processing;
                                subProgressRecord.Activity          = string.IsNullOrEmpty(messageSplitted[0]) ? "-" : messageSplitted[0];
                                subProgressRecord.StatusDescription = string.IsNullOrEmpty(messageSplitted[1]) ? "-" : messageSplitted[1];
                                subProgressRecord.PercentComplete   = Convert.ToInt32((100 / total) * current);
                                WriteProgress(subProgressRecord);
                            }
                            else
                            {
                                subProgressRecord.Activity          = "Processing";
                                subProgressRecord.RecordType        = ProgressRecordType.Processing;
                                subProgressRecord.StatusDescription = activity;
                                subProgressRecord.PercentComplete   = 0;
                                WriteProgress(subProgressRecord);
                            }
                        }
                        else
                        {
                            subProgressRecord.Activity          = "Processing";
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.StatusDescription = activity;
                            subProgressRecord.PercentComplete   = 0;
                            WriteProgress(subProgressRecord);
                        }
                    }
                    break;
                }

                case ProvisioningMessageType.Completed:
                {
                    WriteProgress(new ProgressRecord(1, message, " ")
                        {
                            RecordType = ProgressRecordType.Completed
                        });
                    break;
                }
                }
            };

            applyingInformation.OverwriteSystemPropertyBagValues = OverwriteSystemPropertyBagValues;
            applyingInformation.IgnoreDuplicateDataRowErrors     = IgnoreDuplicateDataRowErrors;
            applyingInformation.ClearNavigation = ClearNavigation;
            applyingInformation.ProvisionContentTypesToSubWebs = ProvisionContentTypesToSubWebs;
            applyingInformation.ProvisionFieldsToSubWebs       = ProvisionFieldsToSubWebs;

            using (var provisioningContext = new PnPProvisioningContext(async(resource, scope) =>
            {
                return(await TokenRetrieval.GetAccessTokenAsync(resource, scope));
                // if (resource.ToLower().StartsWith("https://"))
                // {
                //     var uri = new Uri(resource);
                //     resource = uri.Authority;
                // }
                // if (resource.ToLower().Contains(".sharepoint."))
                // {
                //     // SharePoint
                //     var authManager = PnPConnection.CurrentConnection.Context.GetContextSettings().AuthenticationManager;
                //     if (authManager != null)
                //     {
                //         var token = await authManager.GetAccessTokenAsync($"https://{resource}");
                //         if (token != null)
                //         {
                //             return token;
                //         }
                //     }
                // }

                // // Get Azure AD Token
                // if (PnPConnection.CurrentConnection != null)
                // {
                //     var graphAccessToken = await PnPConnection.CurrentConnection.TryGetAccessTokenAsync(Enums.TokenAudience.MicrosoftGraph);
                //     if (graphAccessToken != null)
                //     {
                //         // Authenticated using -Graph or using another way to retrieve the accesstoken with Connect-PnPOnline
                //         return graphAccessToken;
                //     }
                // }

                // if (PnPConnection.CurrentConnection.PSCredential != null)
                // {
                //     // Using normal credentials
                //     return await TokenHandler.AcquireTokenAsync(resource, null);
                // }
                // else
                // {
                //     // No token...
                //     if (resource.ToLower().Contains(".sharepoint."))
                //     {
                //         return null;
                //     }
                //     else
                //     {
                //         throw new PSInvalidOperationException($"Your template contains artifacts that require an access token for {resource}. Either connect with a clientid which the appropriate permissions, or use credentials with Connect-PnPOnline after providing consent to the PnP Management Shell application first by executing: Register-PnPManagementShellAccess. See https://pnp.github.io/powershell/articles/authentication.html");
                //     }
                // }
            }))
            {
                CurrentWeb.ApplyProvisioningTemplate(provisioningTemplate, applyingInformation);
            }

            WriteProgress(new ProgressRecord(0, $"Applying template to {CurrentWeb.Url}", " ")
            {
                RecordType = ProgressRecordType.Completed
            });
        }
        protected override void ExecuteCmdlet()
        {
            // Retrieve the list
            List list = null;

            if (List != null)
            {
                list = List.GetList(CurrentWeb);
            }

            // Ensure the list exists
            if (list == null)
            {
                throw new PSArgumentException("The provided List through the List parameter could not be found", nameof(List));
            }

            // Retrieve the list item
            var item = Identity.GetListItem(list);

            // Ensure the list item exists
            if (item == null)
            {
                throw new PSArgumentException("The provided list item through the Identity parameter could not be found", nameof(Identity));
            }

            item.EnsureProperties(i => i.HasUniqueRoleAssignments);

            if (ParameterSetName == ParameterSet_INHERIT)
            {
                if (item.HasUniqueRoleAssignments && InheritPermissions.IsPresent)
                {
                    item.ResetRoleInheritance();
                    if (SystemUpdate)
                    {
                        item.SystemUpdate();
                    }
                    else
                    {
                        item.Update();
                    }
                    ClientContext.ExecuteQueryRetry();
                }
            }
            else
            {
                if (!item.HasUniqueRoleAssignments)
                {
                    item.BreakRoleInheritance(!ClearExisting.IsPresent, true);
                }
                else if (ClearExisting.IsPresent)
                {
                    item.ResetRoleInheritance();
                    item.BreakRoleInheritance(!ClearExisting.IsPresent, true);
                }

                if (SystemUpdate.IsPresent)
                {
                    item.SystemUpdate();
                }
                else
                {
                    item.Update();
                }

                ClientContext.ExecuteQueryRetry();

                Principal principal = null;
                if (ParameterSetName == ParameterSet_GROUP)
                {
                    if (Group.Id != -1)
                    {
                        principal = CurrentWeb.SiteGroups.GetById(Group.Id);
                    }
                    else if (!string.IsNullOrEmpty(Group.Name))
                    {
                        principal = CurrentWeb.SiteGroups.GetByName(Group.Name);
                    }
                    else if (Group.Group != null)
                    {
                        principal = Group.Group;
                    }
                }
                else
                {
                    principal = CurrentWeb.EnsureUser(User);
                    ClientContext.ExecuteQueryRetry();
                }
                if (principal == null)
                {
                    throw new PSArgumentException("The provided principal through the Principal parameter could not be found", nameof(Principal));
                }
                if (ParameterSpecified(nameof(AddRole)))
                {
                    var roleDefinition         = AddRole.GetRoleDefinition(ClientContext.Site);
                    var roleDefinitionBindings = new RoleDefinitionBindingCollection(ClientContext)
                    {
                        roleDefinition
                    };
                    var roleAssignments = item.RoleAssignments;
                    roleAssignments.Add(principal, roleDefinitionBindings);
                    ClientContext.Load(roleAssignments);
                    ClientContext.ExecuteQueryRetry();
                }
                if (ParameterSpecified(nameof(RemoveRole)))
                {
                    var roleDefinition         = RemoveRole.GetRoleDefinition(ClientContext.Site);
                    var roleAssignment         = item.RoleAssignments.GetByPrincipal(principal);
                    var roleDefinitionBindings = roleAssignment.RoleDefinitionBindings;
                    ClientContext.Load(roleDefinitionBindings);
                    ClientContext.ExecuteQueryRetry();
                    foreach (var roleDefinitionBinding in roleDefinitionBindings.Where(rd => rd.Name == roleDefinition.Name))
                    {
                        roleDefinitionBindings.Remove(roleDefinitionBinding);
                        roleAssignment.Update();
                        ClientContext.ExecuteQueryRetry();
                        break;
                    }
                }
            }
        }
Exemple #20
0
 protected override void ExecuteCmdlet()
 {
     CurrentWeb.ApplySitePolicy(Name);
 }
Exemple #21
0
 protected override void ExecuteCmdlet()
 {
     WriteObject(CurrentWeb.GetWikiPageContent(ServerRelativePageUrl));
 }
Exemple #22
0
        private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName, ExtractConfiguration configuration)
        {
            CurrentWeb.EnsureProperty(w => w.Url);
            ProvisioningTemplateCreationInformation creationInformation = null;

            if (configuration != null)
            {
                creationInformation = configuration.ToCreationInformation(CurrentWeb);
            }
            else
            {
                creationInformation = new ProvisioningTemplateCreationInformation(CurrentWeb);
            }

            if (ParameterSpecified(nameof(Handlers)))
            {
                creationInformation.HandlersToProcess = Handlers;
            }
            if (ParameterSpecified(nameof(ExcludeHandlers)))
            {
                foreach (var handler in (Handlers[])Enum.GetValues(typeof(Handlers)))
                {
                    if (!ExcludeHandlers.Has(handler) && handler != Handlers.All)
                    {
                        Handlers = Handlers | handler;
                    }
                }
                creationInformation.HandlersToProcess = Handlers;
            }

            var extension = "";

            if (packageName != null)
            {
                if (packageName.IndexOf(".", StringComparison.Ordinal) > -1)
                {
                    extension = packageName.Substring(packageName.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
                }
                else
                {
                    packageName += ".pnp";
                    extension    = ".pnp";
                }
            }

            var fileSystemConnector = new FileSystemConnector(path, "");

            if (extension == ".pnp")
            {
                creationInformation.FileConnector = new OpenXMLConnector(packageName, fileSystemConnector);
            }
            else if (extension == ".md")
            {
                creationInformation.FileConnector = fileSystemConnector;
            }
            else
            {
                creationInformation.FileConnector = fileSystemConnector;
            }
#pragma warning disable 618
            if (ParameterSpecified(nameof(PersistBrandingFiles)))
            {
                creationInformation.PersistBrandingFiles = PersistBrandingFiles;
            }
#pragma warning restore 618
            creationInformation.PersistPublishingFiles       = PersistPublishingFiles;
            creationInformation.IncludeNativePublishingFiles = IncludeNativePublishingFiles;
            if (ParameterSpecified(nameof(IncludeSiteGroups)))
            {
                creationInformation.IncludeSiteGroups = IncludeSiteGroups;
            }
            creationInformation.IncludeTermGroupsSecurity  = IncludeTermGroupsSecurity;
            creationInformation.IncludeSearchConfiguration = IncludeSearchConfiguration;
            if (ParameterSpecified(nameof(IncludeHiddenLists)))
            {
                creationInformation.IncludeHiddenLists = IncludeHiddenLists;
            }
            if (ParameterSpecified(nameof(IncludeAllPages)))
            {
                creationInformation.IncludeAllClientSidePages = IncludeAllPages;
            }
            creationInformation.SkipVersionCheck = SkipVersionCheck;
            if (ParameterSpecified(nameof(ContentTypeGroups)) && ContentTypeGroups != null)
            {
                creationInformation.ContentTypeGroupsToInclude = ContentTypeGroups.ToList();
            }
            creationInformation.PersistMultiLanguageResources = PersistMultiLanguageResources;
            if (extension == ".pnp")
            {
                // if file is of pnp format, persist all files
                creationInformation.PersistBrandingFiles          = true;
                creationInformation.PersistPublishingFiles        = true;
                creationInformation.PersistMultiLanguageResources = true;
            }
            if (!string.IsNullOrEmpty(ResourceFilePrefix))
            {
                creationInformation.ResourceFilePrefix = ResourceFilePrefix;
            }
            else
            {
                if (Out != null)
                {
                    FileInfo fileInfo = new FileInfo(Out);
                    var      prefix   = fileInfo.Name;
                    // strip extension, if there is any
                    var indexOfLastDot = prefix.LastIndexOf(".", StringComparison.Ordinal);
                    if (indexOfLastDot > -1)
                    {
                        prefix = prefix.Substring(0, indexOfLastDot);
                    }
                    creationInformation.ResourceFilePrefix = prefix;
                }
            }
            if (ExtensibilityHandlers != null)
            {
                creationInformation.ExtensibilityHandlers = ExtensibilityHandlers.ToList();
            }

#pragma warning disable CS0618 // Type or member is obsolete
            if (NoBaseTemplate)
            {
                creationInformation.BaseTemplate = null;
            }
            else
            {
                creationInformation.BaseTemplate = CurrentWeb.GetBaseTemplate();
            }
#pragma warning restore CS0618 // Type or member is obsolete

            creationInformation.ProgressDelegate = (message, step, total) =>
            {
                var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));

                WriteProgress(new ProgressRecord(0, $"Extracting Template from {CurrentWeb.Url}", message)
                {
                    PercentComplete = percentage
                });
                WriteProgress(new ProgressRecord(1, " ", " ")
                {
                    RecordType = ProgressRecordType.Completed
                });
            };
            creationInformation.MessagesDelegate = (message, type) =>
            {
                switch (type)
                {
                case ProvisioningMessageType.Warning:
                {
                    WriteWarning(message);
                    break;
                }

                case ProvisioningMessageType.Progress:
                {
                    var activity = message;
                    if (message.IndexOf("|") > -1)
                    {
                        var messageSplitted = message.Split('|');
                        if (messageSplitted.Length == 4)
                        {
                            var current = double.Parse(messageSplitted[2]);
                            var total   = double.Parse(messageSplitted[3]);
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.Activity          = messageSplitted[0];
                            subProgressRecord.StatusDescription = messageSplitted[1];
                            subProgressRecord.PercentComplete   = Convert.ToInt32((100 / total) * current);
                            WriteProgress(subProgressRecord);
                        }
                        else
                        {
                            subProgressRecord.Activity          = "Processing";
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.StatusDescription = activity;
                            subProgressRecord.PercentComplete   = 0;
                            WriteProgress(subProgressRecord);
                        }
                    }
                    else
                    {
                        subProgressRecord.Activity          = "Processing";
                        subProgressRecord.RecordType        = ProgressRecordType.Processing;
                        subProgressRecord.StatusDescription = activity;
                        subProgressRecord.PercentComplete   = 0;
                        WriteProgress(subProgressRecord);
                    }
                    break;
                }

                case ProvisioningMessageType.Completed:
                {
                    WriteProgress(new ProgressRecord(1, message, " ")
                        {
                            RecordType = ProgressRecordType.Completed
                        });
                    break;
                }
                }
            };

            if (IncludeAllTermGroups)
            {
                creationInformation.IncludeAllTermGroups = true;
            }
            else
            {
                if (IncludeSiteCollectionTermGroup)
                {
                    creationInformation.IncludeSiteCollectionTermGroup = true;
                }
            }

            if (ParameterSpecified(nameof(ExcludeContentTypesFromSyndication)))
            {
                creationInformation.IncludeContentTypesFromSyndication = !ExcludeContentTypesFromSyndication.ToBool();
            }

            if (ListsToExtract != null && ListsToExtract.Count > 0)
            {
                creationInformation.ListsToExtract.AddRange(ListsToExtract);
            }
            ProvisioningTemplate template = null;
            using (var provisioningContext = new PnPProvisioningContext(async(resource, scope) =>
            {
                return(await TokenRetrieval.GetAccessTokenAsync(resource, scope));
            }, azureEnvironment: PnPConnection.Current.AzureEnvironment))
            {
                template = CurrentWeb.GetProvisioningTemplate(creationInformation);
            }
            // Set metadata for template, if any
            SetTemplateMetadata(template, TemplateDisplayName, TemplateImagePreviewUrl, TemplateProperties);

            if (!OutputInstance)
            {
                var formatter = ProvisioningHelper.GetFormatter(schema);

                if (extension == ".pnp")
                {
                    XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                        creationInformation.FileConnector as OpenXMLConnector);
                    var templateFileName = packageName.Substring(0, packageName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                    provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
                }
                else if (extension == ".md")
                {
                    WriteWarning("The generation of a markdown report is work in progress, it will improve/grow with later releases.");
                    ITemplateFormatter mdFormatter = new MarkdownPnPFormatter();
                    using (var outputStream = mdFormatter.ToFormattedTemplate(template))
                    {
                        using (var fileStream = File.Create(Path.Combine(path, packageName)))
                        {
                            outputStream.Seek(0, SeekOrigin.Begin);
                            outputStream.CopyTo(fileStream);
                            fileStream.Close();
                        }
                    }
                }
                else
                {
                    if (Out != null)
                    {
                        XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(path, "");
                        provider.SaveAs(template, Path.Combine(path, packageName), formatter, TemplateProviderExtensions);
                    }
                    else
                    {
                        var outputStream = formatter.ToFormattedTemplate(template);
                        var reader       = new StreamReader(outputStream);

                        WriteObject(reader.ReadToEnd());
                    }
                }
            }
            else
            {
                WriteObject(template);
            }
        }
        private IEnumerable <object> GetContents(string FolderSiteRelativeUrl)
        {
            Folder targetFolder = null;

            if (ParameterSetName == ParameterSet_FOLDERSBYPIPE && Identity != null)
            {
                targetFolder = Identity.GetFolder(CurrentWeb);
            }
            else
            {
                string serverRelativeUrl = null;
                if (!string.IsNullOrEmpty(FolderSiteRelativeUrl))
                {
                    var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl);
                    serverRelativeUrl = UrlUtility.Combine(webUrl, FolderSiteRelativeUrl);
                }

                targetFolder = (string.IsNullOrEmpty(FolderSiteRelativeUrl)) ? CurrentWeb.RootFolder : CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl));
            }

            IEnumerable <File>   files   = null;
            IEnumerable <Folder> folders = null;

            if (ItemType == "File" || ItemType == "All")
            {
                files = ClientContext.LoadQuery(targetFolder.Files).OrderBy(f => f.Name);
                if (!string.IsNullOrEmpty(ItemName))
                {
                    files = files.Where(f => f.Name.Equals(ItemName, StringComparison.InvariantCultureIgnoreCase));
                }
            }
            if (ItemType == "Folder" || ItemType == "All" || Recursive)
            {
                folders = ClientContext.LoadQuery(targetFolder.Folders).OrderBy(f => f.Name);
                if (!string.IsNullOrEmpty(ItemName))
                {
                    folders = folders.Where(f => f.Name.Equals(ItemName, StringComparison.InvariantCultureIgnoreCase));
                }
            }
            ClientContext.ExecuteQueryRetry();

            IEnumerable <object> folderContent = null;

            switch (ItemType)
            {
            case "All":
                folderContent = folders.Concat <object>(files);
                break;

            case "Folder":
                folderContent = folders;
                break;

            default:
                folderContent = files;
                break;
            }

            if (Recursive && folders.Count() > 0)
            {
                foreach (var folder in folders)
                {
                    var relativeUrl       = folder.ServerRelativeUrl.Replace(CurrentWeb.ServerRelativeUrl, "");
                    var subFolderContents = GetContents(relativeUrl);
                    folderContent = folderContent.Concat <object>(subFolderContents);
                }
            }

            return(folderContent);
        }
Exemple #24
0
        protected override void ExecuteCmdlet()
        {
            var serverRelativeUrl = string.Empty;

            if (string.IsNullOrEmpty(Path))
            {
                Path = SessionState.Path.CurrentFileSystemLocation.Path;
            }
            else
            {
                if (!System.IO.Path.IsPathRooted(Path))
                {
                    Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
                }
            }

            var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl);

            if (!Url.ToLower().StartsWith(webUrl.ToLower()))
            {
                serverRelativeUrl = UrlUtility.Combine(webUrl, Url);
            }
            else
            {
                serverRelativeUrl = Url;
            }

            File file;

            switch (ParameterSetName)
            {
            case URLTOPATH:

                SaveFileToLocal(CurrentWeb, serverRelativeUrl, Path, Filename, (fileToSave) =>
                {
                    if (!Force)
                    {
                        WriteWarning($"File '{fileToSave}' exists already. use the -Force parameter to overwrite the file.");
                    }
                    return(Force);
                }).Wait();
                break;

            case URLASFILEOBJECT:
                file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl));
                try
                {
                    ClientContext.Load(file, f => f.Author, f => f.Length, f => f.ModifiedBy, f => f.Name, f => f.TimeCreated, f => f.TimeLastModified, f => f.Title);
                    ClientContext.ExecuteQueryRetry();
                }
                catch (ServerException)
                {
                    // Assume the cause of the exception is that a principal cannot be found and try again without:
                    // Fallback in case the creator or person having last modified the file no longer exists in the environment such that the file can still be downloaded
                    ClientContext.Load(file, f => f.Length, f => f.Name, f => f.TimeCreated, f => f.TimeLastModified, f => f.Title);
                    ClientContext.ExecuteQueryRetry();
                }
                WriteObject(file);
                break;

            case URLASLISTITEM:
                file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl));

                ClientContext.Load(file, f => f.Exists, f => f.ListItemAllFields);

                ClientContext.ExecuteQueryRetry();
                if (file.Exists)
                {
                    WriteObject(file.ListItemAllFields);
                }
                else
                {
                    if (ThrowExceptionIfFileNotFound)
                    {
                        throw new PSArgumentException($"No file found with the provided Url {serverRelativeUrl}", "Url");
                    }
                }
                break;

            case URLASSTRING:
                WriteObject(CurrentWeb.GetFileAsString(serverRelativeUrl));
                break;
            }
        }
        private void ExtractTemplate(XMLPnPSchemaVersion schema, string path, string packageName)
        {
            CurrentWeb.EnsureProperty(w => w.Url);

            var creationInformation = new ProvisioningTemplateCreationInformation(CurrentWeb)
            {
                HandlersToProcess = Handlers.Lists
            };

            var extension = "";

            if (packageName != null)
            {
                if (packageName.IndexOf(".", StringComparison.Ordinal) > -1)
                {
                    extension = packageName.Substring(packageName.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
                }
                else
                {
                    packageName += ".pnp";
                    extension    = ".pnp";
                }
            }

            var fileSystemConnector = new FileSystemConnector(path, "");

            if (extension == ".pnp")
            {
                creationInformation.FileConnector = new OpenXMLConnector(packageName, fileSystemConnector);
            }
            else
            {
                creationInformation.FileConnector = fileSystemConnector;
            }

            creationInformation.ProgressDelegate = (message, step, total) =>
            {
                var percentage = Convert.ToInt32((100 / Convert.ToDouble(total)) * Convert.ToDouble(step));

                WriteProgress(new ProgressRecord(0, $"Extracting Template from {CurrentWeb.Url}", message)
                {
                    PercentComplete = percentage
                });
            };
            creationInformation.MessagesDelegate = (message, type) =>
            {
                switch (type)
                {
                case ProvisioningMessageType.Warning:
                {
                    WriteWarning(message);
                    break;
                }

                case ProvisioningMessageType.Progress:
                {
                    var activity = message;
                    if (message.IndexOf("|") > -1)
                    {
                        var messageSplitted = message.Split('|');
                        if (messageSplitted.Length == 4)
                        {
                            var current = double.Parse(messageSplitted[2]);
                            var total   = double.Parse(messageSplitted[3]);
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.Activity          = messageSplitted[0];
                            subProgressRecord.StatusDescription = messageSplitted[1];
                            subProgressRecord.PercentComplete   = Convert.ToInt32((100 / total) * current);
                            WriteProgress(subProgressRecord);
                        }
                        else
                        {
                            subProgressRecord.Activity          = "Processing";
                            subProgressRecord.RecordType        = ProgressRecordType.Processing;
                            subProgressRecord.StatusDescription = activity;
                            subProgressRecord.PercentComplete   = 0;
                            WriteProgress(subProgressRecord);
                        }
                    }
                    else
                    {
                        subProgressRecord.Activity          = "Processing";
                        subProgressRecord.RecordType        = ProgressRecordType.Processing;
                        subProgressRecord.StatusDescription = activity;
                        subProgressRecord.PercentComplete   = 0;
                        WriteProgress(subProgressRecord);
                    }
                    break;
                }

                case ProvisioningMessageType.Completed:
                {
                    WriteProgress(new ProgressRecord(1, message, " ")
                        {
                            RecordType = ProgressRecordType.Completed
                        });
                    break;
                }
                }
            };

            if (List != null && List.Count > 0)
            {
                creationInformation.ListsToExtract.AddRange(List);
            }

            var template = CurrentWeb.GetProvisioningTemplate(creationInformation);



            if (!OutputInstance)
            {
                var formatter = ProvisioningHelper.GetFormatter(schema);

                if (extension == ".pnp")
                {
                    XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                        creationInformation.FileConnector as OpenXMLConnector);
                    var templateFileName = packageName.Substring(0, packageName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                    provider.SaveAs(template, templateFileName, formatter, null);
                }
                else
                {
                    if (Out != null)
                    {
                        XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(path, "");
                        provider.SaveAs(template, Path.Combine(path, packageName), formatter, null);
                    }
                    else
                    {
                        var outputStream = formatter.ToFormattedTemplate(template);
                        var reader       = new StreamReader(outputStream);

                        WriteObject(reader.ReadToEnd());
                    }
                }
            }
            else
            {
                WriteObject(template);
            }
        }
Exemple #26
0
        protected override void ExecuteCmdlet()
        {
            DefaultRetrievalExpressions = new Expression <Func <User, object> >[]
            {
                u => u.Id,
                u => u.Title,
                u => u.LoginName,
                u => u.Email,
                u => u.IsShareByEmailGuestUser,
                u => u.IsSiteAdmin,
                u => u.UserId,
                u => u.IsHiddenInUI,
                u => u.PrincipalType,
                u => u.Alerts.Include(
                    a => a.Title,
                    a => a.Status),
                u => u.Groups.Include(
                    g => g.Id,
                    g => g.Title,
                    g => g.LoginName)
            };

            if (Identity == null)
            {
                CurrentWeb.Context.Load(CurrentWeb.SiteUsers, u => u.Include(RetrievalExpressions));

                List <DetailedUser> users = new List <DetailedUser>();

                if (WithRightsAssigned ||
                    WithRightsAssignedDetailed
                    )
                {
                    // Get all the role assignments and role definition bindings to be able to see which users have been given rights directly on the site level
                    CurrentWeb.Context.Load(CurrentWeb.RoleAssignments, ac => ac.Include(a => a.RoleDefinitionBindings, a => a.Member));
                    var usersWithDirectPermissions = CurrentWeb.SiteUsers.Where(u => CurrentWeb.RoleAssignments.Any(ra => ra.Member.LoginName == u.LoginName));

                    // Get all the users contained in SharePoint Groups
                    CurrentWeb.Context.Load(CurrentWeb.SiteGroups, sg => sg.Include(u => u.Users.Include(RetrievalExpressions), u => u.LoginName));
                    CurrentWeb.Context.ExecuteQueryRetry();

                    // Get all SharePoint groups that have been assigned access
                    var usersWithGroupPermissions = new List <User>();
                    foreach (var group in CurrentWeb.SiteGroups.Where(g => CurrentWeb.RoleAssignments.Any(ra => ra.Member.LoginName == g.LoginName)))
                    {
                        usersWithGroupPermissions.AddRange(group.Users);
                    }

                    // Merge the users with rights directly on the site level and those assigned rights through SharePoint Groups
                    var allUsersWithPermissions = new List <User>(usersWithDirectPermissions.Count() + usersWithGroupPermissions.Count());
                    allUsersWithPermissions.AddRange(usersWithDirectPermissions);
                    allUsersWithPermissions.AddRange(usersWithGroupPermissions);

                    // Add the found users and add them to the custom object
                    if (WithRightsAssignedDetailed)
                    {
                        CurrentWeb.Context.Load(CurrentWeb, s => s.ServerRelativeUrl);
                        CurrentWeb.Context.ExecuteQueryRetry();

                        WriteWarning("Using the -WithRightsAssignedDetailed parameter will cause the script to take longer than normal because of the all enumerations that take place");
                        users.AddRange(GetPermissions(CurrentWeb.RoleAssignments, CurrentWeb.ServerRelativeUrl));
                        foreach (var user in allUsersWithPermissions)
                        {
                            users.Add(new DetailedUser()
                            {
                                Groups = user.Groups,
                                User   = user,
                                Url    = CurrentWeb.ServerRelativeUrl
                            });
                        }
                    }
                    else
                    {
                        // Filter out the users that have been given rights at both places so they will only be returned once
                        WriteObject(allUsersWithPermissions.GroupBy(u => u.Id).Select(u => u.First()), true);
                    }
                }
                else
                {
                    CurrentWeb.Context.ExecuteQueryRetry();
                    WriteObject(CurrentWeb.SiteUsers, true);
                }

                if (WithRightsAssignedDetailed)
                {
                    CurrentWeb.Context.Load(CurrentWeb.Lists, l => l.Include(li => li.ItemCount, li => li.IsSystemList, li => li.IsCatalog, li => li.RootFolder.ServerRelativeUrl, li => li.RoleAssignments, li => li.Title, li => li.HasUniqueRoleAssignments));
                    CurrentWeb.Context.ExecuteQueryRetry();

                    var progress        = new ProgressRecord(0, $"Getting lists for {CurrentWeb.ServerRelativeUrl}", "Enumerating through lists");
                    var progressCounter = 0;

                    foreach (var list in CurrentWeb.Lists)
                    {
                        WriteProgress(progress, $"Getting list {list.RootFolder.ServerRelativeUrl}", progressCounter++, CurrentWeb.Lists.Count);

                        // ignoring the system lists
                        if (list.IsSystemList || list.IsCatalog)
                        {
                            continue;
                        }

                        // if a list or a library has unique permissions then proceed
                        if (list.HasUniqueRoleAssignments)
                        {
                            WriteVerbose(string.Format("List found with HasUniqueRoleAssignments {0}", list.RootFolder.ServerRelativeUrl));
                            string url = list.RootFolder.ServerRelativeUrl;

                            CurrentWeb.Context.Load(list.RoleAssignments, r => r.Include(
                                                        ra => ra.RoleDefinitionBindings,
                                                        ra => ra.Member.LoginName,
                                                        ra => ra.Member.Title,
                                                        ra => ra.Member.PrincipalType));
                            CurrentWeb.Context.ExecuteQueryRetry();

                            users.AddRange(GetPermissions(list.RoleAssignments, url));

                            // if the list with unique permissions also has items, check every item which is uniquely permissioned
                            if (list.ItemCount > 0)
                            {
                                WriteVerbose(string.Format("Enumerating through all listitems of {0}", list.RootFolder.ServerRelativeUrl));

                                CamlQuery query        = CamlQuery.CreateAllItemsQuery();
                                var       queryElement = XElement.Parse(query.ViewXml);

                                var rowLimit = queryElement.Descendants("RowLimit").FirstOrDefault();
                                if (rowLimit != null)
                                {
                                    rowLimit.RemoveAll();
                                }
                                else
                                {
                                    rowLimit = new XElement("RowLimit");
                                    queryElement.Add(rowLimit);
                                }

                                rowLimit.SetAttributeValue("Paged", "TRUE");
                                rowLimit.SetValue(1000);

                                query.ViewXml = queryElement.ToString();

                                List <ListItemCollection> items = new List <ListItemCollection>();

                                do
                                {
                                    var listItems = list.GetItems(query);
                                    CurrentWeb.Context.Load(listItems);
                                    CurrentWeb.Context.ExecuteQueryRetry();
                                    query.ListItemCollectionPosition = listItems.ListItemCollectionPosition;

                                    items.Add(listItems);
                                } while (query.ListItemCollectionPosition != null);

                                // Progress bar for item enumerations
                                var itemProgress        = new ProgressRecord(0, $"Getting items for {list.RootFolder.ServerRelativeUrl}", "Enumerating through items");
                                var itemProgressCounter = 0;

                                foreach (var item in items)
                                {
                                    WriteProgress(itemProgress, $"Retrieving items", itemProgressCounter++, items.Count);

                                    WriteVerbose(string.Format("Enumerating though listitemcollections"));
                                    foreach (var listItem in item)
                                    {
                                        WriteVerbose(string.Format("Enumerating though listitems"));
                                        listItem.EnsureProperty(i => i.HasUniqueRoleAssignments);

                                        if (listItem.HasUniqueRoleAssignments)
                                        {
                                            string listItemUrl = listItem["FileRef"].ToString();
                                            WriteVerbose(string.Format("List item {0} HasUniqueRoleAssignments", listItemUrl));

                                            CurrentWeb.Context.Load(listItem.RoleAssignments, r => r.Include(
                                                                        ra => ra.RoleDefinitionBindings,
                                                                        ra => ra.Member.LoginName,
                                                                        ra => ra.Member.Title,
                                                                        ra => ra.Member.PrincipalType));
                                            CurrentWeb.Context.ExecuteQueryRetry();

                                            users.AddRange(GetPermissions(listItem.RoleAssignments, listItemUrl));
                                        }
                                    }
                                }
                                itemProgress.RecordType = ProgressRecordType.Completed;
                                WriteProgress(itemProgress);
                            }
                        }
                        progress.RecordType = ProgressRecordType.Completed;
                        WriteProgress(progress);
                    }

                    // Fetch all the unique users from everything that has been collected
                    var uniqueUsers = (from u in users
                                       select u.User.LoginName).Distinct();

                    // Looping through each user, getting all the details like specific permissions and groups an user belongs to
                    foreach (var uniqueUser in uniqueUsers)
                    {
                        // Getting all the assigned permissions per user
                        var userPermissions = (from u in users
                                               where u.User.LoginName == uniqueUser && u.Permissions != null
                                               select u).ToList();

                        // Making the permissions readable by getting the name of the permission and the URL of the artifact
                        Dictionary <string, string> Permissions = new Dictionary <string, string>();
                        foreach (var userPermission in userPermissions)
                        {
                            StringBuilder stringBuilder = new StringBuilder();
                            foreach (var permissionMask in userPermission.Permissions)
                            {
                                stringBuilder.Append(permissionMask);
                            }
                            Permissions.Add(userPermission.Url, stringBuilder.ToString());
                        }

                        // Getting all the groups where the user is added to
                        var groupsMemberships = (from u in users
                                                 where u.User.LoginName == uniqueUser && u.Groups != null
                                                 select u.Groups).ToList();

                        // Getting the titles of the all the groups
                        List <string> Groups = new List <string>();
                        foreach (var groupMembership in groupsMemberships)
                        {
                            foreach (var group in groupMembership)
                            {
                                Groups.Add(group.Title);
                            }
                        }

                        // Getting the User object of the user so we can get to the title, loginname, etc
                        var userInformation = (from u in users
                                               where u.User.LoginName == uniqueUser
                                               select u.User).FirstOrDefault();

                        WriteObject(new { userInformation.Title, userInformation.LoginName, userInformation.Email, Groups, Permissions }, true);
                    }
                }
            }
            else
            {
                User user = null;
                if (Identity.Id > 0)
                {
                    user = CurrentWeb.GetUserById(Identity.Id);
                }
                else if (Identity.User != null && Identity.User.Id > 0)
                {
                    user = CurrentWeb.GetUserById(Identity.User.Id);
                }
                else if (!string.IsNullOrWhiteSpace(Identity.Login))
                {
                    user = CurrentWeb.SiteUsers.GetByLoginName(Identity.Login);
                }
                if (user != null)
                {
                    CurrentWeb.Context.Load(user, RetrievalExpressions);
                    CurrentWeb.Context.ExecuteQueryRetry();
                }
                WriteObject(user);
            }
        }
Exemple #27
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSpecified(nameof(SetSharedField)) && ParameterSpecified(nameof(RemoveSharedField)))
            {
                WriteWarning("Cannot set and remove a shared field at the same time");
                return;
            }
            if (ParameterSpecified(nameof(SetWelcomePageField)) && ParameterSpecified(nameof(RemoveWelcomePageField)))
            {
                WriteWarning("Cannot set and remove a welcome page field at the same time");
                return;
            }

            var docSetTemplate = DocumentSet.GetDocumentSetTemplate(CurrentWeb);


            ClientContext.Load(docSetTemplate, dt => dt.AllowedContentTypes, dt => dt.SharedFields, dt => dt.WelcomePageFields);
            ClientContext.ExecuteQueryRetry();

            var field = Field.Field;

            if (field == null)
            {
                if (Field.Id != Guid.Empty)
                {
                    field = CurrentWeb.Fields.GetById(Field.Id);
                }
                else if (!string.IsNullOrEmpty(Field.Name))
                {
                    field = CurrentWeb.Fields.GetByInternalNameOrTitle(Field.Name);
                }
                ClientContext.Load(field);
                ClientContext.ExecuteQueryRetry();
            }
            if (field != null)
            {
                // Check if field is part of the content types in the document set
                Field existingField = null;
                foreach (var allowedCtId in docSetTemplate.AllowedContentTypes)
                {
                    var allowedCt = CurrentWeb.GetContentTypeById(allowedCtId.StringValue, true);

                    var fields = allowedCt.Fields;
                    ClientContext.Load(fields, fs => fs.Include(f => f.Id));
                    ClientContext.ExecuteQueryRetry();
                    existingField = fields.FirstOrDefault(f => f.Id == field.Id);
                    if (existingField != null)
                    {
                        break;
                    }
                }
                if (existingField == null)
                {
                    var docSetCt = DocumentSet.ContentType;
                    var fields   = docSetCt.Fields;
                    ClientContext.Load(fields, fs => fs.Include(f => f.Id));
                    ClientContext.ExecuteQueryRetry();
                    existingField = fields.FirstOrDefault(f => f.Id == field.Id);
                }
                if (existingField != null)
                {
                    if (SetSharedField)
                    {
                        docSetTemplate.SharedFields.Add(field);
                    }
                    if (SetWelcomePageField)
                    {
                        docSetTemplate.WelcomePageFields.Add(field);
                    }
                    if (RemoveSharedField)
                    {
                        docSetTemplate.SharedFields.Remove(field);
                    }
                    if (RemoveWelcomePageField)
                    {
                        docSetTemplate.WelcomePageFields.Remove(field.Id);
                    }
                    docSetTemplate.Update(true);
                    ClientContext.ExecuteQueryRetry();
                }
                else
                {
                    WriteWarning("Field not present in document set allowed content types");
                }
            }
        }
Exemple #28
0
        protected override void ExecuteCmdlet()
        {
            Field f;

            if (List != null)
            {
                List list = List.GetList(CurrentWeb);

                f = list.CreateField(FieldXml);
            }
            else
            {
                f = CurrentWeb.CreateField(FieldXml);
            }
            ClientContext.Load(f);
            ClientContext.ExecuteQueryRetry();
            switch (f.FieldTypeKind)
            {
            case FieldType.DateTime:
            {
                WriteObject(ClientContext.CastTo <FieldDateTime>(f));
                break;
            }

            case FieldType.Choice:
            {
                WriteObject(ClientContext.CastTo <FieldChoice>(f));
                break;
            }

            case FieldType.Calculated:
            {
                WriteObject(ClientContext.CastTo <FieldCalculated>(f));
                break;
            }

            case FieldType.Computed:
            {
                WriteObject(ClientContext.CastTo <FieldComputed>(f));
                break;
            }

            case FieldType.Geolocation:
            {
                WriteObject(ClientContext.CastTo <FieldGeolocation>(f));
                break;
            }

            case FieldType.User:
            {
                WriteObject(ClientContext.CastTo <FieldUser>(f));
                break;
            }

            case FieldType.Currency:
            {
                WriteObject(ClientContext.CastTo <FieldCurrency>(f));
                break;
            }

            case FieldType.Guid:
            {
                WriteObject(ClientContext.CastTo <FieldGuid>(f));
                break;
            }

            case FieldType.URL:
            {
                WriteObject(ClientContext.CastTo <FieldUrl>(f));
                break;
            }

            case FieldType.Lookup:
            {
                WriteObject(ClientContext.CastTo <FieldLookup>(f));
                break;
            }

            case FieldType.MultiChoice:
            {
                WriteObject(ClientContext.CastTo <FieldMultiChoice>(f));
                break;
            }

            case FieldType.Number:
            {
                WriteObject(ClientContext.CastTo <FieldNumber>(f));
                break;
            }

            default:
            {
                WriteObject(f);
                break;
            }
            }
        }
Exemple #29
0
        protected override void ExecuteCmdlet()
        {
            if (Id == Guid.Empty)
            {
                Id = Guid.NewGuid();
            }

            if (List != null)
            {
                var list = List.GetList(CurrentWeb);
                if (list == null)
                {
                    throw new PSArgumentException($"No list found with id, title or url '{List}'", "List");
                }
                Field f;
                if (ParameterSetName != ParameterSet_ADDFIELDREFERENCETOLIST)
                {
                    var fieldCI = new FieldCreationInformation(Type)
                    {
                        Id               = Id,
                        InternalName     = InternalName,
                        DisplayName      = DisplayName,
                        Group            = Group,
                        AddToDefaultView = AddToDefaultView
                    };

                    if (AddToAllContentTypes)
                    {
                        fieldCI.FieldOptions |= AddFieldOptions.AddToAllContentTypes;
                    }

                    if (ClientSideComponentId != null)
                    {
                        fieldCI.ClientSideComponentId = ClientSideComponentId;
                    }
                    if (!string.IsNullOrEmpty(ClientSideComponentProperties))
                    {
                        fieldCI.ClientSideComponentProperties = ClientSideComponentProperties;
                    }
                    if (Type == FieldType.Choice || Type == FieldType.MultiChoice)
                    {
                        f = list.CreateField <FieldChoice>(fieldCI);
                        ((FieldChoice)f).Choices = choiceFieldParameters.Choices;
                        f.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                    else if (Type == FieldType.Calculated)
                    {
                        // Either set the ResultType as input parameter or set it to the default Text
                        if (!string.IsNullOrEmpty(calculatedFieldParameters.ResultType))
                        {
                            fieldCI.AdditionalAttributes = new List <KeyValuePair <string, string> >()
                            {
                                new KeyValuePair <string, string>("ResultType", calculatedFieldParameters.ResultType)
                            };
                        }
                        else
                        {
                            fieldCI.AdditionalAttributes = new List <KeyValuePair <string, string> >()
                            {
                                new KeyValuePair <string, string>("ResultType", "Text")
                            };
                        }

                        fieldCI.AdditionalChildNodes = new List <KeyValuePair <string, string> >()
                        {
                            new KeyValuePair <string, string>("Formula", calculatedFieldParameters.Formula)
                        };

                        f = list.CreateField <FieldCalculated>(fieldCI);
                    }
                    else
                    {
                        f = list.CreateField(fieldCI);
                    }
                    if (Required)
                    {
                        f.Required = true;
                        f.Update();
                        ClientContext.Load(f);
                        ClientContext.ExecuteQueryRetry();
                    }
                    WriteObject(f);
                }
                else
                {
                    Field field = Field.Field;
                    if (field == null)
                    {
                        if (Field.Id != Guid.Empty)
                        {
                            field = CurrentWeb.Fields.GetById(Field.Id);
                            ClientContext.Load(field);
                            ClientContext.ExecuteQueryRetry();
                        }
                        else if (!string.IsNullOrEmpty(Field.Name))
                        {
                            try
                            {
                                field = CurrentWeb.Fields.GetByInternalNameOrTitle(Field.Name);
                                ClientContext.Load(field);
                                ClientContext.ExecuteQueryRetry();
                            }
                            catch
                            {
                                // Field might be sitecolumn, swallow exception
                            }
                            if (field != null)
                            {
                                var rootWeb = ClientContext.Site.RootWeb;
                                field = rootWeb.Fields.GetByInternalNameOrTitle(Field.Name);
                                ClientContext.Load(field);
                                ClientContext.ExecuteQueryRetry();
                            }
                        }
                    }
                    if (field != null)
                    {
                        list.Fields.Add(field);
                        list.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                }
            }
            else
            {
                Field f;

                var fieldCI = new FieldCreationInformation(Type)
                {
                    Id               = Id,
                    InternalName     = InternalName,
                    DisplayName      = DisplayName,
                    Group            = Group,
                    AddToDefaultView = AddToDefaultView
                };

                if (ClientSideComponentId != null)
                {
                    fieldCI.ClientSideComponentId = ClientSideComponentId;
                }
                if (!string.IsNullOrEmpty(ClientSideComponentProperties))
                {
                    fieldCI.ClientSideComponentProperties = ClientSideComponentProperties;
                }

                if (Type == FieldType.Choice || Type == FieldType.MultiChoice)
                {
                    f = CurrentWeb.CreateField <FieldChoice>(fieldCI);
                    ((FieldChoice)f).Choices = choiceFieldParameters.Choices;
                    f.Update();
                    ClientContext.ExecuteQueryRetry();
                }
                else if (Type == FieldType.Calculated)
                {
                    f = CurrentWeb.CreateField <FieldCalculated>(fieldCI);
                    ((FieldCalculated)f).Formula = calculatedFieldParameters.Formula;
                    f.Update();
                    ClientContext.ExecuteQueryRetry();
                }
                else
                {
                    f = CurrentWeb.CreateField(fieldCI);
                }

                if (Required)
                {
                    f.Required = true;
                    f.Update();
                    ClientContext.Load(f);
                    ClientContext.ExecuteQueryRetry();
                }
                switch (f.FieldTypeKind)
                {
                case FieldType.DateTime:
                {
                    WriteObject(ClientContext.CastTo <FieldDateTime>(f));
                    break;
                }

                case FieldType.Choice:
                {
                    WriteObject(ClientContext.CastTo <FieldChoice>(f));
                    break;
                }

                case FieldType.Calculated:
                {
                    var calculatedField = ClientContext.CastTo <FieldCalculated>(f);
                    calculatedField.EnsureProperty(fc => fc.Formula);
                    WriteObject(calculatedField);
                    break;
                }

                case FieldType.Computed:
                {
                    WriteObject(ClientContext.CastTo <FieldComputed>(f));
                    break;
                }

                case FieldType.Geolocation:
                {
                    WriteObject(ClientContext.CastTo <FieldGeolocation>(f));
                    break;
                }

                case FieldType.User:
                {
                    WriteObject(ClientContext.CastTo <FieldUser>(f));
                    break;
                }

                case FieldType.Currency:
                {
                    WriteObject(ClientContext.CastTo <FieldCurrency>(f));
                    break;
                }

                case FieldType.Guid:
                {
                    WriteObject(ClientContext.CastTo <FieldGuid>(f));
                    break;
                }

                case FieldType.URL:
                {
                    WriteObject(ClientContext.CastTo <FieldUrl>(f));
                    break;
                }

                case FieldType.Lookup:
                {
                    WriteObject(ClientContext.CastTo <FieldLookup>(f));
                    break;
                }

                case FieldType.MultiChoice:
                {
                    WriteObject(ClientContext.CastTo <FieldMultiChoice>(f));
                    break;
                }

                case FieldType.Number:
                {
                    WriteObject(ClientContext.CastTo <FieldNumber>(f));
                    break;
                }

                default:
                {
                    WriteObject(f);
                    break;
                }
                }
            }
        }
Exemple #30
0
        protected override void ExecuteCmdlet()
        {
            var emails = CurrentWeb.GetRequestAccessEmails();

            WriteObject(emails, true);
        }