Exemplo n.º 1
0
        public Folder Create(string url, Guid libraryId, FolderCreateQuery folderCreateQuery)
        {
            Folder folder;

            try
            {
                SP.ListItem folderListItem;

                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    var splist       = clientContext.Web.Lists.GetById(libraryId);
                    var parentFolder = !String.IsNullOrEmpty(folderCreateQuery.Path) ? clientContext.Web.GetFolderByServerRelativeUrl(folderCreateQuery.Path) : splist.RootFolder;

                    clientContext.Load(parentFolder);

                    // check that new folder name is unique
                    var folderName = folderCreateQuery.Name;
                    var subfolderWithTheSameName = clientContext.LoadQuery(parentFolder.Folders.Where(f => f.Name == folderName));
                    try
                    {
                        clientContext.ExecuteQuery();
                    }
                    catch (Exception ex)
                    {
                        var message = string.Format("An exception of type {0} occurred in the InternalApi.SPFolderService.Create() method for SharePoint ServerRelativeUrl: '{1}' in SPWebUrl: '{2}'. The exception message is: {3}", ex.GetType(), folderCreateQuery.Path, url, ex.Message);
                        SPLog.FileNotFound(ex, message);

                        throw new SPInternalException(message, ex);
                    }

                    if (subfolderWithTheSameName != null && subfolderWithTheSameName.Any())
                    {
                        throw new InvalidOperationException(string.Format("The folder with '{0}' name already exists at ServerRelativeUrl: '{1}' in SPWebUrl: '{2}'.", folderName, folderCreateQuery.Path, url));
                    }

                    var newFolder = parentFolder.Folders.Add(folderCreateQuery.Name);
                    clientContext.Load(newFolder, f => f.Name, f => f.ServerRelativeUrl, f => f.ItemCount);

                    parentFolder.Update();
                    clientContext.ExecuteQuery();

                    var query           = GetFolderByServerRelativeUrl(newFolder.ServerRelativeUrl);
                    var folderListItems = clientContext.LoadQuery(splist.GetItems(query));
                    clientContext.ExecuteQuery();

                    folder         = new Folder(newFolder.Name, newFolder.ServerRelativeUrl, newFolder.ItemCount, libraryId);
                    folderListItem = folderListItems.First();
                }

                listItemDataService.AddUpdate(new ItemBase(libraryId,
                                                           Guid.Parse(folderListItem["UniqueId"].ToString()),
                                                           folderListItem.Id,
                                                           Convert.ToDateTime(folderListItem["Modified"]))
                {
                    IsIndexable = false
                });
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            catch (SPInternalException)
            {
                throw;
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the InternalApi.SPFolderService.Create() method while creating a new folder with the Name: '{1}' ServerRelativeUrl: '{2}' in SPWebUrl: '{3}'. The exception message is: {4}", ex.GetType(), folderCreateQuery.Name, folderCreateQuery.Path, url, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }

            return(folder);
        }
Exemplo n.º 2
0
        public Folder Rename(string url, Guid libraryId, string folderPath, FolderRenameQuery folderRenameQuery)
        {
            Folder folder;

            if (string.IsNullOrEmpty(folderPath))
            {
                throw new InvalidOperationException("ServerRelativeUrl cannot be empty.");
            }

            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    var spfolder = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
                    var parent   = spfolder.ParentFolder;
                    clientContext.Load(spfolder);

                    // check that new folder name is unique
                    string folderName = folderRenameQuery.Name;
                    var    subfolderWithTheSameName = clientContext.LoadQuery(parent.Folders.Where(f => f.Name == folderName));
                    try
                    {
                        clientContext.ExecuteQuery();
                    }
                    catch (Exception ex)
                    {
                        string message = string.Format("An exception of type {0} occurred in the InternalApi.SPFolderService.Rename() method for SharePoint ServerRelativeUrl: '{1}' in SPWebUrl: '{2}'. The exception message is: {3}", ex.GetType(), folderPath, url, ex.Message);
                        SPLog.FileNotFound(ex, message);

                        throw new SPInternalException(message, ex);
                    }

                    if (subfolderWithTheSameName != null && subfolderWithTheSameName.Any())
                    {
                        throw new InvalidOperationException(string.Format("The folder with '{0}' name already exists at ServerRelativeUrl: '{1}' in SPWebUrl: '{2}'.", folderName, folderPath, url));
                    }

                    var folderToRenameQuery = clientContext.Web.Lists.GetById(libraryId).GetItems(GetFolderByServerRelativeUrl(spfolder.ServerRelativeUrl));
                    var spfolderListItems   = clientContext.LoadQuery(SP.ClientObjectQueryableExtension.IncludeWithDefaultProperties(folderToRenameQuery, f => f["FileLeafRef"]));
                    clientContext.ExecuteQuery();

                    var spfolderListItem = spfolderListItems != null?spfolderListItems.FirstOrDefault() : null;

                    if (spfolderListItem == null)
                    {
                        throw new Exception("The folder cannot be loaded, because CAML request failed or invalid.");
                    }

                    spfolderListItem["FileLeafRef"] = folderRenameQuery.Name;
                    spfolderListItem.Update();

                    clientContext.Load(spfolder);

                    clientContext.ExecuteQuery();

                    folder = new Folder(spfolder.Name, spfolder.ServerRelativeUrl, spfolder.ItemCount, libraryId);
                }
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            catch (SPInternalException)
            {
                throw;
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the InternalApi.SPFolderService.Rename() method FolderName: '{1}' ServerRelativeUrl: '{2}' in SPWebUrl: '{3}'. The exception message is: {4}", ex.GetType(), folderRenameQuery.Name, folderPath, url, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }

            return(folder);
        }
Exemplo n.º 3
0
        public IRestResponse List(SPListCollectionRequest request)
        {
            var response = new DefaultRestResponse
            {
                Name = "Lists"
            };

            var errors = new List <string>();

            ValidateUrl(request.Url, errors);
            if (errors.Any())
            {
                response.Errors = errors.ToArray();
                return(response);
            }

            string url            = request.Url;
            string includeType    = request.ListType;
            string excludeType    = request.ExcludeListType;
            string listNameFilter = request.ListNameFilter;
            int    pageSize       = request.PageSize;
            int    pageIndex      = request.PageIndex;

            var listCollection = (IEnumerable <List>)cacheService.Get(CacheKey(url, includeType, excludeType), CacheScope.Context | CacheScope.Process);

            if (listCollection == null)
            {
                try
                {
                    using (var clientContext = new SPContext(url, IntegrationManagerPlugin.CurrentAuth(url), runAsServiceAccount: true))
                    {
                        ListTemplateType includeLookUpTemplate;
                        ListTemplateType excludeLookUpTemplate;
                        var includeItemsByTemplate = TryGetTemplateType(includeType, out includeLookUpTemplate);
                        var excludeItemsByTemplate = TryGetTemplateType(excludeType, out excludeLookUpTemplate);
                        if (includeItemsByTemplate)
                        {
                            var lookUpTemplateValue = (int)includeLookUpTemplate;
                            listCollection = clientContext.LoadQuery(clientContext.Web.Lists.Where(list => list.BaseTemplate == lookUpTemplateValue && list.Hidden == false).Include(RestSPList.InstanceQuery));
                        }
                        else if (excludeItemsByTemplate)
                        {
                            var lookUpTemplateValue = (int)excludeLookUpTemplate;
                            listCollection = clientContext.LoadQuery(clientContext.Web.Lists.Where(list => list.BaseTemplate != lookUpTemplateValue && list.Hidden == false).Include(RestSPList.InstanceQuery));
                        }
                        else
                        {
                            listCollection = clientContext.LoadQuery(clientContext.Web.Lists.Include(RestSPList.InstanceQuery));
                        }

                        clientContext.ExecuteQuery();
                    }
                    cacheService.Put(CacheKey(url, includeType, excludeType), listCollection, CacheScope.Context | CacheScope.Process, new string[] { }, CacheTimeOut);
                }
                catch (Exception ex)
                {
                    string message = string.Format("An exception of type {0} occurred in the RESTApi.Lists.List() method for SPWebUrl: '{1}'. The exception message is: {2}", ex.GetType(), url, ex.Message);
                    SPLog.RoleOperationUnavailable(ex, message);

                    response.Errors = new[] { plugin.Translate(SharePointEndpoints.Translations.UnknownError) };
                }
            }

            if (listCollection != null)
            {
                try
                {
                    Func <List, bool> filter = (m => true);
                    bool hasListNameFilter   = !String.IsNullOrEmpty(listNameFilter);
                    if (hasListNameFilter)
                    {
                        filter = l => l.Title.StartsWith(listNameFilter, StringComparison.OrdinalIgnoreCase) || listNameFilter.Split(' ').Where(f => !string.IsNullOrWhiteSpace(f)).All(f => l.Title.Split(' ').Any(t => t.StartsWith(f, StringComparison.OrdinalIgnoreCase)));
                    }

                    List <List> itemsList = listCollection.Where(filter).ToList();
                    response.Data = new SPListCollectionData(itemsList.Skip(pageIndex).Take(pageSize).Select(item => new RestSPList(item)), itemsList.Count);
                }
                catch (Exception ex)
                {
                    string message = string.Format("An exception of type {0} occurred in the RESTApi.Lists.List() method while processing not empty collection of Lists from SPWebUrl: '{1}'. The exception message is: {2}", ex.GetType(), url, ex.Message);
                    SPLog.RoleOperationUnavailable(ex, message);

                    response.Errors = new[] { plugin.Translate(SharePointEndpoints.Translations.UnknownError) };
                }
            }
            return(response);
        }
        public ApiList <SPListItem> List(SPList list,
                                         [Documentation(Name = "ViewFields", Type = typeof(List <string>)),
                                          Documentation(Name = "ViewQuery", Type = typeof(string))]
                                         IDictionary options)
        {
            if (list == null)
            {
                return(new ApiList <SPListItem>());
            }

            var cacheId   = string.Concat(SharePointListItemCacheId, string.Format("{0}_{1}", list.SPWebUrl, list.Id));
            var cacheList = (ApiList <SPListItem>)cacheService.Get(cacheId, CacheScope.Context | CacheScope.Process);

            if (cacheList == null)
            {
                using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
                {
                    var sharepointList = clientContext.ToList(list.Id);
                    ListItemCollection listItemCollection;
                    if (options != null && options["ViewQuery"] != null)
                    {
                        var camlQuery = new CamlQuery
                        {
                            ViewXml = String.Format("<View><Query>{0}</Query></View>", options["ViewQuery"])
                        };
                        listItemCollection = sharepointList.GetItems(camlQuery);
                    }
                    else
                    {
                        listItemCollection = sharepointList.GetItems(CamlQuery.CreateAllItemsQuery());
                    }
                    IEnumerable <ListItem> items;
                    if (options != null && options["ViewFields"] != null)
                    {
                        var viewFields = (List <string>)options["ViewFields"];
                        items = clientContext.LoadQuery(listItemCollection.Include(CreateListItemLoadExpressions(viewFields)));
                    }
                    else
                    {
                        items = clientContext.LoadQuery(listItemCollection.Include(SPItemService.InstanceQuery));
                    }
                    var userItemCollection = clientContext.Web.SiteUserInfoList.GetItems(CamlQuery.CreateAllItemsQuery());
                    IEnumerable <SP.ListItem> userItems = clientContext.LoadQuery(
                        userItemCollection.Include(new Expression <Func <ListItem, object> >[] { item => item.Id, item => item["Picture"] }));

                    var fieldsQuery = clientContext.LoadQuery(sharepointList.Fields.Where(field => !field.Hidden && field.Group != "_Hidden"));
                    clientContext.ExecuteQuery();
                    var apiList = new ApiList <SPListItem>();
                    var fields  = fieldsQuery.ToList();

                    foreach (var item in items)
                    {
                        apiList.Add(new SPListItem(item, fields));
                    }

                    cacheService.Put(cacheId, apiList, CacheScope.Context | CacheScope.Process, new[] { GetTag(list.Id) }, CacheTimeOut);
                    return(apiList);
                }
            }

            return(cacheList);
        }
Exemplo n.º 5
0
        public SPDocumentVersionList Versions(SPList list, SPListItem listItem,
                                              [Documentation(Name = "PageSize", Type = typeof(int)),
                                               Documentation(Name = "PageIndex", Type = typeof(int))]
                                              IDictionary options)
        {
            using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
            {
                var splist = clientContext.Web.Lists.GetById(list.Id);
                clientContext.Load(splist, item => item.ParentWebUrl);

                var splistItem = splist.GetItemById(listItem.Id);
                var spfile     = splistItem.File;
                clientContext.Load(spfile);
                clientContext.Load(spfile, item => item.ModifiedBy, item => item.TimeLastModified);
                var versions = clientContext.LoadQuery(spfile.Versions.IncludeWithDefaultProperties(item => item.CreatedBy, item => item.IsCurrentVersion));
                clientContext.ExecuteQuery();

                string fileName = spfile.ServerRelativeUrl;

                // There is no way to get file size using Client Object Model
                var fileSize = new Dictionary <string, int>();
                using (var service = new VersionService(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
                {
                    var nodeList = service.GetVersions(fileName);
                    foreach (XmlNode node in nodeList.ChildNodes)
                    {
                        if (node.Name == "result" && node.Attributes != null)
                        {
                            string v = node.Attributes["version"].Value.Replace("@", "");
                            int    size;
                            int.TryParse(node.Attributes["size"].Value, out size);
                            fileSize.Add(v, size);
                        }
                    }
                }

                var result = new List <SPDocumentVersion>
                {
                    new SPDocumentVersion(spfile, fileName, splist.ParentWebUrl)
                    {
                        Size = fileSize[spfile.UIVersionLabel]
                    }
                };
                result.AddRange(versions.Select(version => new SPDocumentVersion(version, fileName, splist.ParentWebUrl)
                {
                    Size = fileSize[version.VersionLabel]
                }));

                // pagination
                var versioning = new SPDocumentVersionList {
                    TotalCount = result.Count
                };
                int pageSize = 10;
                if (options != null && options["PageSize"] != null)
                {
                    int.TryParse(options["PageSize"].ToString(), out pageSize);
                }
                int pageIndex = 0;
                if (options != null && options["PageIndex"] != null)
                {
                    int.TryParse(options["PageIndex"].ToString(), out pageIndex);
                }
                int startIndex = pageIndex * pageSize;
                int count      = Math.Min(versioning.TotalCount - startIndex, pageSize);
                var comparer   = new SPDocumentVersionComparer();
                versioning.AddRange(result.OrderByDescending(item => item.VersionLabel, comparer).ToList().GetRange(startIndex, count));
                return(versioning);
            }
        }
        public IRestResponse List(SPUserOrGroupRequest request, bool onlyGroups = false, bool onlyUsers = false)
        {
            var response = new DefaultRestResponse
            {
                Name = "List"
            };

            var errors = new List <string>();

            ValidateUrl(request.Url, errors);
            if (errors.Any())
            {
                response.Errors = errors.ToArray();
                return(response);
            }

            string url       = request.Url;
            string search    = request.Search;
            int    pageSize  = request.PageSize > 0 ? request.PageSize : DefaultPageSize;
            int    pageIndex = request.PageIndex > 0 ? request.PageIndex : 0;

            response.Data = cacheService.Get(CacheKey(url, onlyGroups, onlyUsers, search, pageSize, pageIndex), CacheScope.Context | CacheScope.Process);
            if (response.Data == null)
            {
                try
                {
                    using (var clientContext = new SPContext(url, IntegrationManagerPlugin.CurrentAuth(url), runAsServiceAccount: true))
                    {
                        var web = clientContext.Web;
                        clientContext.Load(web, w => w.Id);

                        var site = clientContext.Site;
                        clientContext.Load(site, s => s.Id);

                        var query = CamlQuery.CreateAllItemsQuery(pageSize);
                        query.ViewXml = String.Concat("<View><Query>", ViewFieldsSection(RestSPUserOrGroup.ViewFields), WhereSection(search, onlyGroups, onlyUsers), "</Query></View>");

                        if (pageIndex > 0)
                        {
                            var tempListItems = web.SiteUserInfoList.GetItems(CamlQuery.CreateAllItemsQuery(pageSize * pageIndex));
                            clientContext.Load(tempListItems, itemsCollection => itemsCollection.ListItemCollectionPosition);
                            clientContext.ExecuteQuery();

                            query.ListItemCollectionPosition = tempListItems.ListItemCollectionPosition;
                        }

                        var siteUsersAndGroups = clientContext.LoadQuery(web.SiteUserInfoList.GetItems(query));
                        clientContext.ExecuteQuery();

                        response.Data = siteUsersAndGroups.Select(RestSPUserOrGroup.Get).ToArray();
                    }
                    cacheService.Put(CacheKey(url, onlyGroups, onlyUsers, search, pageSize, pageIndex), response.Data, CacheScope.Context | CacheScope.Process, new string[] { }, CacheTimeOut);
                }
                catch (Exception ex)
                {
                    string message = string.Format("An exception of type {0} occurred in the RESTApi.GroupsAndUsers.List() method for SPWebUrl: '{1}' Search: '{2}' OnlyGroups: {3} OnlyUsers: {4}. The exception message is: {5}", ex.GetType(), url, search, onlyGroups, onlyUsers, ex.Message);
                    SPLog.RoleOperationUnavailable(ex, message);

                    response.Errors = new[] { plugin.Translate(SharePointEndpoints.Translations.UnknownError) };
                }
            }
            return(response);
        }
Exemplo n.º 7
0
        public List <SPDocumentVersion> GetVersions(string url, Guid libraryId, int itemId)
        {
            var documentVersionList = new List <SPDocumentVersion>();

            try
            {
                var auth = credentials.Get(url);
                using (var clientContext = new SPContext(url, auth))
                {
                    var splist = clientContext.Web.Lists.GetById(libraryId);
                    clientContext.Load(splist, l => l.ParentWebUrl);

                    var splistItem = splist.GetItemById(itemId);
                    var spfile     = splistItem.File;
                    clientContext.Load(spfile);
                    clientContext.Load(spfile, i => i.ModifiedBy, i => i.TimeLastModified);

                    var versions = clientContext.LoadQuery(spfile.Versions.IncludeWithDefaultProperties(i => i.CreatedBy, i => i.IsCurrentVersion));

                    clientContext.ExecuteQuery();

                    // There is no way to get file size using Client Object Model
                    var fileSizePool = new Dictionary <string, int>();

                    using (var service = new VersionService(url, auth))
                    {
                        var nodeList = service.GetVersions(spfile.ServerRelativeUrl);
                        foreach (XmlNode node in nodeList.ChildNodes)
                        {
                            if (node.Name == "result")
                            {
                                if (node.Attributes != null)
                                {
                                    var version = node.Attributes["version"];
                                    var v       = version.Value.Replace("@", "");
                                    int size;
                                    int.TryParse(node.Attributes["size"].Value, out size);
                                    fileSizePool.Add(v, size);
                                }
                            }
                        }
                    }

                    documentVersionList.Add(new SPDocumentVersion(spfile, spfile.ServerRelativeUrl, splist.ParentWebUrl)
                    {
                        Size = fileSizePool[spfile.UIVersionLabel]
                    });
                    documentVersionList.AddRange(
                        versions
                        .OrderByDescending(v => v.VersionLabel, new SPDocumentVersionComparer())
                        .Select(version => new SPDocumentVersion(version, spfile.ServerRelativeUrl, splist.ParentWebUrl)
                    {
                        Size = fileSizePool[version.VersionLabel]
                    })
                        );
                }
            }
            catch (Exception ex)
            {
                var message = string.Format("An exception of type {0} occurred in the InternalApi.SPFileService.GetVersions() method for URL: {1}, LibraryId: {2}, ItemId: {3}. The exception message is: {4}", ex.GetType(), url, libraryId, itemId, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message);
            }
            return(documentVersionList);
        }