//protected void WithExistingWebPart(ListItem listItem, WebPartDefinition webPartModel,
        //  Action<WebPart> action)
        //{
        //    WithExistingWebPart(listItem.File, webPartModel, action);
        //}

        protected void WithExistingWebPart(File file, WebPartDefinition webPartModel,
           Action<WebPart> action)
        {
            WithExistingWebPart(file, webPartModel, (w, d) =>
            {
                action(w);
            });
        }
        public DocumentStream(ClientContext ctx, ListItem documentItem)
        {
            _ctx = ctx;

            _documentFile = documentItem.File;
            ctx.Load(_documentFile);
            ctx.Load(_documentFile.Versions);
            ctx.ExecuteQuery();

            MajorVersionLabel = _documentFile.MajorVersion + ".0";
            FileName = _documentFile.Name;
        }
        public SPOContentReaderWriter(File file, bool isBinary)
        {
            _file = file;
            _isBinary = isBinary;
            _stream = new MemoryStream();

            var spStream = _file.OpenBinaryStream();
            _file.Context.ExecuteQuery();
            spStream.Value.CopyTo(_stream);
            _stream.Position = 0;

            _streamWriter = new StreamWriter(_stream);
            _streamReader = new StreamReader(_stream);
        }
        public void AddWebParts(ClientContext context, File uploadFile, List<ShWebPartReference> webPartReferences, bool replaceWebParts)
        {
            // we should be allowed to delete webparts (by using replaceWebparts and define no new ones
            if (webPartReferences.Count <= 0 && !replaceWebParts) return;

            var limitedWebPartManager = uploadFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

            context.Load(limitedWebPartManager, manager => manager.WebParts);
            context.ExecuteQuery();

            if (limitedWebPartManager.WebParts.Count == 0 || replaceWebParts)
            {
                for (int i = limitedWebPartManager.WebParts.Count - 1; i >= 0; i--)
                {
                    limitedWebPartManager.WebParts[i].DeleteWebPart();
                }
                context.ExecuteQuery();

                foreach (ShWebPartReference webPart in webPartReferences)
                {
                    //Convention: All webparts are located in the content/webparts folder
                    var webPartPath = Path.Combine(_contentDirectoryPath, "webparts", webPart.FileName);
                    var webPartFileContent = System.IO.File.ReadAllText(webPartPath);
                    if (!System.IO.File.Exists(webPartPath))
                    {
                        Log.ErrorFormat("Webpart at path {0} not found", webPartPath);
                        continue;
                    }

                    //Token replacement in the webpart XML
                    webPartFileContent = GetPropertyValueWithTokensReplaced(webPartFileContent, context);
                    var webPartDefinition = limitedWebPartManager.ImportWebPart(webPartFileContent);
                    if (webPart.PropertiesOverrides.Count > 0)
                    {
                        foreach (KeyValuePair<string, string> propertyOverride in webPart.PropertiesOverrides)
                        {
                            //Token replacement in the PropertiesOverrides JSON array
                            var propOverrideValue = GetPropertyValueWithTokensReplaced(propertyOverride.Value, context);
                            webPartDefinition.WebPart.Properties[propertyOverride.Key] = propOverrideValue;
                        }
                    }
                    limitedWebPartManager.AddWebPart(webPartDefinition.WebPart, webPart.ZoneID, webPart.Order);
                }

                context.Load(limitedWebPartManager);
                context.ExecuteQuery();
            }
        }
Beispiel #5
0
        private static bool CheckOutIfNeeded(Web web, File targetFile)
        {
            var checkedOut = false;
            try
            {
                web.Context.Load(targetFile, f => f.CheckOutType, f => f.ListItemAllFields.ParentList.ForceCheckout);
                web.Context.ExecuteQueryRetry();

                if (targetFile.CheckOutType == CheckOutType.None)
                {
                    targetFile.CheckOut();
                }
                checkedOut = true;
            }
            catch (ServerException ex)
            {
                // Handling the exception stating the "The object specified does not belong to a list."
                if (ex.ServerErrorCode != -2146232832)
                {
                    throw;
                }
            }
            return checkedOut;
        }
