示例#1
0
 public SPDocumentCheckOutInfo GetFileInfo(SPList list, SPListItem listItem)
 {
     using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
     {
         var spList = clientContext.ToList(list.Id);
         var spfile = spList.GetItemById(listItem.Id).File;
         clientContext.Load(spList);
         clientContext.Load(spfile);
         clientContext.Load(spfile, f => f.CheckedOutByUser);
         clientContext.ExecuteQuery();
         User user = null;
         if (!spfile.CheckedOutByUser.ServerObjectIsNull.GetValueOrDefault(true))
         {
             user = spfile.CheckedOutByUser;
             clientContext.Load(user);
             clientContext.ExecuteQuery();
         }
         return(new SPDocumentCheckOutInfo
         {
             IsCheckedOut = !(spfile.CheckedOutByUser.ServerObjectIsNull ?? true),
             CheckedOutByUser = user,
             EnableVersioning = spList.EnableVersioning,
             EnableMinorVersions = spList.EnableMinorVersions,
             MajorVersion = spfile.MajorVersion,
             MinorVersion = spfile.MinorVersion
         });
     }
 }
        public void Remove(string url, Guid listId, AttachmentsRemoveQuery options)
        {
            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                ListItemCollection listItems = null;
                if (!options.Id.HasValue)
                {
                    listItems = clientContext.Web.Lists.GetById(listId).GetItems(CAMLQueryBuilder.GetItem(options.ContentId, new string[] { }));
                    clientContext.Load(listItems, _ => _.Include(item => item.Id));
                }

                var listRootFolder = clientContext.Web.Lists.GetById(listId).RootFolder;
                clientContext.Load(listRootFolder, f => f.ServerRelativeUrl);
                clientContext.ExecuteQuery();

                int listItemId = options.Id.HasValue ? options.Id.Value : listItems.First().Id;

                var attachmentsFolder = clientContext.Web.GetFolderByServerRelativeUrl(listRootFolder.ServerRelativeUrl + "/Attachments/" + listItemId);
                clientContext.Load(attachmentsFolder.Files);
                clientContext.ExecuteQuery();

                foreach (var file in attachmentsFolder.Files.ToList())
                {
                    if (options.FileNames.Contains(file.Name))
                    {
                        file.DeleteObject();
                    }
                }
                attachmentsFolder.Update();
                clientContext.ExecuteQuery();
            }
        }
