protected override void ExecuteCmdlet()
        {
            if (string.IsNullOrEmpty(Folder))
            {
                if (SelectedWeb.PropertyBagContainsKey(Key))
                {
                    if (Force || ShouldContinue(string.Format(Properties.Resources.Delete0, Key), Properties.Resources.Confirm))
                    {
                        SelectedWeb.RemovePropertyBagValue(Key);
                    }
                }
            }
            else
            {
                SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

                var folderUrl = UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder);
                var folder    = SelectedWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(folderUrl));

                folder.EnsureProperty(f => f.Properties);

                if (folder.Properties.FieldValues.ContainsKey(Key))
                {
                    if (Force || ShouldContinue(string.Format(Properties.Resources.Delete0, Key), Properties.Resources.Confirm))
                    {
                        folder.Properties[Key] = null;
                        folder.Properties.FieldValues.Remove(Key);
                        folder.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Ensures the folder to which the file is to be uploaded exists. Changed from using the EnsureFolder implementation in PnP Sites Core as that requires at least member rights to the entire site to work.
        /// </summary>
        /// <returns>The folder to which the file needs to be uploaded</returns>
        private Folder EnsureFolder()
        {
            // First try to get the folder if it exists already. This avoids an Access Denied exception if the current user doesn't have Full Control access at Web level
            SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);
            var Url = UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder);

            Folder folder = null;

            try
            {
#if ONPREMISES
                folder = SelectedWeb.GetFolderByServerRelativeUrl(Url);
#else
                folder = SelectedWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(Url));
#endif
                folder.EnsureProperties(f => f.ServerRelativeUrl);
                return(folder);
            }
            // Exception will be thrown if the folder does not exist yet on SharePoint
            catch (ServerException serverEx) when(serverEx.ServerErrorCode == -2147024894)
            {
                // Try to create the folder
                folder = SelectedWeb.EnsureFolder(SelectedWeb.RootFolder, Folder);
                folder.EnsureProperties(f => f.ServerRelativeUrl);
                return(folder);
            }
        }
Exemplo n.º 3
0
        private static Tuple <string, DateTime> GetFileInformation(Web web, string serverRelativeUrl)
        {
            var file = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl));

            web.Context.Load(file, p => p.ListItemAllFields);
            web.Context.ExecuteQueryRetry();

            // TODO: fails when using sites.read.all role on xoml file download (access denied, requires ACP permission level)
            ClientResult <Stream> stream = file.OpenBinaryStream();

            web.Context.ExecuteQueryRetry();

            string   returnString = string.Empty;
            DateTime date         = DateTime.MinValue;

            date = file.ListItemAllFields.LastModifiedDateTime();

            using (Stream memStream = new MemoryStream())
            {
                CopyStream(stream.Value, memStream);
                memStream.Position = 0;
                StreamReader reader = new StreamReader(memStream);
                returnString = reader.ReadToEnd();
            }

            return(new Tuple <string, DateTime>(returnString, date));
        }
Exemplo n.º 4
0
        protected override void ExecuteCmdlet()
        {
            SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

#if ONPREMISES
            Folder sourceFolder = SelectedWeb.GetFolderByServerRelativeUrl(UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder));
            ClientContext.Load(sourceFolder, f => f.Name, f => f.ServerRelativeUrl);
            ClientContext.ExecuteQueryRetry();

            var targetPath = string.Concat(TargetFolder, "/", sourceFolder.Name);
            sourceFolder.MoveTo(targetPath);
            ClientContext.ExecuteQueryRetry();

            var folder = SelectedWeb.GetFolderByServerRelativeUrl(targetPath);
            ClientContext.Load(folder, f => f.Name, f => f.ItemCount, f => f.TimeLastModified, f => f.ListItemAllFields);
            ClientContext.ExecuteQueryRetry();
            WriteObject(folder);
#else
            var    sourceFolderUrl = UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder);
            Folder sourceFolder    = SelectedWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(sourceFolderUrl));
            ClientContext.Load(sourceFolder, f => f.Name, f => f.ServerRelativeUrl);
            ClientContext.ExecuteQueryRetry();

            var targetPath = string.Concat(TargetFolder, "/", sourceFolder.Name);
            sourceFolder.MoveToUsingPath(ResourcePath.FromDecodedUrl(targetPath));
            ClientContext.ExecuteQueryRetry();

            var folder = SelectedWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(targetPath));
            ClientContext.Load(folder, f => f.Name, f => f.ItemCount, f => f.TimeLastModified, f => f.ListItemAllFields);
            ClientContext.ExecuteQueryRetry();
            WriteObject(folder);
#endif
        }
Exemplo n.º 5
0
        protected override void ExecuteCmdlet()
        {
            SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

#if ONPREMISES
            Folder folder = SelectedWeb.GetFolderByServerRelativeUrl(UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder, Name));