Beispiel #6
0
        public void AddWebParts(ClientContext context, File uploadFile, List<ShWebPartReference> webPartReferences, bool replaceWebParts)
        {
            // we should be allowed to delete webparts (by using replaceWebparts and define no new ones
            if (webPartReferences.Count <= 0 && !replaceWebParts) return;

            var limitedWebPartManager = uploadFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

            context.Load(limitedWebPartManager, manager => manager.WebParts);
            context.ExecuteQuery();

            if (limitedWebPartManager.WebParts.Count == 0 || replaceWebParts)
            {
                for (int i = limitedWebPartManager.WebParts.Count - 1; i >= 0; i--)
                {
                    limitedWebPartManager.WebParts[i].DeleteWebPart();
                    context.ExecuteQuery();
                }

                foreach (ShWebPartReference webPart in webPartReferences)
                {
                    //Convention: All webparts are located in the content/webparts folder
                    var webPartPath = Path.Combine(_contentDirectoryPath, "webparts", webPart.FileName);
                    var webPartFileContent = System.IO.File.ReadAllText(webPartPath);
                    if (!System.IO.File.Exists(webPartPath))
                    {
                        Log.ErrorFormat("Webpart at path {0} not found", webPartPath);
                        continue;
                    }

                    //Token replacement in the webpart XML
                    webPartFileContent = GetPropertyValueWithTokensReplaced(webPartFileContent, context);

                    //Overriding DataProviderJSON properties if specified. Need to use different approach (Update XML directly before import)
                    if (webPart.PropertiesOverrides.Count > 0 || webPart.DataProviderJSONOverrides.Count > 0)
                    {
                        webPartFileContent = ReplaceWebPartPropertyOverrides(context, webPart, webPartFileContent);
                    }

                    var webPartDefinition = limitedWebPartManager.ImportWebPart(webPartFileContent);
                    limitedWebPartManager.AddWebPart(webPartDefinition.WebPart, webPart.ZoneID, webPart.Order);
                    context.Load(limitedWebPartManager);
                    context.ExecuteQuery();
                }
            }
        }
Beispiel #7
0
        private void ApplyFileProperties(ClientContext context, IEnumerable<ShFileProperties> filePropertiesCollection, File uploadFile)
        {
            if (filePropertiesCollection != null)
            {
                var fileProperties = filePropertiesCollection.SingleOrDefault(f => f.Url == uploadFile.Name);
                if (fileProperties != null)
                {
                    var filePropertiesWithTokensReplaced = new Dictionary<string, string>();
                    foreach (KeyValuePair<string, string> keyValuePair in fileProperties.Properties)
                    {
                        filePropertiesWithTokensReplaced.Add(keyValuePair.Key, GetPropertyValueWithTokensReplaced(keyValuePair.Value, context));
                    }
                    uploadFile.SetFileProperties(filePropertiesWithTokensReplaced);

                    if (uploadFile.Name.ToLower().EndsWith(".aspx")) 
                        AddWebParts(context, uploadFile, fileProperties.WebParts, fileProperties.ReplaceWebParts);
                    context.ExecuteQuery();
                }
            }
        }