示例#3
0
        public void ResetInheritance(PermissionsGetQuery options)
        {
            var spwebUrl = EnsureUrl(options.Url, options.ListId);

            try
            {
                using (var clientContext = new SPContext(spwebUrl, credentials.Get(spwebUrl)))
                {
                    List splist = clientContext.Web.Lists.GetById(options.ListId);
                    var  splistItemCollection = splist.GetItems(options.Id.HasValue ?
                                                                CAMLQueryBuilder.GetItem(options.Id.Value, new string[] { }) :
                                                                CAMLQueryBuilder.GetItem(options.ContentId, new string[] { }));

                    var lazyListItems = clientContext.LoadQuery(splistItemCollection.Include(item => item.HasUniqueRoleAssignments, item => item.Id));
                    clientContext.ExecuteQuery();

                    var splistItem = lazyListItems.First();
                    splistItem.ResetRoleInheritance();

                    clientContext.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
                string itemId  = options.Id.HasValue ? options.Id.Value.ToString(CultureInfo.InvariantCulture) : options.ContentId.ToString();
                string message = string.Format("An exception of type {0} occurred in the SPPermissionsService.ResetInheritance() method for ListId: {1} ItemId: {2}. The exception message is: {3}", ex.GetType(), options.ListId, itemId, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
        }
        public SP.FileCollection Attachments(SPListItem listItem, SPList list, object value)
        {
            if (value == null || !(bool)value)
            {
                return(null);
            }

            using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
            {
                SP.Web web = clientContext.Web;
                clientContext.Load(web);
                SP.List splist = clientContext.ToList(list.Id);
                clientContext.Load(splist);
                SP.ListItem splistItem = splist.GetItemById(listItem.Id);
                clientContext.Load(splistItem);
                clientContext.ExecuteQuery();

                SP.Folder listFolder = splistItem.ParentList.RootFolder;
                clientContext.Load(listFolder, f => f.ServerRelativeUrl);
                clientContext.ExecuteQuery();

                SP.Folder attachmentsFolder = web.GetFolderByServerRelativeUrl(listFolder.ServerRelativeUrl + "/attachments/" + splistItem.Id.ToString());
                clientContext.Load(attachmentsFolder);
                var attachments = attachmentsFolder.Files;
                clientContext.Load(attachments);
                clientContext.ExecuteQuery();

                return(attachments);
            }
        }
示例#5
0
        public SPView Get(
            [Documentation(Name = "List", Type = typeof(SPList)),
             Documentation(Name = "ById", Type = typeof(string)),
             Documentation(Name = "ByTitle", Type = typeof(string))]
            IDictionary options)
        {
            SPList list = null;

            if (options != null && options["List"] != null)
            {
                list = (SPList)options["List"];
            }
            else
            {
                return(null);
            }

            var byId    = (options["ById"] != null) ? options["ById"].ToString() : string.Empty;
            var byTitle = (options["ByTitle"] != null) ? options["ByTitle"].ToString() : string.Empty;

            using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
            {
                SP.List splist      = clientContext.ToList(list.Id);
                var     fieldsQuery = clientContext.LoadQuery(splist.Fields.Include(
                                                                  field => field.Title,
                                                                  field => field.InternalName));

                SP.View spview = null;

                if (!string.IsNullOrEmpty(byId))
                {
                    string viewId = options["ById"].ToString();
                    spview = splist.GetView(new Guid(viewId));
                    clientContext.Load(spview);
                    clientContext.Load(spview, SPView.InstanceQuery);
                    clientContext.ExecuteQuery();
                }

                if (spview == null && !string.IsNullOrEmpty(byTitle))
                {
                    string viewTitle = options["ByTitle"].ToString();
                    var    viewQuery = clientContext.LoadQuery(splist.Views
                                                               .Where(view => view.Title == viewTitle)
                                                               .IncludeWithDefaultProperties(SPView.InstanceQuery));
                    clientContext.ExecuteQuery();
                    spview = viewQuery.FirstOrDefault();
                }

                if (spview != null)
                {
                    return(new SPView(spview, fieldsQuery.ToDictionary(item => item.InternalName, item => item.Title)));
                }
            }

            return(null);
        }
        public void Add(string url, Guid listId, AttachmentsAddQuery options)
        {
            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                ListItemCollection listItems = null;
                if (!options.Id.HasValue)
                {
                    listItems = clientContext.Web.Lists.GetById(listId).GetItems(CAMLQueryBuilder.GetItem(options.ContentId, new string[] { }));
                    clientContext.Load(listItems, _ => _.Include(item => item.Id));
                }

                var listRootFolder = clientContext.Web.Lists.GetById(listId).RootFolder;
                clientContext.Load(listRootFolder, f => f.ServerRelativeUrl);
                clientContext.ExecuteQuery();

                int listItemId = options.Id.HasValue ? options.Id.Value : listItems.First().Id;

                Microsoft.SharePoint.Client.Folder attachmentsFolder;
                try
                {
                    attachmentsFolder = clientContext.Web.GetFolderByServerRelativeUrl(listRootFolder.ServerRelativeUrl + "/Attachments/" + listItemId.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
                    clientContext.Load(attachmentsFolder);
                    clientContext.ExecuteQuery();
                }
                catch
                {
                    attachmentsFolder = null;
                }

                // add
                var useService = (attachmentsFolder == null);
                if (useService)
                {
                    //There is no way to create attachments folder using client object model.
                    using (var service = new ListService(url, credentials.Get(url)))
                    {
                        service.AddAttachment(listId.ToString(), listItemId.ToString(CultureInfo.InvariantCulture), options.FileName, options.FileData);
                    }
                }
                else
                {
                    var fileUrl = string.Format("{0}/{1}", listRootFolder.ServerRelativeUrl + "/Attachments/" + listItemId.ToString(CultureInfo.InvariantCulture).ToLowerInvariant(), options.FileName);
                    if (options.FileData != null)
                    {
                        using (var stream = new MemoryStream(options.FileData))
                        {
                            Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, fileUrl, stream, true);
                        }
                        clientContext.ExecuteQuery();
                    }
                }
            }
        }
示例#7
0
        public Folder GetParent(string url, Guid libraryId, string folderPath)
        {
            if (string.IsNullOrEmpty(folderPath) || string.IsNullOrEmpty(folderPath.Trim('/')))
            {
                return(null);
            }

            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    SP.List splist = clientContext.Web.Lists.GetById(libraryId);

                    SP.Folder rootFolder = splist.RootFolder;
                    clientContext.Load(rootFolder, f => f.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    if (rootFolder.ServerRelativeUrl.Trim('/').Equals(folderPath.Trim('/'), StringComparison.InvariantCultureIgnoreCase))
                    {
                        // This is a root folder, so it has no parents
                        return(null);
                    }

                    var spfolder = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
                    clientContext.Load(spfolder, f => f.ServerRelativeUrl);
                    clientContext.Load(spfolder.ParentFolder, p => p.Name, p => p.ServerRelativeUrl, p => p.ItemCount);
                    clientContext.ExecuteQuery();

                    bool pathIsNotEmpty  = spfolder != null && !String.IsNullOrEmpty(spfolder.ServerRelativeUrl.Trim('/'));
                    bool isARootFolder   = spfolder == null || rootFolder.ServerRelativeUrl.Trim('/').Equals(spfolder.ServerRelativeUrl.Trim('/'));
                    bool hasParentFolder = pathIsNotEmpty && !isARootFolder;
                    if (!hasParentFolder)
                    {
                        return(null);
                    }

                    if (spfolder.ParentFolder != null)
                    {
                        return(new Folder(spfolder.ParentFolder.Name, spfolder.ParentFolder.ServerRelativeUrl, spfolder.ParentFolder.ItemCount, libraryId));
                    }
                    return(null);
                }
            }
            catch (Exception ex)
            {
                throw new SPInternalException(ex.Message, ex);
            }
        }
        public List <SPAttachment> List(string url, Guid listId, AttachmentsGetQuery options)
        {
            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                var site = clientContext.Site;
                clientContext.Load(site, s => s.Url);

                ListItemCollection listItems = null;
                if (!options.Id.HasValue)
                {
                    listItems = clientContext.Web.Lists.GetById(listId).GetItems(CAMLQueryBuilder.GetItem(options.ContentId, new string[] { }));
                    clientContext.Load(listItems, _ => _.Include(item => item.Id));
                }

                var listRootFolder = clientContext.Web.Lists.GetById(listId).RootFolder;
                clientContext.Load(listRootFolder, f => f.ServerRelativeUrl);
                clientContext.ExecuteQuery();

                try
                {
                    int listItemId = options.Id.HasValue ? options.Id.Value : listItems.First().Id;

                    var attachmentsFolder = clientContext.Web.GetFolderByServerRelativeUrl(listRootFolder.ServerRelativeUrl + "/Attachments/" + listItemId.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());
                    clientContext.Load(attachmentsFolder);
                    clientContext.Load(attachmentsFolder.Files,
                                       files => files.Include(
                                           f => f.ServerRelativeUrl,
                                           f => f.Name,
                                           f => f.Title,
                                           f => f.TimeCreated,
                                           f => f.Author,
                                           f => f.TimeLastModified,
                                           f => f.ModifiedBy));
                    clientContext.ExecuteQuery();
                    return(attachmentsFolder.Files.ToList().Select(attachment => new SPAttachment(attachment.Name, new Uri(site.Url + attachment.ServerRelativeUrl))
                    {
                        Created = attachment.TimeCreated,
                        Modified = attachment.TimeLastModified,
                        CreatedBy = new SPUserPrincipal(attachment.Author),
                        ModifiedBy = new SPUserPrincipal(attachment.ModifiedBy)
                    }).ToList());
                }
                catch
                {
                    return(new List <SPAttachment>());
                }
            }
        }