#else
            var    folderUrl = UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder, Name);
            Folder folder    = SelectedWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(folderUrl));
#endif
            folder.EnsureProperty(f => f.Name);

            if (Force || ShouldContinue(string.Format(Resources.Delete0, folder.Name), Resources.Confirm))
            {
                if (Recycle)
                {
                    folder.Recycle();
                }
                else
                {
                    folder.DeleteObject();
                }

                ClientContext.ExecuteQueryRetry();
            }
        }
Exemplo n.º 6
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSetName == ParameterSet_SITE)
            {
                var webUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);
                ServerRelativeUrl = UrlUtility.Combine(webUrl, SiteRelativeUrl);
            }
#if ONPREMISES
            var file = SelectedWeb.GetFileByServerRelativeUrl(ServerRelativeUrl);

            ClientContext.Load(file, f => f.Name);
            ClientContext.ExecuteQueryRetry();

            if (Force || ShouldContinue(string.Format(Resources.MoveFile0To1, ServerRelativeUrl, TargetUrl), Resources.Confirm))
            {
                file.MoveTo(TargetUrl, OverwriteIfAlreadyExists ? MoveOperations.Overwrite : MoveOperations.None);

                ClientContext.ExecuteQueryRetry();
            }
#else
            var file = SelectedWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(ServerRelativeUrl));

            ClientContext.Load(file, f => f.Name);
            ClientContext.ExecuteQueryRetry();

            if (Force || ShouldContinue(string.Format(Resources.MoveFile0To1, ServerRelativeUrl, TargetUrl), Resources.Confirm))
            {
                file.MoveToUsingPath(ResourcePath.FromDecodedUrl(TargetUrl), OverwriteIfAlreadyExists ? MoveOperations.Overwrite : MoveOperations.None);

                ClientContext.ExecuteQueryRetry();
            }
#endif
        }
Exemplo n.º 7
0
        private void SaveFileToLocal(Web web, string serverRelativeUrl, string localPath, string localFileName = null, Func <string, bool> fileExistsCallBack = null)
        {
#if SP2013 || SP2016
            var file = web.GetFileByServerRelativeUrl(serverRelativeUrl);
#else
            var file = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl));
#endif

            var clientContext = web.Context as ClientContext;
            clientContext.Load(file);
            clientContext.ExecuteQueryRetry();

            ClientResult <Stream> stream = file.OpenBinaryStream();
            clientContext.ExecuteQueryRetry();

            var fileOut = System.IO.Path.Combine(localPath, !string.IsNullOrEmpty(localFileName) ? localFileName : file.Name);

            if (!System.IO.File.Exists(fileOut) || (fileExistsCallBack != null && fileExistsCallBack(fileOut)))
            {
                using (Stream fileStream = new FileStream(fileOut, FileMode.Create))
                {
                    CopyStream(stream.Value, fileStream);
                }
            }
        }
        protected override void ExecuteCmdlet()
        {
            var serverRelativeUrl = string.Empty;

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

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

            File file;

            file = SelectedWeb.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;
                ClientContext.ExecuteQueryRetry();
                WriteObject(versions);
            }
        }
Exemplo n.º 9
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSetName == ParameterSet_SITE)
            {
                var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl);
                ServerRelativeUrl = UrlUtility.Combine(webUrl, SiteRelativeUrl);
            }
            var file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(ServerRelativeUrl));

            ClientContext.Load(file, f => f.Name);
            ClientContext.ExecuteQueryRetry();

            if (Force || ShouldContinue(string.Format(Resources.Delete0, file.Name), Resources.Confirm))
            {
                if (Recycle)
                {
                    file.Recycle();
                }
                else
                {
                    file.DeleteObject();
                }

                ClientContext.ExecuteQueryRetry();
            }
        }