Beispiel #8
0
        public void SetFileProperties(File file, IDictionary<string, string> properties, bool checkoutIfRequired = true)
        {
            var context = file.Context;
            if (properties != null && properties.Count > 0)
            {
                // Get a reference to the target list, if any
                // and load file item properties
                var parentList = file.ListItemAllFields.ParentList;
                context.Load(parentList);
                context.Load(file.ListItemAllFields);
                try
                {
                    context.ExecuteQueryRetry();
                }
                catch (ServerException ex)
                {
                    // If this throws ServerException (does not belong to list), then shouldn't be trying to set properties)
                    if (ex.Message != "The object specified does not belong to a list.")
                    {
                        throw;
                    }
                }

                // Loop through and detect changes first, then, check out if required and apply
                foreach (var kvp in properties)
                {
                    var propertyName = kvp.Key;
                    var propertyValue = kvp.Value;

                    var targetField = parentList.Fields.GetByInternalNameOrTitle(propertyName);
                    targetField.EnsureProperties(f => f.TypeAsString, f => f.ReadOnlyField);

                    // Changed by PaoloPia because there are fields like PublishingPageLayout
                    // which are marked as read-only, but have to be overwritten while uploading
                    // a publishing page file and which in reality can still be written
                    if (!targetField.ReadOnlyField || WriteableReadOnlyFields.Contains(propertyName.ToLower()))
                    {
                        switch (propertyName.ToUpperInvariant())
                        {
                            case "CONTENTTYPE":
                                {
                                    Microsoft.SharePoint.Client.ContentType targetCT = parentList.GetContentTypeByName(propertyValue);
                                    context.ExecuteQueryRetry();

                                    if (targetCT != null)
                                    {
                                        file.ListItemAllFields["ContentTypeId"] = targetCT.StringId;
                                    }
                                    else
                                    {
                                        Log.Error(Constants.LOGGING_SOURCE, "Content Type {0} does not exist in target list!", propertyValue);
                                    }
                                    break;
                                }
                            default:
                                {
                                    switch (targetField.TypeAsString)
                                    {
                                        case "User":
                                            var user = parentList.ParentWeb.EnsureUser(propertyValue);
                                            context.Load(user);
                                            context.ExecuteQueryRetry();

                                            if (user != null)
                                            {
                                                var userValue = new FieldUserValue
                                                {
                                                    LookupId = user.Id,
                                                };
                                                file.ListItemAllFields[propertyName] = userValue;
                                            }
                                            break;
                                        case "URL":
                                            var urlArray = propertyValue.Split(',');
                                            var linkValue = new FieldUrlValue();
                                            if (urlArray.Length == 2)
                                            {
                                                linkValue.Url = urlArray[0];
                                                linkValue.Description = urlArray[1];
                                            }
                                            else
                                            {
                                                linkValue.Url = urlArray[0];
                                                linkValue.Description = urlArray[0];
                                            }
                                            file.ListItemAllFields[propertyName] = linkValue;
                                            break;
                                        case "MultiChoice":
                                            var multiChoice = JsonUtility.Deserialize<String[]>(propertyValue);
                                            file.ListItemAllFields[propertyName] = multiChoice;
                                            break;
                                        case "LookupMulti":
                                            var lookupMultiValue = JsonUtility.Deserialize<FieldLookupValue[]>(propertyValue);
                                            file.ListItemAllFields[propertyName] = lookupMultiValue;
                                            break;
                                        case "TaxonomyFieldType":
                                            var taxonomyValue = JsonUtility.Deserialize<TaxonomyFieldValue>(propertyValue);
                                            file.ListItemAllFields[propertyName] = taxonomyValue;
                                            break;
                                        case "TaxonomyFieldTypeMulti":
                                            var taxonomyValueArray = JsonUtility.Deserialize<TaxonomyFieldValue[]>(propertyValue);
                                            file.ListItemAllFields[propertyName] = taxonomyValueArray;
                                            break;
                                        default:
                                            file.ListItemAllFields[propertyName] = propertyValue;
                                            break;
                                    }
                                    break;
                                }
                        }
                    }
                    file.ListItemAllFields.Update();
                    context.ExecuteQueryRetry();
                }
            }
        }
        private Model.File RetrieveFieldValues(Web web, File file, Model.File homeFile)
        {
            var listItem = file.EnsureProperty(f => f.ListItemAllFields);

            var list = listItem.ParentList;

            var fields = list.Fields;
            web.Context.Load(fields, fs => fs.IncludeWithDefaultProperties(f => f.TypeAsString, f => f.InternalName, f => f.Title));
            web.Context.ExecuteQueryRetry();

            var fieldValues = listItem.FieldValues;

            var fieldValuesAsText = listItem.EnsureProperty(li => li.FieldValuesAsText).FieldValues;

            var fieldstoExclude = new[] {
                "ID",
                "GUID",
                "Author",
                "Editor",
                "FileLeafRef",
                "FileRef",
                "File_x0020_Type",
                "Modified_x0020_By",
                "Created_x0020_By",
                "Created",
                "Modified",
                "FileDirRef",
                "Last_x0020_Modified",
                "Created_x0020_Date",
                "File_x0020_Size",
                "FSObjType",
                "IsCheckedoutToLocal",
                "ScopeId",
                "UniqueId",
                "VirusStatus",
                "_Level",
                "_IsCurrentVersion",
                "ItemChildCount",
                "FolderChildCount",
                "SMLastModifiedDate",
                "owshiddenversion",
                "_UIVersion",
                "_UIVersionString",
                "Order",
                "WorkflowVersion",
                "DocConcurrencyNumber",
                "ParentUniqueId",
                "CheckedOutUserId",
                "SyncClientId",
                "CheckedOutTitle",
                "SMTotalSize",
                "SMTotalFileStreamSize",
                "SMTotalFileCount",
                "ParentVersionString",
                "ParentLeafName",
                "SortBehavior",
                "_ModerationStatus"
            };

            foreach (var fieldValue in fieldValues.Where(f => !fieldstoExclude.Contains(f.Key)))
            {
                if (fieldValue.Value != null && !string.IsNullOrEmpty(fieldValue.Value.ToString()))
                {
                    var field = fields.FirstOrDefault(fs => fs.InternalName == fieldValue.Key);

                    string value = string.Empty;
                    if (field.TypeAsString == "URL")
                    {
                        value = Tokenize(fieldValuesAsText[fieldValue.Key], web.Url);
                    }
                    else {
                        value = Tokenize(fieldValue.Value.ToString(), web.Url);
                    }

                    if (fieldValue.Key == "ContentTypeId")
                    {
                        // Replace the content typeid with a token
                        var ct = list.GetContentTypeById(value);
                        if (ct != null)
                        {
                            value = string.Format("{{contenttypeid:{0}}}", ct.Name);
                        }
                    }
                    homeFile.Properties.Add(fieldValue.Key, value);
                }
            }

            return homeFile;
        }
        //protected void WithExistingWebPart(ListItem listItem, WebPartDefinition webPartModel,
        //    Action<WebPart, Microsoft.SharePoint.Client.WebParts.WebPartDefinition> action)
        //{
        //    WithExistingWebPart(listItem.File, webPartModel, action);
        //}
        protected void WithExistingWebPart(File pageFile, WebPartDefinition webPartModel,
             Action<WebPart, Microsoft.SharePoint.Client.WebParts.WebPartDefinition> action)
        {
            var context = pageFile.Context;
            var webPartManager = pageFile.GetLimitedWebPartManager(PersonalizationScope.Shared);

            // web part on the page
            var webpartOnPage = webPartManager.WebParts.Include(wp => wp.Id, wp => wp.WebPart);
            var webPartDefenitions = context.LoadQuery(webpartOnPage);

            context.ExecuteQueryWithTrace();

            Microsoft.SharePoint.Client.WebParts.WebPartDefinition def = null;
            var existingWebPart = FindExistingWebPart(webPartDefenitions, webPartModel, out def);

            action(existingWebPart, def);
        }
        public Core.File ToFile(File file)
        {
            if (file == null)
                return null;

            var errorFile = file as SharePointFileErrorEntry;
            if (errorFile != null)
                return new Core.File
                {
                    ID = MakeId(errorFile.ID),
                    FolderID = MakeId(GetParentFolderId(errorFile.ID)),
                    CreateBy = Owner,
                    CreateOn = DateTime.UtcNow,
                    ModifiedBy = Owner,
                    ModifiedOn = DateTime.UtcNow,
                    ProviderId = ID,
                    ProviderKey = ProviderKey,
                    RootFolderCreator = Owner,
                    RootFolderId = MakeId(RootFolder.ServerRelativeUrl),
                    RootFolderType = RootFolderType,
                    Title = MakeTitle(GetTitleById(errorFile.ID)),
                    Error = errorFile.Error
                };

            var result = new Core.File
            {
                ID = MakeId(file.ServerRelativeUrl),
                Access = Core.Security.FileShare.None,
                //ContentLength = file.Length,
                CreateBy = Owner,
                CreateOn = file.TimeCreated.Kind == DateTimeKind.Utc ? TenantUtil.DateTimeFromUtc(file.TimeCreated) : file.TimeCreated,
                FileStatus = FileStatus.None,
                FolderID = MakeId(GetParentFolderId(file.ServerRelativeUrl)),
                ModifiedBy = Owner,
                ModifiedOn = file.TimeLastModified.Kind == DateTimeKind.Utc ? TenantUtil.DateTimeFromUtc(file.TimeLastModified) : file.TimeLastModified,
                NativeAccessor = file,
                ProviderId = ID,
                ProviderKey = ProviderKey,
                Title = MakeTitle(file.Name),
                RootFolderId = MakeId(SpRootFolderId),
                RootFolderType = RootFolderType,
                RootFolderCreator = Owner,
                SharedByMe = false,
                Version = 1
            };

            if (file.IsPropertyAvailable("Length"))
            {
                result.ContentLength = file.Length;
            }
            else if(file.IsObjectPropertyInstantiated("ListItemAllFields"))
            {
                result.ContentLength = Convert.ToInt64(file.ListItemAllFields["File_x0020_Size"]);
            }

            return result;
        }
        private void EnsurePublish(File file, string publishComment)
        {
            // Load dependent data.
            var parentList = file.ListItemAllFields.ParentList;
            if (!parentList.IsPropertyAvailable("EnableMinorVersion") || !parentList.IsPropertyAvailable("EnableModeration") || !file.IsPropertyAvailable("Level") || !file.IsPropertyAvailable("ListItemAllFields"))
            {
                _clientContext.Load(parentList);
                _clientContext.Load(file);
                _clientContext.ExecuteQuery();
            }

            var isDirty = false;
            if (file.Level == FileLevel.Checkout)
            {
                file.CheckIn(string.Empty, CheckinType.MajorCheckIn);
                isDirty = true;
            }
            if (parentList.EnableMinorVersions && file.Level != FileLevel.Published)
            {
                file.Publish(publishComment);
                isDirty = true;
            }
            if (parentList.EnableModeration && Convert.ToInt32(file.ListItemAllFields["_ModerationStatus"]) != 0)
            {
                file.Approve(string.Empty);
                isDirty = true;
            }

            if (isDirty)
            {
                file.RefreshLoad();
                _clientContext.ExecuteQuery();
            }
        }
Beispiel #13
0
 private WebPartDefinition AddWebPart(Web web, WebPart webPart, File pageFile)
 {
     LimitedWebPartManager limitedWebPartManager = pageFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
     WebPartDefinition oWebPartDefinition = limitedWebPartManager.ImportWebPart(webPart.Contents);
     WebPartDefinition wpdNew = limitedWebPartManager.AddWebPart(oWebPartDefinition.WebPart, webPart.Zone, (int)webPart.Order);
     web.Context.Load(wpdNew, x => x.Id);
     web.Context.ExecuteQueryRetry();
     return wpdNew;
 }