示例#9
0
        public void AddUserToGroup(string url, Authentication authentication, string loginNames, int groupId)
        {
            // Group Id is invalid
            if (groupId <= 0)
            {
                return;
            }

            using (var clientContext = new SPContext(url, authentication ?? credentials.Get(url)))
            {
                var group = clientContext.Web.SiteGroups.GetById(groupId);
                foreach (var loginName in loginNames.Split(','))
                {
                    var user = clientContext.Web.EnsureUser(loginName);
                    group.Users.AddUser(user);
                }
                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (ServerException ex)
                {
                    //User not found
                    SPLog.RoleOperationUnavailable(ex, String.Format("A server exception occurred while adding users to the group with id '{0}'. The exception message is: {1}", groupId, ex.Message));
                }
            }
        }
        public void Delete(Guid id, bool deleteList)
        {
            var list = listDataService.Get(id);

            if (list == null)
            {
                return;
            }

            Validate(list);

            listDataService.Delete(list.Id);
            if (deleteList)
            {
                try
                {
                    using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
                    {
                        var splist = clientContext.Web.Lists.GetById(list.Id);
                        splist.DeleteObject();
                        clientContext.ExecuteQuery();
                    }
                }
                catch (Exception ex)
                {
                    string message = string.Format("An exception of type {0} occurred in the InternalApi.SPListService.Delete() method for ApplicationId: {1}. The exception message is: {2}", ex.GetType(), id, ex.Message);
                    SPLog.RoleOperationUnavailable(ex, message);

                    throw new SPInternalException(message, ex);
                }
            }
        }