Exemplo n.º 10
0
        public void CopyFile_EmptyFolderBetweenSiteCollections_Test()
        {
            using (var scope = new PSTestScope(_site1Url, true))
            {
                var sourceUrl      = $"{Site1RelativeFolderUrl}/{EmptyFolderName}";
                var destinationUrl = $"{Site2RelativeFolderUrl}/{EmptyFolderName}";

                var results = scope.ExecuteCommand("Copy-PnPFile",
                                                   new CommandParameter("SourceUrl", sourceUrl),
                                                   new CommandParameter("TargetUrl", destinationUrl),
                                                   new CommandParameter("Force"));

                using (var ctx = TestCommon.CreateClientContext(_site2Url))
                {
                    Folder initialFolder = ctx.Web.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(destinationUrl));
                    initialFolder.EnsureProperties(f => f.Name, f => f.Exists);
                    ctx.Load(initialFolder);
                    ctx.ExecuteQuery();
                    if (!initialFolder.Exists)
                    {
                        Assert.Fail("Copied folder cannot be found");
                    }
                }
            }
        }
        private MemoryStream GetFileFromStorage(string fileName, string container)
        {
            try
            {
                using (ClientContext cc = GetClientContext().Clone(GetConnectionString()))
                {
                    string fileServerRelativeUrl = GetFileServerRelativeUrl(cc, fileName, container);
                    var    file = cc.Web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(fileServerRelativeUrl));
                    cc.Load(file);
                    cc.ExecuteQueryRetry();
                    if (file.Exists)
                    {
                        MemoryStream stream       = new MemoryStream();
                        var          streamResult = file.OpenBinaryStream();
                        cc.ExecuteQueryRetry();

                        streamResult.Value.CopyTo(stream);

                        Log.Info(Constants.LOGGING_SOURCE, CoreResources.Provisioning_Connectors_SharePoint_FileRetrieved, fileName, GetConnectionString(), container);

                        // Set the stream position to the beginning
                        stream.Position = 0;
                        return(stream);
                    }

                    throw new Exception("File not found");
                }
            }
            catch (Exception ex)
            {
                Log.Error(Constants.LOGGING_SOURCE, CoreResources.Provisioning_Connectors_SharePoint_FileNotFound, fileName, GetConnectionString(), container, ex.Message);
                return(null);
            }
        }
        /// <summary>
        /// Deletes a file from the specified container
        /// </summary>
        /// <param name="fileName">Name of the file to delete</param>
        /// <param name="container">Name of the container to delete the file from</param>
        public override void DeleteFile(string fileName, string container)
        {
            if (container != null)
            {
                container = container.Replace('\\', '/');
            }

            try
            {
                using (ClientContext cc = GetClientContext().Clone(GetConnectionString()))
                {
                    string fileServerRelativeUrl = GetFileServerRelativeUrl(cc, fileName, container);
                    File   file = cc.Web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(fileServerRelativeUrl));
                    cc.Load(file);
                    cc.ExecuteQueryRetry();

                    if (file != null)
                    {
                        file.DeleteObject();
                        cc.ExecuteQueryRetry();
                        Log.Info(Constants.LOGGING_SOURCE, CoreResources.Provisioning_Connectors_SharePoint_FileDeleted, fileName, GetConnectionString(), container);
                    }
                    else
                    {
                        Log.Warning(Constants.LOGGING_SOURCE, CoreResources.Provisioning_Connectors_SharePoint_FileDeleteNotFound, fileName, GetConnectionString(), container);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(Constants.LOGGING_SOURCE, CoreResources.Provisioning_Connectors_SharePoint_FileDeleteFailed, fileName, GetConnectionString(), container, ex.Message);
                throw;
            }
        }
Exemplo n.º 13
0
        public static bool CheckListExist(ClientContext context, string listUrl)
        {
            var file = context.Web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl("/sites/Test5/Shared Documents/20200611142343.txt"));

            context.Load(file);
            context.ExecuteQuery();
            bool siteAssetsExist         = false;
            List list                    = null;
            ExceptionHandlingScope scope = new ExceptionHandlingScope(context);

            using (scope.StartScope())
            {
                using (scope.StartTry())
                {
                    list = context.Web.GetList(listUrl);
                    context.Load(list, l => l.Title, l => l.IsSiteAssetsLibrary);
                }
                using (scope.StartCatch())
                { }
            }
            context.ExecuteQuery();
            if (scope.HasException)
            {
            }
            else if (list.ServerObjectIsNull.HasValue && !list.ServerObjectIsNull.Value)
            {
                siteAssetsExist = true;//list.IsSiteAssetsLibrary;
            }
            return(siteAssetsExist);
        }