示例#11
0
        public bool IsSite()
        {
            try
            {
                using (var clientContext = new SPContext(siteUrl, auth, runAsServiceAccount: true))
                {
                    var web = clientContext.Web;
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();
                }
            }
            catch (ClientRequestException)
            {
                // site does not existed
                return(false);
            }
            catch (WebException)
            {
                // credentials are invalid
                return(false);
            }
            catch (Exception)
            {
                // unhandled exception
                return(false);
            }

            return(true);
        }
示例#12
0
        public List <string> LoadSubSiteUrls()
        {
            var webCollection = new List <string>();

            using (var clientContext = new SPContext(siteUrl, auth, runAsServiceAccount: true))
            {
                var webs = clientContext.Web.Webs;
                clientContext.Load(webs);

                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    SPLog.UnKnownError(ex, "An exception in the process of SiteCollection loading of type {0} has been occurred. The exception message is: {1}", ex.GetType().Name, ex.Message);
                    return(webCollection);
                }

                var baseUrl = clientContext.Url.Trim('/');

                foreach (var web in webs)
                {
                    webCollection.Add(MergeUrl(baseUrl, web.ServerRelativeUrl));
                }
            }

            return(webCollection);
        }
示例#13
0
        public Folder Get(string url, Guid libraryId, string folderPath)
        {
            Folder folder;

            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    var spfolder = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
                    clientContext.Load(spfolder, f => f.Name, f => f.ServerRelativeUrl, f => f.ItemCount);

                    clientContext.ExecuteQuery();

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

                throw new SPInternalException(message, ex);
            }
            return(folder);
        }