Exemplo n.º 14
0
        protected override void ExecuteCmdlet()
        {
            var webServerRelativeUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl);

            if (!SourceUrl.StartsWith("/"))
            {
                SourceUrl = UrlUtility.Combine(webServerRelativeUrl, SourceUrl);
            }
            if (!TargetUrl.StartsWith("/"))
            {
                TargetUrl = UrlUtility.Combine(webServerRelativeUrl, TargetUrl);
            }

            string sourceFolder = SourceUrl.Substring(0, SourceUrl.LastIndexOf('/'));
            string targetFolder = TargetUrl;

            if (System.IO.Path.HasExtension(TargetUrl))
            {
                targetFolder = TargetUrl.Substring(0, TargetUrl.LastIndexOf('/'));
            }

            Uri currentContextUri = new Uri(ClientContext.Url);
            Uri sourceUri         = new Uri(currentContextUri, EncodePath(sourceFolder));
            Uri sourceWebUri      = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, sourceUri);
            Uri targetUri         = new Uri(currentContextUri, EncodePath(targetFolder));
            Uri targetWebUri      = Microsoft.SharePoint.Client.Web.WebUrlFromFolderUrlDirect(ClientContext, targetUri);

            if (Force || ShouldContinue(string.Format(Resources.MoveFile0To1, SourceUrl, TargetUrl), Resources.Confirm))
            {
                if (sourceWebUri != targetWebUri)
                {
                    Move(currentContextUri, sourceUri, targetUri, SourceUrl, TargetUrl, false);
                }
                else
                {
                    var isFolder = false;
                    try
                    {
                        var folder = CurrentWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(TargetUrl));
                        var folderServerRelativePath = folder.EnsureProperty(f => f.ServerRelativePath);
                        isFolder = folderServerRelativePath.DecodedUrl == ResourcePath.FromDecodedUrl(TargetUrl).DecodedUrl;
                    }
                    catch
                    {
                    }
                    if (isFolder)
                    {
                        Move(currentContextUri, sourceUri, targetUri, SourceUrl, TargetUrl, true);
                    }
                    else
                    {
                        var file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(SourceUrl));
                        file.MoveToUsingPath(ResourcePath.FromDecodedUrl(TargetUrl), Overwrite ? MoveOperations.Overwrite : MoveOperations.None);
                        ClientContext.ExecuteQueryRetry();
                    }
                }
            }
        }
Exemplo n.º 15
0
        protected override void ExecuteCmdlet()
        {
            try
            {
                if (!ParameterSpecified(nameof(Folder)))
                {
                    if (!Indexed)
                    {
                        // If it is already an indexed property we still have to add it back to the indexed properties
                        Indexed = !string.IsNullOrEmpty(SelectedWeb.GetIndexedPropertyBagKeys().FirstOrDefault(k => k == Key));
                    }

                    SelectedWeb.SetPropertyBagValue(Key, Value);
                    if (Indexed)
                    {
                        SelectedWeb.AddIndexedPropertyBagKey(Key);
                    }
                    else
                    {
                        SelectedWeb.RemoveIndexedPropertyBagKey(Key);
                    }
                }
                else
                {
                    SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

                    var folderUrl = UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder);
#if ONPREMISES
                    var folder = SelectedWeb.GetFolderByServerRelativeUrl(folderUrl);
#else
                    var folder = SelectedWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(folderUrl));
#endif

                    folder.EnsureProperty(f => f.Properties);

                    folder.Properties[Key] = Value;
                    folder.Update();
                    ClientContext.ExecuteQueryRetry();
                }
            }
            catch (Exception ex)
            {
                if (ex is ServerUnauthorizedAccessException)
                {
                    if (SelectedWeb.IsNoScriptSite())
                    {
                        ThrowTerminatingError(new ErrorRecord(new Exception($"{ex.Message} Site might have NoScript enabled, this prevents setting some property bag values.", ex), "NoScriptEnabled", ErrorCategory.InvalidOperation, this));
                        return;
                    }
                    throw;
                }
                else
                {
                    throw;
                }
            }
        }
Exemplo n.º 16
0
        public static CSOMOperation LoadWebByUrl(this CSOMOperation operation, string url,
                                                 params Expression <Func <Web, object> >[] retrievals)
        {
            operation.LogDebug($"Loading web with url: {url}");

            var web = operation.LastSite.OpenWebUsingPath(ResourcePath.FromDecodedUrl(url));

            return(LoadWeb(operation, web, retrievals));
        }
Exemplo n.º 17
0
        protected override void ExecuteCmdlet()
        {
            var serverRelativeUrl = string.Empty;

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

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

            File file;

#if ONPREMISES
            file = SelectedWeb.GetFileByServerRelativeUrl(serverRelativeUrl);
#else
            file = SelectedWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(serverRelativeUrl));
#endif

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

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

                if (Force || ShouldContinue("Restoring a previous version will overwrite the current version.", Resources.Confirm))
                {
                    if (!string.IsNullOrEmpty(Identity.Label))
                    {
                        versions.RestoreByLabel(Identity.Label);
                        ClientContext.ExecuteQueryRetry();
                        WriteObject("Version restored");
                    }
                    else if (Identity.Id != -1)
                    {
                        var version = versions.GetById(Identity.Id);
                        ClientContext.Load(version);
                        ClientContext.ExecuteQueryRetry();

                        versions.RestoreByLabel(version.VersionLabel);
                        ClientContext.ExecuteQueryRetry();
                        WriteObject("Version restored");
                    }
                }
            }
            else
            {
                throw new PSArgumentException("File not found", nameof(Url));
            }
        }