示例#14
0
        public void CheckIn(string url, Guid libraryId, int itemId, FileCheckInOptions options)
        {
            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    var spfile = clientContext.Web.Lists.GetById(libraryId).GetItemById(itemId).File;
                    var type   = !string.IsNullOrEmpty(options.CheckinType) ? (CheckinType)Enum.Parse(typeof(CheckinType), options.CheckinType) : CheckinType.MajorCheckIn;

                    spfile.CheckIn(options.Comment, type);

                    if (options.KeepCheckOut)
                    {
                        spfile.CheckOut();
                    }

                    clientContext.ExecuteQuery();
                }
            }
            catch (Exception ex)
            {
                var message = string.Format("An exception of type {0} occurred in the InternalApi.SPFileService.CheckIn() 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);
            }
        }
        public bool IsFolderValid(string url, Guid listId, string folderName, string currentDir)
        {
            folderName = folderName.Trim();
            if (String.IsNullOrEmpty(folderName))
            {
                return(false);
            }

            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                SP.Folder parentFolder = clientContext.Web.GetFolderByServerRelativeUrl(currentDir);
                clientContext.Load(parentFolder);
                var subfolders = clientContext.LoadQuery(parentFolder.Folders.Where(folder => folder.Name == folderName));
                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    SPLog.FileNotFound(ex, "Coult not load subfolders for a directory '{0}'", currentDir);
                    return(false);
                }

                return(subfolders.Any());
            }
        }
        public SP.Folder NewFolder(string url, Guid listId, string folderName, string currentDir)
        {
            if (!IsFolderValid(url, listId, folderName, currentDir))
            {
                return(null);
            }

            using (var clientContext = new SPContext(url, credentials.Get(url)))
            {
                SP.Folder parentFolder = clientContext.Web.GetFolderByServerRelativeUrl(currentDir);
                clientContext.Load(parentFolder);

                // add a new folder
                SP.Folder newFolder = parentFolder.Folders.Add(folderName);
                parentFolder.Update();
                clientContext.Load(newFolder);
                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    SPLog.FileNotFound(ex, "Error occurred while creating a new folder with a name '{0}' for a directory '{1}'.", folderName, currentDir);
                    return(null);
                }

                CacheService.RemoveByTags(new[] { Documents.Tag(listId), Folders.Tag(listId) }, CacheScope.All);

                return(newFolder);
            }
        }
示例#17
0
        private OAuthData GetUserData()
        {
            //We now have the credentials, so we can start making API calls
            using (var context = new SPContext(Office365Url, new Components.AuthenticationUtil.Methods.OAuth()))
            {
                var userDetails = context.Web.CurrentUser;

                context.Load(userDetails,
                             usr => usr.Email,
                             usr => usr.Id,
                             usr => usr.LoginName,
                             usr => usr.Title,
                             usr => usr.UserId);

                context.ExecuteQuery();

                var uid  = userDetails.Id.ToString(CultureInfo.InvariantCulture);
                var data = new OAuthData
                {
                    ClientId   = uid,
                    ClientType = ClientType,
                    Email      = userDetails.Email,
                    UserName   = SanitizeUserName(userDetails.LoginName),
                    AvatarUrl  = string.Empty,
                    CommonName = userDetails.Title
                };

                return(data);
            }
        }
        public int GetWSSId(string url, string label)
        {
            using (var context = new SPContext(url, credentials.Get(url)))
            {
                try
                {
                    var taxonomyList = context.Web.Lists.GetByTitle("TaxonomyHiddenList");
                    var taxItems     = taxonomyList.GetItems(CAMLQueryBuilder.GetItemByTitle(label, new[] { "Title", "ID" }));
                    context.Load(taxItems);

                    context.ExecuteQuery();

                    if (taxItems.Any())
                    {
                        return(taxItems[0].Id);
                    }
                }
                catch (Exception ex)
                {
                    SPLog.UnKnownError(ex, ex.Message);
                }
            }

            return(-1);
        }