Exemplo n.º 18
0
        public static CSOMOperation DeleteFolder(this CSOMOperation operation, string remotePath)
        {
            operation.LogInfo($"Deleting folder: {remotePath}");

            var list = operation.LastList;
            var resourceFolderPath = ResourcePath.FromDecodedUrl(list.RootFolder.Name + "/" + remotePath);

            list.RootFolder.Folders.GetByPath(resourceFolderPath).DeleteObject();

            return(operation);
        }
Exemplo n.º 19
0
        protected override void ExecuteCmdlet()
        {
            // Ensure that with ParameterSet_OTHERSITE we either receive a ServerRelativeUrl or SiteRelativeUrl
            if (ParameterSetName == ParameterSet_OTHERSITE && !ParameterSpecified(nameof(ServerRelativeUrl)) && !ParameterSpecified(nameof(SiteRelativeUrl)))
            {
                throw new PSArgumentException($"Either provide {nameof(ServerRelativeUrl)} or {nameof(SiteRelativeUrl)}");
            }

            if (ParameterSpecified(nameof(SiteRelativeUrl)))
            {
                var webUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);
                ServerRelativeUrl = UrlUtility.Combine(webUrl, SiteRelativeUrl);
            }

            var file = SelectedWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(ServerRelativeUrl));

            ClientContext.Load(file, f => f.Name, f => f.ServerRelativeUrl);
            ClientContext.ExecuteQueryRetry();

            if (Force || ShouldContinue(string.Format(Resources.MoveFile0To1, ServerRelativeUrl, TargetUrl), Resources.Confirm))
            {
                switch (ParameterSetName)
                {
                case ParameterSet_SITE:
                case ParameterSet_SERVER:
                    file.MoveToUsingPath(ResourcePath.FromDecodedUrl(TargetUrl), OverwriteIfAlreadyExists.ToBool() ? MoveOperations.Overwrite : MoveOperations.None);
                    break;

                case ParameterSet_OTHERSITE:
                    SelectedWeb.EnsureProperties(w => w.Url, w => w.ServerRelativeUrl);

                    // Create full URLs including the SharePoint domain to the source and destination
                    var source      = UrlUtility.Combine(SelectedWeb.Url.Remove(SelectedWeb.Url.Length - SelectedWeb.ServerRelativeUrl.Length + 1, SelectedWeb.ServerRelativeUrl.Length - 1), file.ServerRelativeUrl);
                    var destination = UrlUtility.Combine(SelectedWeb.Url.Remove(SelectedWeb.Url.Length - SelectedWeb.ServerRelativeUrl.Length + 1, SelectedWeb.ServerRelativeUrl.Length - 1), TargetServerRelativeLibrary);

                    ClientContext.Site.CreateCopyJobs(new[] { source }, destination, new CopyMigrationOptions {
                        IsMoveMode          = true,
                        AllowSchemaMismatch = AllowSchemaMismatch.ToBool(),
                        AllowSmallerVersionLimitOnDestination = AllowSmallerVersionLimitOnDestination.ToBool(),
                        IgnoreVersionHistory = IgnoreVersionHistory.ToBool(),
                        NameConflictBehavior = OverwriteIfAlreadyExists.ToBool() ? MigrationNameConflictBehavior.Replace : MigrationNameConflictBehavior.Fail
                    });
                    break;

                default:
                    throw new PSInvalidOperationException(string.Format(Resources.ParameterSetNotImplemented, ParameterSetName));
                }

                ClientContext.ExecuteQueryRetry();
            }
        }
Exemplo n.º 20
0
        protected override void ExecuteCmdlet()
        {
#if !SP2013
            DefaultRetrievalExpressions = new Expression <Func <Folder, object> >[] { f => f.ServerRelativeUrl, f => f.Name, f => f.TimeLastModified, f => f.ItemCount };
#else
            DefaultRetrievalExpressions = new Expression <Func <Folder, object> >[] { f => f.ServerRelativeUrl, f => f.Name, f => f.ItemCount };
#endif
            if (List != null)
            {
                // Gets the provided list
                var list = List.GetList(SelectedWeb);

                // Query for all folders in the list
                CamlQuery query = CamlQuery.CreateAllFoldersQuery();
                do
                {
                    // Execute the query. It will retrieve all properties of the folders. Refraining to using the RetrievalExpressions would cause a tremendous increased load on SharePoint as it would have to execute a query per list item which would be less efficient, especially on lists with many folders, than just getting all properties directly
                    ListItemCollection listItems = list.GetItems(query);
                    ClientContext.Load(listItems, item => item.Include(t => t.Folder), item => item.ListItemCollectionPosition);
                    ClientContext.ExecuteQueryRetry();

                    // Take all the folders from the resulting list items and put them in a list to return
                    var folders = new List <Folder>(listItems.Count);
                    foreach (ListItem listItem in listItems)
                    {
                        var folder = listItem.Folder;
                        folders.Add(folder);
                    }

                    WriteObject(folders, true);

                    query.ListItemCollectionPosition = listItems.ListItemCollectionPosition;
                } while (query.ListItemCollectionPosition != null);
            }
            else
            {
                var webServerRelativeUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);
                if (!Url.StartsWith(webServerRelativeUrl, StringComparison.OrdinalIgnoreCase))
                {
                    Url = UrlUtility.Combine(webServerRelativeUrl, Url);
                }
#if ONPREMISES
                var folder = SelectedWeb.GetFolderByServerRelativeUrl(Url);
#else
                var folder = SelectedWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(Url));
#endif
                folder.EnsureProperties(RetrievalExpressions);

                WriteObject(folder);
            }
        }
        internal static string ReplaceFileUniqueToken(Web web, string UrlValue)
        {
            if (!string.IsNullOrWhiteSpace(UrlValue))
            {
                Regex regex = new Regex("(?:=([{]{1,2})|(%7[bB]{1}[{]{1}))(?<tokenname>fileuniqueid|fileuniqueidencoded)(?::)(?<fileurl>[^}]*)", RegexOptions.Compiled | RegexOptions.Multiline);

                Match match = regex.Match(UrlValue);
                if (match.Success)
                {
                    if (match.Groups["fileurl"].Success)
                    {
                        try
                        {
                            var spFile = web.GetFileByUrl(match.Groups["fileurl"].Value);
                            web.Context.Load(spFile, f => f.UniqueId);
                            web.Context.ExecuteQueryRetry();
                            string fileId = spFile.UniqueId.ToString();
                            if (match.Groups["tokenname"].Value.Equals("fileuniqueidencoded", StringComparison.InvariantCultureIgnoreCase))
                            {
                                fileId = fileId.Replace("-", "%2D");
                            }
                            UrlValue = Regex.Replace(UrlValue, $"{{{match.Groups["tokenname"].Value}:{match.Groups["fileurl"].Value}}}", fileId, RegexOptions.IgnoreCase);
                        }
                        catch (Exception)
                        {
                            //Test if fileuniqueid belongs to a folder
                            try
                            {
                                web.EnsureProperties(w => w.ServerRelativeUrl);
                                string folderUrl = $"{web.ServerRelativeUrl}/{ match.Groups["fileurl"].Value}";
                                var    spFolder  = web.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(folderUrl));
                                web.Context.Load(spFolder, f => f.UniqueId);
                                web.Context.ExecuteQueryRetry();
                                string folderId = spFolder.UniqueId.ToString();
                                if (match.Groups["tokenname"].Value.Equals("fileuniqueidencoded", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    folderId = folderId.Replace("-", "%2D");
                                }
                                UrlValue = Regex.Replace(UrlValue, $"{{{match.Groups["tokenname"].Value}:{match.Groups["fileurl"].Value}}}", folderId, RegexOptions.IgnoreCase);
                            }
                            catch (Exception)
                            {
                                // swallow exception
                            }
                        }
                    }
                }
            }
            return(UrlValue);
        }
Exemplo n.º 22
0
        protected override void ExecuteCmdlet()
        {
            SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

            var    sourceFolderUrl = UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder);
            Folder sourceFolder    = SelectedWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(sourceFolderUrl));

            ClientContext.Load(sourceFolder, f => f.Name, f => f.ServerRelativePath);
            ClientContext.ExecuteQueryRetry();

            var targetPath = string.Concat(sourceFolder.ServerRelativePath.DecodedUrl.Remove(sourceFolder.ServerRelativePath.DecodedUrl.Length - sourceFolder.Name.Length), TargetFolderName);

            sourceFolder.MoveToUsingPath(ResourcePath.FromDecodedUrl(targetPath));
            ClientContext.ExecuteQueryRetry();
        }
Exemplo n.º 23
0
        public static CSOMOperation CreateFolder(this CSOMOperation operation, string remotePath, bool overwrite = true)
        {
            operation.LogInfo($"Creating folder: {remotePath}");

            var list = operation.LastList;
            var resourceFolderPath = ResourcePath.FromDecodedUrl(list.RootFolder.Name + "/" + remotePath);

            var folder = list.RootFolder.Folders.AddUsingPath(resourceFolderPath, new FolderCollectionAddParameters {
                Overwrite = overwrite
            });

            folder.Context.Load(folder);

            return(operation);
        }