示例#19
0
        public void Restore(string url, Guid libraryId, int itemId, string version)
        {
            try
            {
                var auth = credentials.Get(url);
                using (var clientContext = new SPContext(url, auth))
                {
                    var spfile = clientContext.Web.Lists.GetById(libraryId).GetItemById(itemId).File;
                    clientContext.Load(spfile, f => f.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    var fileName = spfile.ServerRelativeUrl;
                    // There is no way to restore file using Client Object Model
                    using (var service = new VersionService(url, auth))
                    {
                        service.RestoreVersion(fileName, version);
                    }
                }
            }
            catch (Exception ex)
            {
                var message = string.Format("An exception of type {0} occurred in the InternalApi.SPFileService.Restore() method for URL: {1}, LibraryId: {2}, ItemId: {3}, Version: {4}. The exception message is: {5}", ex.GetType(), url, libraryId, itemId, version, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message);
            }
        }
示例#20
0
        private Folder CreateFolder(List list, string folderName)
        {
            ListItem newItem = null;

            try
            {
                ListItemCreationInformation info = new ListItemCreationInformation();

                info.UnderlyingObjectType = FileSystemObjectType.Folder;
                info.LeafName             = folderName.Trim();//Trim for spaces.Just extra check

                newItem = list.AddItem(info);

                newItem["Title"] = folderName;
                newItem.Update();

                SPContext.ExecuteQuery();
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
            }

            return(newItem == null ? null : newItem.Folder);
        }
        public SP.Folder NewFolder(SPList list, string folderName, string currentDir)
        {
            if (!IsFolderValid(list, folderName, currentDir))
            {
                return(null);
            }

            using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
            {
                SP.List   splist       = clientContext.ToList(list.Id);
                SP.Folder parentFolder = clientContext.Web.GetFolderByServerRelativeUrl(currentDir);
                clientContext.Load(parentFolder);

                // add a new folder
                SP.Folder newFolder = parentFolder.Folders.Add(folderName);
                parentFolder.Update();
                clientContext.Load(newFolder);
                try
                {
                    clientContext.ExecuteQuery();
                }
                catch (Exception ex)
                {
                    EventLogs.Warn(String.Format("An exception of type {0} occurred while creating a new folder with a name '{1}' for a directory '{2}'. The exception message is: {3}", ex.GetType().Name, folderName, currentDir, ex.Message), "SharePointClient", 778, CSContext.Current.SettingsID);
                    return(null);
                }

                cacheService.RemoveByTags(new[] { GetTag(list.Id) }, CacheScope.Context | CacheScope.Process);
                return(newFolder);
            }
        }
        public List <User> List(IEnumerable <string> emails)
        {
            var userList = new List <User>();

            SP.Web web = spcontext.Site.RootWeb;
            foreach (string camlQuery in CamlQueryBuilder(emails.ToArray(), userProfileBatchCapacity, syncSettings.SPUserEmailFieldName))
            {
                SP.ListItemCollection spuserCollection = web.SiteUserInfoList.GetItems(new CamlQuery {
                    ViewXml = camlQuery
                });
                spcontext.Load(spuserCollection);
                spcontext.ExecuteQuery();
                InitUserList(spuserCollection, userList);
            }
            return(userList);
        }
 public bool IsFolderValid(SPList list, string folderName, string currentDir)
 {
     folderName = folderName.Trim();
     if (String.IsNullOrEmpty(folderName))
     {
         return(false);
     }
     using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
     {
         SP.List   splist       = clientContext.ToList(list.Id);
         SP.Folder parentFolder = clientContext.Web.GetFolderByServerRelativeUrl(currentDir);
         clientContext.Load(parentFolder);
         var subfolders = clientContext.LoadQuery(parentFolder.Folders.Where(folder => folder.Name == folderName));
         try
         {
             clientContext.ExecuteQuery();
         }
         catch (Exception ex)
         {
             EventLogs.Warn(String.Format("An exception of type {0} occurred while loading subfolders for a directory '{1}'. The exception message is: {2}", ex.GetType().Name, currentDir, ex.Message), "SharePointClient", 778, CSContext.Current.SettingsID);
             return(false);
         }
         // subfolders.Count()>0 means, that the folder already exists
         return(!subfolders.Any());
     }
 }
        public bool CanEdit(Guid listId)
        {
            var listBase = listDataService.Get(listId);

            if (listBase == null)
            {
                return(false);
            }

            Validate(listBase);

            try
            {
                bool?canEdit;
                using (var spcontext = new SPContext(listBase.SPWebUrl, credentials.Get(listBase.SPWebUrl)))
                {
                    var splist = spcontext.Web.Lists.GetById(listId);
                    spcontext.Load(splist, l => l.EffectiveBasePermissions);
                    spcontext.ExecuteQuery();
                    canEdit = splist.EffectiveBasePermissions.Has(PermissionKind.EditListItems);
                }
                return(canEdit.Value);
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the InternalApi.SPListService.CanEdit() method for ApplicationId: {1}. The exception message is: {2}", ex.GetType(), listId, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
        }
示例#25
0
 public ApiList <SPView> List(SPList list)
 {
     using (var clientContext = new SPContext(list.SPWebUrl, credentials.Get(list.SPWebUrl)))
     {
         SP.ViewCollection viewCollection = clientContext.ToList(list.Id).Views;
         var     views       = clientContext.LoadQuery(viewCollection.Include(SPView.InstanceQuery));
         SP.List splist      = clientContext.ToList(list.Id);
         var     fieldsQuery = clientContext.LoadQuery(splist.Fields.Include(
                                                           field => field.Title,
                                                           field => field.InternalName));
         clientContext.Load(splist,
                            _list => _list.ContentTypes.Include(ct => ct.Fields.SchemaXml),
                            _list => _list.SchemaXml);
         clientContext.ExecuteQuery();
         var spviewCollection = new ApiList <SPView>();
         var columns          = fieldsQuery.ToDictionary(item => item.InternalName, item => item.Title);
         foreach (var view in views)
         {
             if (!view.Hidden)
             {
                 spviewCollection.Add(new SPView(view, columns));
             }
         }
         return(spviewCollection);
     }
 }
示例#26
0
        public SPPermissions Get(int userOrGroupId, PermissionsGetQuery options)
        {
            var spwebUrl = EnsureUrl(options.Url, options.ListId);

            try
            {
                using (var clientContext = new SPContext(spwebUrl, credentials.Get(spwebUrl)))
                {
                    List splist = clientContext.Web.Lists.GetById(options.ListId);
                    var  splistItemCollection = splist.GetItems(options.Id.HasValue ?
                                                                CAMLQueryBuilder.GetItem(options.Id.Value, new string[] { }) :
                                                                CAMLQueryBuilder.GetItem(options.ContentId, new string[] { }));

                    var listItemRoleAssignments = clientContext.LoadQuery(
                        splistItemCollection.Select(item => item.RoleAssignments.GetByPrincipalId(userOrGroupId)).Include(
                            roleAssignment => roleAssignment.Member,
                            roleAssignment => roleAssignment.RoleDefinitionBindings.Include(
                                roleDef => roleDef.Id,
                                roleDef => roleDef.Name,
                                roleDef => roleDef.Description)));

                    clientContext.ExecuteQuery();

                    return(listItemRoleAssignments.First().ToPermission());
                }
            }
            catch (Exception ex)
            {
                string itemId  = options.Id.HasValue ? options.Id.Value.ToString(CultureInfo.InvariantCulture) : options.ContentId.ToString();
                string message = string.Format("An exception of type {0} occurred in the SPPermissionsService.Get() method for a User or Group with Id: {1} ListId: {2} ItemId: {3}. The exception message is: {4}", ex.GetType(), userOrGroupId, options.ListId, itemId, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
        }
示例#27
0
        public List <SPPermissionsLevel> Levels(string webUrl)
        {
            var levels = new List <SPPermissionsLevel>();

            try
            {
                using (var clientContext = new SPContext(webUrl, credentials.Get(webUrl)))
                {
                    var web = clientContext.Web;
                    clientContext.Load(web,
                                       w => w.RoleDefinitions.Include(
                                           rd => rd.Id,
                                           rd => rd.Name,
                                           rd => rd.Description));
                    clientContext.ExecuteQuery();

                    foreach (var rd in web.RoleDefinitions)
                    {
                        levels.Add(new SPPermissionsLevel(rd.Id, rd.Name)
                        {
                            Description = rd.Description
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the SPPermissionsService.Levels() method for SPWebUrl: {1}. The exception message is: {2}", ex.GetType(), webUrl, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
            return(levels);
        }
示例#28
0
        public List <Folder> List(string url, Guid libraryId, string folderPath)
        {
            var folderList = new List <Folder>();

            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    var list       = clientContext.Web.Lists.GetById(libraryId);
                    var rootFolder = list.RootFolder;
                    clientContext.Load(rootFolder, f => f.ServerRelativeUrl);

                    var spfolder         = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
                    var folderCollection = clientContext.LoadQuery(SP.ClientObjectQueryableExtension.Include(spfolder.Folders, f => f.Name, f => f.ServerRelativeUrl, f => f.ItemCount));

                    clientContext.ExecuteQuery();

                    folderList.AddRange(from f in folderCollection
                                        where !IsHiddenFolder(f.ServerRelativeUrl, rootFolder.ServerRelativeUrl)
                                        select new Folder(f.Name, f.ServerRelativeUrl, f.ItemCount, libraryId));
                }
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the InternalApi.SPFolderService.List() method LibraryId: {1} ServerRelativeUrl: '{2}' SPWebUrl: '{3}'. The exception message is: {4}", ex.GetType(), libraryId, folderPath, url, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
            return(folderList);
        }
示例#29
0
        public Folder Delete(string url, Guid libraryId, string folderPath)
        {
            Folder folder;

            try
            {
                using (var clientContext = new SPContext(url, credentials.Get(url)))
                {
                    SP.List splist = clientContext.Web.Lists.GetById(libraryId);

                    SP.Folder rootFolder = splist.RootFolder;
                    clientContext.Load(rootFolder, f => f.ServerRelativeUrl);

                    SP.Folder spfolder = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
                    clientContext.Load(spfolder, f => f.Name, f => f.ServerRelativeUrl, f => f.ItemCount);

                    clientContext.ExecuteQuery();

                    bool pathIsNotEmpty  = !String.IsNullOrEmpty(spfolder.ServerRelativeUrl.Trim('/'));
                    bool isARootFolder   = rootFolder.ServerRelativeUrl.Trim('/').Equals(spfolder.ServerRelativeUrl.Trim('/'));
                    bool hasParentFolder = pathIsNotEmpty && !isARootFolder;
                    if (hasParentFolder && !IsHiddenFolder(spfolder.ServerRelativeUrl, rootFolder.ServerRelativeUrl))
                    {
                        folder = new Folder(spfolder.Name, spfolder.ServerRelativeUrl, spfolder.ItemCount, libraryId);

                        spfolder.DeleteObject();
                        clientContext.ExecuteQuery();
                    }
                    else
                    {
                        throw new SPInternalException("Folder can not be removed.");
                    }
                }
            }
            catch (SPInternalException)
            {
                throw;
            }
            catch (Exception ex)
            {
                string message = string.Format("An exception of type {0} occurred in the InternalApi.SPFolderService.Delete() method LibraryId: {1} ServerRelativeUrl: '{2}' in SPWebUrl: '{3}'. The exception message is: {4}", ex.GetType(), libraryId, folderPath, url, ex.Message);
                SPLog.RoleOperationUnavailable(ex, message);

                throw new SPInternalException(message, ex);
            }
            return(folder);
        }
        internal static SPConfiguration Get(string url, Authentication auth)
        {
            var config = new SPConfiguration(url, auth);

            using (var spcontext = new SPContext(url, auth))
            {
                try
                {
                    SP.Web web = spcontext.Site.RootWeb;
                    var    siteProfileFieldsQuery = spcontext.LoadQuery(web.SiteUserInfoList.Fields).Where(f => !f.Hidden);

                    spcontext.ExecuteQuery();
                    config.SiteProfileFields = siteProfileFieldsQuery.Select(f => new ProfileField(f.StaticName, f.Title, !f.ReadOnlyField)).OrderBy(f => f.Title).ToList();

                    spcontext.Load(web.AllProperties,
                                   prop => prop[SPWebPropertyKey.SyncEnabled],
                                   prop => prop[SPWebPropertyKey.SiteSettings],
                                   prop => prop[SPWebPropertyKey.FarmSettings],
                                   prop => prop[SPWebPropertyKey.FarmSyncEnabled]);

                    spcontext.ExecuteQuery();
                    ParseWebProperties(web, config);
                }
                catch (Exception)
                {
                    SPLog.Info("Profile Sync properites do not exist in SharePoint. These are optional fields, no action is required.");
                }
            }

            config.FarmProfileFields = new List <ProfileField>();
            using (var userProfileService = new ProfileService(url, auth))
            {
                try
                {
                    var properties = userProfileService.GetUserProfileSchema();
                    foreach (var property in properties.OrderBy(p => p.DisplayName))
                    {
                        config.FarmProfileFields.Add(new ProfileField(property.Name, property.DisplayName, property.IsUserEditable));
                    }
                }
                catch (Exception ex)
                {
                    SPLog.RoleOperationUnavailable(ex, ex.Message);
                }
            }
            return(config);
        }