Exemplo n.º 24
0
        protected override void ExecuteCmdlet()
        {
            if (string.IsNullOrEmpty(Folder))
            {
                if (!string.IsNullOrEmpty(Key))
                {
                    WriteObject(SelectedWeb.GetPropertyBagValueString(Key, string.Empty));
                }
                else
                {
                    SelectedWeb.EnsureProperty(w => w.AllProperties);

                    var values = SelectedWeb.AllProperties.FieldValues.Select(x => new PropertyBagValue()
                    {
                        Key = x.Key, Value = x.Value
                    });
                    WriteObject(values, true);
                }
            }
            else
            {
                // Folder Property Bag

                SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

                var folderUrl = UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder);
#if ONPREMISES
                var folder = SelectedWeb.GetFolderByServerRelativeUrl(folderUrl);
#else
                var folder = SelectedWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(folderUrl));
#endif
                folder.EnsureProperty(f => f.Properties);

                if (!string.IsNullOrEmpty(Key))
                {
                    var value = folder.Properties.FieldValues.FirstOrDefault(x => x.Key == Key);
                    WriteObject(value.Value, true);
                }
                else
                {
                    var values = folder.Properties.FieldValues.Select(x => new PropertyBagValue()
                    {
                        Key = x.Key, Value = x.Value
                    });
                    WriteObject(values, true);
                }
            }
        }
Exemplo n.º 25
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSetName == "SITE")
            {
                var serverUrl = SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);
                ServerRelativePageUrl = UrlUtility.Combine(serverUrl, SiteRelativePageUrl);
            }
#if ONPREMISES
            var file = SelectedWeb.GetFileByServerRelativeUrl(ServerRelativePageUrl);
#else
            var file = SelectedWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(ServerRelativePageUrl));
#endif
            file.DeleteObject();

            ClientContext.ExecuteQueryRetry();
        }
Exemplo n.º 26
0
        private void UploadFile(string srcFilePath, string fileName, string spPath, ClientContext ctx, string segmentByValue)
        {
            try
            {
                Web web = ctx.Web;
                if (segmentByValue != null)
                {
                    fileName = fileName.Replace(".xlsx", "_" + segmentByValue + ".xlsx");
                }
                ResourcePath folderPath   = ResourcePath.FromDecodedUrl(spPath + "/" + fileName);
                Folder       parentFolder = web.GetFolderByServerRelativePath(folderPath);

                byte[] fileData = null;

                using (FileStream fs = System.IO.File.OpenRead(srcFilePath))
                {
                    using (BinaryReader binaryReader = new BinaryReader(fs))
                    {
                        fileData = binaryReader.ReadBytes((int)fs.Length);
                    }
                }

                FileCollectionAddParameters fileAddParameters = new FileCollectionAddParameters();
                fileAddParameters.Overwrite = true;
                using (MemoryStream contentStream = new MemoryStream(fileData))
                {
                    // Add a file
                    Microsoft.SharePoint.Client.File addedFile = parentFolder.Files.AddUsingPath(folderPath, fileAddParameters, contentStream);

                    // Select properties of added file to inspect
                    ctx.Load(addedFile, f => f.UniqueId, f1 => f1.ServerRelativePath);

                    // Perform the actual operation
                    ctx.ExecuteQuery();

                    // Print the results
                    // eventLog.WriteEntry("Added File [ServerRelativePath:" + addedFile.ServerRelativePath.DecodedUrl + "]");
                }
            }
            catch (Exception ex)
            {
                Log.Error(this, "" + ex);
                eventLog.WriteEntry("" + ex, EventLogEntryType.Error);
                throw new Exception(string.Format("" + ex));
            }
        }
        private void IncludePageHeaderImageInExport(Web web, string imageServerRelativeUrl, ProvisioningTemplate template, ProvisioningTemplateCreationInformation creationInfo, PnPMonitoredScope scope)
        {
            try
            {
                if (!imageServerRelativeUrl.StartsWith("/_LAYOUTS", StringComparison.OrdinalIgnoreCase))
                {
                    var pageHeaderImage = web.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(imageServerRelativeUrl));
                    web.Context.Load(pageHeaderImage, p => p.Level, p => p.ServerRelativeUrl);
                    web.Context.ExecuteQueryRetry();

                    LoadAndAddPageImage(web, pageHeaderImage, template, creationInfo, scope);
                }
            }
            catch (Exception ex)
            {
                // Eat possible exceptions as header images may point to locations outside of the current site (other site collections, _layouts, CDN's, internet)
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Method to check if file with same name already exists during UPLOAD
        /// </summary>
        /// <param name="clientContext">SPO Client Context</param>
        /// <param name="uploadDocumentRequest">Request model for Update document</param>
        /// <param name="LoggerId">MessageId used for Logging Information</param>
        /// <returns></returns>
        private static bool TryGetFileByServerRelativeUrl(ClientContext clientContext, UploadDocumentRequest uploadDocumentRequest, string LoggerId)
        {
            bool fileAlreadyExistStatus = false;

            try
            {
                Log.DebugFormat("In TryGetFileByServerRelativeUrl method for MessageId - {0}", LoggerId);
                //To ensure special characters in file name are decoded while fetching a file from SPO example: #,$,(
                ResourcePath filePath = ResourcePath.FromDecodedUrl(new Uri(clientContext.Url).AbsolutePath
                                                                    + ConfigurationManager.AppSettings.Get(ConfigurationConstants.SPOFolder)
                                                                    + "/"
                                                                    + uploadDocumentRequest.DocumentName);
                File file = clientContext.Web.GetFileByServerRelativePath(filePath);
                clientContext.Load(file, i => i.Exists);
                clientContext.ExecuteQueryWithRetry(Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryCount)),
                                                    Convert.ToInt32(ConfigurationManager.AppSettings.Get(ExecuteQueryConstants.RetryDelayTime)),
                                                    LoggerId);
                if (file.Exists)
                {
                    //If file exists in SPO, return true
                    fileAlreadyExistStatus = true;
                }
            }
            catch (ServerException ex)
            {
                Log.ErrorFormat("ServerException in TryGetFileByServerRelativeUrl method for MessageId - {0} :{1}", LoggerId, ex.Message);
                if (ex.ServerErrorTypeName == ErrorException.SystemIoFileNotFound)
                {
                    //If file doesn't exists in SPO
                    fileAlreadyExistStatus = false;
                }
                else
                {
                    throw;
                }
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Exception in TryGetFileByServerRelativeUrl method for MessageId - {0} :{1}", LoggerId, ex.Message);
                fileAlreadyExistStatus = false;
            }
            Log.DebugFormat("Out TryGetFileByServerRelativeUrl method for MessageId - {0} fileAlreadyExistStatus :{1}", LoggerId, fileAlreadyExistStatus);
            return(fileAlreadyExistStatus);
        }
Exemplo n.º 29
0
        protected override void ExecuteCmdlet()
        {
            if (SelectedWeb.IsNoScriptSite())
            {
                ThrowTerminatingError(new ErrorRecord(new Exception("Site has NoScript enabled, and setting property bag values is not supported"), "NoScriptEnabled", ErrorCategory.InvalidOperation, this));
                return;
            }
            if (!MyInvocation.BoundParameters.ContainsKey("Folder"))
            {
                if (!Indexed)
                {
                    // If it is already an indexed property we still have to add it back to the indexed properties
                    Indexed = !string.IsNullOrEmpty(SelectedWeb.GetIndexedPropertyBagKeys().FirstOrDefault(k => k == Key));
                }

                SelectedWeb.SetPropertyBagValue(Key, Value);
                if (Indexed)
                {
                    SelectedWeb.AddIndexedPropertyBagKey(Key);
                }
                else
                {
                    SelectedWeb.RemoveIndexedPropertyBagKey(Key);
                }
            }
            else
            {
                SelectedWeb.EnsureProperty(w => w.ServerRelativeUrl);

                var folderUrl = UrlUtility.Combine(SelectedWeb.ServerRelativeUrl, Folder);
#if ONPREMISES
                var folder = SelectedWeb.GetFolderByServerRelativeUrl(folderUrl);
#else
                var folder = SelectedWeb.GetFolderByServerRelativePath(ResourcePath.FromDecodedUrl(folderUrl));
#endif

                folder.EnsureProperty(f => f.Properties);

                folder.Properties[Key] = Value;
                folder.Update();
                ClientContext.ExecuteQueryRetry();
            }
        }
Exemplo n.º 30
0
        protected override void ExecuteCmdlet()
        {
            if (ParameterSetName == "SITE")
            {
                var webUrl = CurrentWeb.EnsureProperty(w => w.ServerRelativeUrl);
                ServerRelativeUrl = UrlUtility.Combine(webUrl, SiteRelativeUrl);
            }
            var file = CurrentWeb.GetFileByServerRelativePath(ResourcePath.FromDecodedUrl(ServerRelativeUrl));

            ClientContext.Load(file, f => f.Name, f => f.ServerRelativePath);
            ClientContext.ExecuteQueryRetry();

            if (Force || ShouldContinue(string.Format(Resources.RenameFile0To1, file.Name, TargetFileName), Resources.Confirm))
            {
                var targetPath = string.Concat(file.ServerRelativePath.DecodedUrl.Remove(file.ServerRelativePath.DecodedUrl.Length - file.Name.Length), TargetFileName);
                file.MoveToUsingPath(ResourcePath.FromDecodedUrl(targetPath), OverwriteIfAlreadyExists ? MoveOperations.Overwrite : MoveOperations.None);

                ClientContext.ExecuteQueryRetry();
            }
        }